How to input string for encryption using arc4?

936 views Asked by At

I was using the Crypto++ library to do my arc4 encryption. Reference from here but not fully explained: http://www.cryptopp.com/wiki/Stream_Cipher.

The following is my code:

string key = "key";
string msg = "hello";

ARC4 arc4((byte*)key.c_str(), sizeof((byte*)key.c_str()));

arc4.ProcessData((byte*)msg.c_str(), (byte*)msg.c_str(), sizeof((byte*)msg.c_str()));
arc4.ProcessData((byte*)msg.c_str(), (byte*)msg.c_str(), sizeof((byte*)msg.c_str()));

cout << msg << endl;

My message after encrypt and decrypt which is totally garbage then i could not read. not decrypted back to "hello" in short.

So how can I encrypt and decrypt message with key as above?

1

There are 1 answers

0
jww On BEST ANSWER

Two problems. First, you need to use the string's size(), and not sizeof(). Second, you need to reset the arc4 object when decrypting. Otherwise, the cipher's state is continued from the previous encryption.

string key = "key";
string msg = "hello";

ARC4 arc4((byte*)key.data(), key.size());
arc4.ProcessData((byte*)msg.data(), (byte*)msg.data(), msg.size());

// Reset state
arc4.SetKey((byte*)key.data(), key.size());
arc4.ProcessData((byte*)msg.data(), (byte*)msg.data(), msg.size());

cout << msg << endl;