gpt4 book ai didi

c# - "Padding is invalid and cannot be removed"Aes解密密文出错

转载 作者:行者123 更新时间:2023-11-30 21:37:10 25 4
gpt4 key购买 nike

我想使用 Aes 加密/解密我的访问 token 。加密部分成功运行。但是我的问题是在发生错误后解密加密的访问 token 时

Padding is invalid and cannot be removed.

下一行抛出异常:

 using (var srDecrypt = new StreamReader(csDecrypt))
{
result = srDecrypt.ReadToEnd();
}

谁能告诉我如何解决这个问题? (作为控制台应用程序)

 class Program
{
private static string keyString = "E546C8DF278CD5931069B522E695D4F2";
static void Main(string[] args)
{
var text = "a16df7367e9eca23ac5e071dc4449a7a";
Console.WriteLine(EncryptString(text)); ;
Console.WriteLine(DecryptString(EncryptString(text)));
Console.ReadLine();
}

public static string EncryptString(string text)
{
var key = Encoding.UTF8.GetBytes(keyString);

using (var aesAlg = Aes.Create())
{
using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV))
{
using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
using (var swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(text);
}

var iv = aesAlg.IV;

var decryptedContent = msEncrypt.ToArray();

var result = new byte[iv.Length + decryptedContent.Length];

Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
Buffer.BlockCopy(decryptedContent, 0, result, iv.Length, decryptedContent.Length);

return Convert.ToBase64String(result);
}
}
}
}

public static string DecryptString(string cipherText)
{
var fullCipher = Convert.FromBase64String(cipherText);

var iv = new byte[16];
var cipher = new byte[16];

Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length);
Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, iv.Length);
var key = Encoding.UTF8.GetBytes(keyString);

using (var aesAlg = Aes.Create())
{
using (var decryptor = aesAlg.CreateDecryptor(key, iv))
{
string result;
using (var msDecrypt = new MemoryStream(cipher))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new StreamReader(csDecrypt))
{
result = srDecrypt.ReadToEnd();
}
}
}

return result;
}
}
}
}

最佳答案

你应该改变它

        var iv = new byte[16];
var cipher = new byte[16];

Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length);
Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, iv.Length);

        var iv = new byte[16];
var cipher = new byte[fullCipher.Length - 16]; //Calculate correct byte size

Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length);
Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, cipher.Length); //Change destination count of copied bytes

默认情况下,密码数组大小不能为 16 个字节,您应该计算它。

关于c# - "Padding is invalid and cannot be removed"Aes解密密文出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47506053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com