与PHP一样,在C#中解密用AES-256-CBC加密的数据

本文关键字:AES-256-CBC 加密 数据 解密 一样 PHP | 更新日期: 2023-09-27 18:14:07

我在数据库中使用PHP进行了一些加密,通常会使用解密

$encrypt_method = "AES-256-CBC";
$secret_key = "testing";
$secret_iv = "testingyes!!!";
$key = hash('sha256', $secret_key); // hash the key
$iv = substr(hash('sha256', $secret_iv), 0, 16); // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
echo(openssl_decrypt(base64_decode($data), $encrypt_method, $key, 0, $iv)); // the decrypted data

我正在尝试做同样的任务,但使用C#2013来解密相同的数据,有什么想法吗?

我会在php中使用加密

$encrypt_method = "AES-256-CBC";
$secret_key = "testing";
$secret_iv = "testingyes!!!";
$key = hash('sha256', $secret_key); // hash the key
$iv = substr(hash('sha256', $secret_iv), 0, 16); // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
echo(base64_encode(openssl_encrypt($data, $encrypt_method, $key, 0, $iv))); // the encrypted data

加密:这是一个测试

给出:d0EzQ2MvMHkxRks2cXg5NkFkK2twZz09=

我在C#中尝试过这个:

public static String sha256_hash(String value)
    {
        StringBuilder Sb = new StringBuilder();
        using (SHA256 hash = SHA256Managed.Create())
        {
            Encoding enc = Encoding.UTF8;
            Byte[] result = hash.ComputeHash(enc.GetBytes(value));
            foreach (Byte b in result)
                Sb.Append(b.ToString("x2"));
        }
        return Sb.ToString();
    }
private static String AES_decrypt(String Input)
    {
        RijndaelManaged aes = new RijndaelManaged();
        aes.KeySize = 256;
        aes.BlockSize = 256;
        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.None;
        aes.Key = Convert.FromBase64String(sha256_hash("testing"));            
        aes.IV = Convert.FromBase64String(sha256_hash("testingyes!!!").Substring(0, 16));
        var decrypt = aes.CreateDecryptor();
        byte[] xBuff = null;
        using (var ms = new MemoryStream())
        {
            using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write))
            {
                byte[] xXml = Convert.FromBase64String(Input);
                cs.Write(xXml, 0, xXml.Length);
            }
            xBuff = ms.ToArray();
        }
        String Output = Encoding.UTF8.GetString(xBuff);
        return Output;
    }
string cipherData = "d0EzQ2MvMHkxRks2cXg5NkFkK2twZz09=";
string f = AES_decrypt(cipherData);
Console.Write(f);

但我得到了错误:指定的密钥不是这个算法的有效大小

然而,当我使用PHP 时,我使用的密钥是有效的

与PHP一样,在C#中解密用AES-256-CBC加密的数据

    RijndaelManaged aes = new RijndaelManaged();
    aes.KeySize = 256;
    aes.BlockSize = 256;

块大小应为128,以便与AES-256-CBC兼容。

Rijndael支持可变块大小-AES不支持。