如何从C#中以ruby解密此RijandelManaged? [英] How do I decrypt this RijandelManaged in ruby, from C#?
问题描述
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;
}
很明显,密钥和iv已更改为所有一个"以保护罪名.
Obviously the key and iv have been changed to all "ones" to protect the guilty.
我在这里尝试了其他几篇SO文章,但无济于事.
I have tried several other SO article on here but to no avail.
我以为我会继续展示我尝试使用的ruby openssl代码:
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
推荐答案
默认情况下,Ruby的OpenSSL模块似乎使用PKCS5类型填充( http://www.ruby-doc.org/stdlib-1.9.3/libdoc/openssl/rdoc/OpenSSL/PKCS7.html ).就个人而言,由于加密是如此挑剔,所以我喜欢手动设置每个选项,而不是默认设置,即使我使用默认设置只是为了确保两端相同.我之前使用C#/PHP完成了此操作,请查看我的文章以查看是否完全有帮助(
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.
这篇关于如何从C#中以ruby解密此RijandelManaged?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!