使用C#和OpenSSL命令创建兼容的AES-256-CBC代码

时间:2016-10-24 10:40:13

标签: c# encryption openssl aes

我在Linux终端中使用OpenSSL进行编码时遇到问题,而在C#中使用.net Cryptography进行编码时遇到问题。

当我使用时:

openssl enc -A -aes-256-cbc -base64 -K b14f636c88ba3dad57d53a8fab09dd95512ce1b545bbb93362113487e73a13fe -iv e43f2a549d05132fe2efe555edbd42a0 <<< "Ala ma kota. Kot ma, ale... to jednak ona go posiada. Jednakże gdy przeczytamy to ponownie to..."

返回

+xD6VmtDUqiwpGsOYDNajofvMdS8F1eYkK50l+dsuqdgr6bUf2xWSwdEifd96A5h/yM2bIxdWeWM5+4eCCitDjh+qZDj32rJS0fpV/q08hhfNltWdWxJhVezcuIAV3VZa/MhqBICBW0kagAcSy6Y6g==

我的C#代码是:

public static byte[] GetByteArrayFromStringHex(string HexString)
{
    int NumberChars = HexString.Length;
    byte[] bytes = new byte[NumberChars / 2];
    for (int i = 0; i < NumberChars; i += 2)
        bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);
    return bytes;
}
public static void EncryptTest()
{
    string key = "b14f636c88ba3dad57d53a8fab09dd95512ce1b545bbb93362113487e73a13fe";
    string iv = "e43f2a549d05132fe2efe555edbd42a0";
    string mess = "Ala ma kota. Kot ma, ale... to jednak ona go posiada. Jednakże gdy przeczytamy to ponownie to...";
    RijndaelManaged myAes = new RijndaelManaged();
    myAes.KeySize = 256;
    myAes.BlockSize = 128;
    myAes.Padding = PaddingMode.PKCS7;
    myAes.Mode = CipherMode.CBC;
    var enrypt = myAes.CreateEncryptor(GetByteArrayFromStringHex(key), GetByteArrayFromStringHex(iv));
    byte[] byteInput = Encoding.UTF8.GetBytes(mess);
    DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
    var memStream = new MemoryStream();
    CryptoStream cryptoStream = new CryptoStream(memStream, enrypt, CryptoStreamMode.Write);
    cryptoStream.Write(byteInput, 0, byteInput.Length);
    cryptoStream.FlushFinalBlock();
    Console.WriteLine(Convert.ToBase64String(memStream.ToArray()));
}

返回

+xD6VmtDUqiwpGsOYDNajofvMdS8F1eYkK50l+dsuqdgr6bUf2xWSwdEifd96A5h/yM2bIxdWeWM5+4eCCitDjh+qZDj32rJS0fpV/q08hhfNltWdWxJhVezcuIAV3VZVM7jph3JF0gic6VECmsZ2w==

为什么它会返回两个不同的密文?

1 个答案:

答案 0 :(得分:3)

两种加密的输出都不同,因为您使用的shell(bash,ksh ...)在使用 here string 功能<<<时向字符串添加尾部换行符(参考here)。

要使用完全相同的加密printf

printf "%s" "Ala ma kota. Kot ma, ale... to jednak ona go posiada. Jednakże gdy przeczytamy to ponownie to..." | openssl enc -aes-256-cbc -base64 -A -K b14f636c88ba3dad57d53a8fab09dd95512ce1b545bbb93362113487e73a13fe -iv e43f2a549d05132fe2efe555edbd42a0
+xD6VmtDUqiwpGsOYDNajofvMdS8F1eYkK50l+dsuqdgr6bUf2xWSwdEifd96A5h/yM2bIxdWeWM5+4eCCitDjh+qZDj32rJS0fpV/q08hhfNltWdWxJhVezcuIAV3VZVM7jph3JF0gic6VECmsZ2w==