使用16字节密码解密AES256

时间:2017-07-13 11:43:25

标签: c# encryption base64 rijndaelmanaged

我试图用C#解密加密的base64编码字符串。 我使用以下在线工具加密了字符串: http://encode-decode.com/aes256-encrypt-online/

例如,当我加密文本时,abcd'使用密钥' zzzz',我得到以下base64字符串: 3crNVWxmpkE + UjT3lPoi0g ==

我没有得到的是......这只是16字节的数据,而IV本身应该已经是16字节。 结果,我试图添加填充,但是密码正在抱怨填充。我觉得我错过了什么。请参阅下面的解密功能:

public static string Decrypt(string cipherText, string keyString)
{
    int Keysize = 256;
    var key = Encoding.UTF8.GetBytes(keyString);
    if (key.Length < 16)
    {
        var keycopy = new byte[16];
        Array.Copy(key, 0, keycopy, 15 - key.Length, key.Length);
        key = keycopy;
    }
    // Get the complete stream of bytes that represent:
    // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
    var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
    // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
    var iv = cipherTextBytesWithSaltAndIv.Take(8).ToArray();
    if (iv.Length < 16)
    {
        var ivcopy = new byte[16];
        Array.Copy(iv, 0, ivcopy, 15 - iv.Length, iv.Length);
        iv = ivcopy;
    }

    // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
    var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip(8).Take(cipherTextBytesWithSaltAndIv.Length - 8).ToArray();
    if (cipherTextBytes.Length < 16)
    {
        var cipherTextBytescopy = new byte[16];
        Array.Copy(cipherTextBytes, 0, cipherTextBytescopy, 15 - cipherTextBytes.Length, cipherTextBytes.Length);
        cipherTextBytes = cipherTextBytescopy;
    }

    try
    {
        using (var rijndaelManaged = new RijndaelManaged { Key = key, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 })
        using (var memoryStream = new MemoryStream(cipherTextBytes))
        using (var cryptoStream = new CryptoStream(memoryStream,
                       rijndaelManaged.CreateDecryptor(key, iv),
                       CryptoStreamMode.Read))
        {
            return new StreamReader(cryptoStream).ReadToEnd();
        }
    }
    catch (CryptographicException e)
    {
        Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
        return null;
    }
    // You may want to catch more exceptions here...
}

0 个答案:

没有答案
相关问题