Signed/unsigned issue, now with more broken-ness!
So, I'm working on a bit of code to implement the (A)RC4 algorithm, for no reason other than for fun. My problem (please be kind - I know there are several issues with the code) is that, for some reason, the encryption algorithm likes to output signed ints. For example, if the plaintext input is "Hello." and the key is "1234" I get the following output:
4d 2c 1d ffffffc3 ffffff9c ffffffc2
I'm sure I'm missing a cast or something, but I'm completely lost. Any help would be fantastic.
Code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string Encrypt(const string &plaintext, const unsigned int text_length, const string &key, const unsigned int key_length);
int main()
{
string plaintext, cyphertext, key;
cout << "Enter string to be encrypted/decrypted: ";
getline(cin, plaintext, '\n');
unsigned int text_length(plaintext.length());
cout << "Enter encryption key: ";
getline(cin, key, '\n');
unsigned int key_length(key.length());
cyphertext = Encrypt(plaintext, text_length, key, key_length);
for(unsigned int i = 0; i < text_length; ++i)
cout << hex << static_cast<unsigned int>(cyphertext.at(i)) << " ";
return 0;
}
string Encrypt(const string &plaintext, const unsigned int text_length, const string &key, const unsigned int key_length)
{
unsigned int i(0);
unsigned int j(0);
unsigned int k(0);
vector<unsigned int> S(256, 0);
string cyphertext;
//BEGIN KEY-SCHEDULING ALGORITHM
for(i = 0; i < 256; ++i)
{
S.at(i) = i; //initialize s-box S[0] = 0...S[255] = 255
}
for(i = 0; i < 256; ++i)
{
//transpose s-box values based on key
j = (j + S.at(i) + key.at(i % key_length)) % 256;
swap(S.at(i), S.at(j));
}
//END KEY-SCHEDULING ALGORITHM
//BEGIN PSEUDO-RANDOM GENORATION ALGORITHM
for(i = 0, j = 0; i < text_length; ++i)
{
//transpose s-box values based on s-box values
j = (j + 1) % 256;
k = (k + S.at(j)) % 256;
swap(S.at(j), S.at(k));
//encryption happens here
cyphertext += plaintext.at(i) ^ (S.at((S.at(j) + S.at(k)) % 256));
}
//END PSEUDO-RANDOM GENORATION ALGORITHM
return cyphertext;
}