I need to encrypt a text string in a .net application using a known text key, and then decrypt it in Ruby using the same known key...however I'm having trouble making this happen. I think it has to do with string encoding issues. .Net to Ruby RC4 examples have proven to be elusive.
I'm receiving and invalid decryption on the Ruby side. The encryption/decryption works fine on the .net implementation. But when I copy the encrypted value over to the Ruby implementation and use the same key, I don't get my original value.
Below is my .net RC4 implementation (this does not require the highest level of security, but some is nice) :)
On the ruby side I'm using ruby-rc4 https://github.com/caiges/Ruby-RC4
public string keytext = "thisismykey";
public Form1()
{
InitializeComponent();
}
public void RC4(ref Byte[] bytes, Byte[] key)
{
Byte[] s = new Byte[256];
Byte[] k = new Byte[256];
Byte temp;
int i, j;
for (i = 0; i < 256; i++)
{
s[i] = (Byte)i;
k[i] = key[i % key.GetLength(0)];
}
j = 0;
for (i = 0; i < 256; i++)
{
j = (j + s[i] + k[i]) % 256;
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
i = j = 0;
for (int x = 0; x < bytes.GetLength(0); x++)
{
i = (i + 1) % 256;
j = (j + s[i]) % 256;
temp = s[i];
s[i] = s[j];
s[j] = temp;
int t = (s[i] + s[j]) % 256;
bytes[x] ^= s[t];
}
}
static byte[] GetBytes(string str)
{
Byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
private void button1_Click(object sender, EventArgs e)
{
Byte[] content = Encoding.ASCII.GetBytes(textBox1.Text);
RC4(ref content, Encoding.ASCII.GetBytes(keytext));
textBox2.Text = Encoding.ASCII.GetString(content);
RC4(ref content, Encoding.ASCII.GetBytes(keytext));
label1.Text = Encoding.ASCII.GetString(content);
}
The problem is likely occurring because ASCII encoding is 7-bit and has trouble recreating characters for values above 127. Try encoding with UTF-8 or convert the byte array to a Base64 string.