Reputation: 4607
I'm making an application that writes a small txt file containing 3 strings then loads them back into the application in a list widget.
This all works fine, but now I want to make it so that the txt file is not in plain text. I don't need any complicated cipher or anything that needs a key to encrypt and decrypt. I just simply want to be able to encrypt it on saving (saves a document that isn't in plain text) and decrypt it before it loads it back into the lost widget.
Below is my code for writing to and reading from the txt file. I'd just like to rework this so it's not plain text nothing else and I don't care that its not secure just not plain text
QFile m_file("mytext.txt");
m_file.open(QFile::WriteOnly | QFile::Append);
QTextStream m_stream(&m_file);
m_stream << ui->txt_1->text() + " " + ui->txt_2->text() + " " + ui->txt_3->text() <<;
m_file.close();
QFile n_file("mytext.txt");
n_file.open(QFile::ReadOnly);
QTextStream n_stream(&n_file);
int i=0;
while (!n_stream.atEnd())
{
ui->listWidget->addItem(n_stream.readLine());
i++;
}
Upvotes: 1
Views: 3198
Reputation: 704
I assume from your question and comments, you do not want to any external library to achieve this simple task. Here are the alternatives:
1- Use own encrypt/decrypt function. Then, simply, call encrypt function when writing, call decrypt function when reading. Here are usable code for this purpose. (Same function used for enc/dec, little hacky)
string encryptDecrypt(string toEncrypt) {
char key[3] = {'K', 'C', 'Q'}; //Any chars will work, in an array of any size
string output = toEncrypt;
for (int i = 0; i < toEncrypt.size(); i++)
output[i] = toEncrypt[i] ^ key[i % (sizeof(key) / sizeof(char))];
return output;
}
int main(int argc, const char * argv[])
{
string encrypted = encryptDecrypt("kylewbanks.com");
cout << "Encrypted:" << encrypted << "\n";
string decrypted = encryptDecrypt(encrypted);
cout << "Decrypted:" << decrypted << "\n";
return 0;
}
2- To absolute security and more standard code use a cipher algorithm. Best way to using a cipher algorithm is selecting a state-of-the-art crypto library like Crypto++ or Qt Cryptographic Architecture (QCA).
Choice is yours.
Upvotes: 1
Reputation: 340
Maybe?
void cyptStr(char *str){
if(!str){
return;
}
char *end = str + (strlen(str) - 1);
for(;str < end;str++){
if (*str != ' ')
*str ^= 1;
}
}
void ucyptStr(char *str){
if(!str){
return;
}
char *end = str + (strlen(str) - 1);
for(;str < end;str++){
if (*str != ' ')
*str ^= 1;
}
}
Upvotes: 1
Reputation: 8975
I know you do not want to hear this, but encryption is something you do not want to do yourself. The easiest really is to use a good library for this, such as Crypto++.
If you really feel the need to do something yourself, the Vignère cipher is a very simple algorithm to code, but also very simple to break.
Upvotes: 1