views:

412

answers:

1

Im constantly getting "bad decrypt" whilst trying to unencrypt a string from a c# program using the same iv on both sides. This is getting a bit annoying and I cant really figure out the problem.

This is the ruby code

def unencrypt(message) 

c = OpenSSL::Cipher::Cipher.new("aes-256-cbc") c.padding = 1 c.decrypt c.key = key = Digest::SHA1.hexdigest("mytestiv1111111111111111111111111").unpack('a2'*32).map{|x| x.hex}.pack('c'*32) c.iv = iv = key e = c.update(Base64.decode64(message)) e << c.final puts e end

And this is what does the encryption on the c# side

 public string  encrypt(string text, //the text to be encrypt

string password,// the encryption key int cipherindex//The strength of the encryption ) { try {
//get the cipher strength--from cipherindex CipherKey Key=CipherKey.getCipherKey(cipherindex); //build and init the Encryptor RijndaelManaged rijndaelCipher = new RijndaelManaged(); rijndaelCipher.Mode = sCipherMode; rijndaelCipher.Padding = sPaddingMode; rijndaelCipher.KeySize = Key.Size; rijndaelCipher.BlockSize =Key.Size; byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(password); byte[] keyBytes = new byte[Key.Len]; int len= pwdBytes.Length; if (len > keyBytes.Length) len= keyBytes.Length; System.Array.Copy(pwdBytes,keyBytes,len); rijndaelCipher.Key = keyBytes; rijndaelCipher.IV = keyBytes; ICryptoTransform transform = rijndaelCipher.CreateEncryptor();

byte [] plainText = System.Text.Encoding.UTF8.GetBytes(text);
byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
return Convert.ToBase64String(cipherBytes);

} catch (Exception e) { throw; }

}

Any ideas? Cheers David

A: 

Your keys look totally different to me,

  1. In Ruby, you use SHA1 to derive the key.
  2. In C#, the password is used raw.

Dump binary key buffers on both platform to make sure they are identical. Then, you just clean your first hurdle :)

ZZ Coder