1

在尝试使用双方相同的 iv 从 ac# 程序中解密字符串时,我不断得到“错误解密”。这有点烦人,我无法真正找出问题所在。

这是红宝石代码

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

这就是c#端的加密

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;
    }

}

有任何想法吗?干杯大卫

4

1 回答 1

1

你的钥匙在我看来完全不同,

  1. 在 Ruby 中,您使用 SHA1 来派生密钥。
  2. 在 C# 中,密码是原始使用的。

在两个平台上转储二进制密钥缓冲区以确保它们相同。然后,您只需清除您的第一个障碍 :)

于 2009-08-29T00:46:04.457 回答