问题
static byte[] keyBytes = new byte[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1
};
static byte[] iv = new byte[] { 1, 1, 1, 1 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
static SymmetricAlgorithm getKey()
{
RijndaelManaged key = new RijndaelManaged();
key.Key = keyBytes;
key.IV = iv;
return key;
}
static string Encrypt(string PlainText)
{
SymmetricAlgorithm key = getKey();
MemoryStream ms = new MemoryStream();
CryptoStream encStream = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(encStream);
sw.WriteLine(PlainText);
sw.Close();
encStream.Close();
byte[] buffer = ms.ToArray();
ms.Close();
return Convert.ToBase64String(buffer);
}
static string Decrypt(string encrypted)
{
SymmetricAlgorithm key = getKey();
byte[] CypherText = Convert.FromBase64String(encrypted);
MemoryStream ms = new MemoryStream(CypherText);
CryptoStream encStream = new CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read);
StreamReader sr = new StreamReader(encStream);
string val = sr.ReadLine();
sr.Close();
encStream.Close();
ms.Close();
return val;
}
Obviously the key and iv have been changed to all "ones" to protect the guilty.
I have tried several other SO article on here but to no avail.
I thought i'd go ahead and show the ruby openssl code i'm trying to use:
def Crypt.decrypt(encrypted_data, key, iv, cipher_type)
aes = OpenSSL::Cipher::Cipher.new(cipher_type)
aes.decrypt
#aes.padding = 1
aes.key = key
aes.iv = iv if iv != nil
aes.update(encrypted_data) + aes.final
end
回答1:
It appears that the OpenSSL module for Ruby uses PKCS5 type padding by default (http://www.ruby-doc.org/stdlib-1.9.3/libdoc/openssl/rdoc/OpenSSL/Cipher.html). But the Microsoft Rj-Managed uses PKCS7 as default. PKCS7 is supported in the Ruby module, so you may just want to stick with that (http://www.ruby-doc.org/stdlib-1.9.3/libdoc/openssl/rdoc/OpenSSL/PKCS7.html). Personally, since encryption is so finicky, I like to manually set every option rather than go by the default, even if I am using the default setting just to make sure they are the same on both ends. I've done this before with C#/PHP, check out my post to see if that helps at all (C# Encryption to PHP Decryption) my completed solution is posted as the second answer.
来源:https://stackoverflow.com/questions/12610647/how-do-i-decrypt-this-rijandelmanaged-in-ruby-from-c