gpt4 book ai didi

c# - aspnet core加密和解密字符串

转载 作者:太空狗 更新时间:2023-10-29 18:00:17 35 4
gpt4 key购买 nike

我正在尝试使用一些非常标准的算法来解密字符串。

public static string DecryptString(string cipherText)
{
string keyString = string.Empty;

// Check whether the environment variable exists.
keyString = Environment.GetEnvironmentVariable("EncryptKey");

if (keyString == null)
{
keyString = "E546C8DF278CD5931069B522E695D4F2";
}

var fullCipher = Convert.FromBase64String(cipherText);
using (var aesAlg = Aes.Create())
{
byte[] iv = new byte[aesAlg.BlockSize / 8];
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);

string result;
using (var decryptor = aesAlg.CreateDecryptor(key, iv))
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;
}
}

我不断收到错误:

System.Security.Cryptography.CryptographicException: Specified padding mode is not valid for this algorithm.

我试过很多这样的方法

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

或者

var iv = aesAlg.IV;

此时我仍然遇到错误。我做错了什么?

最佳答案

需要做两处改动

var cipher = new byte[fullCipher.Length - iv.Length];

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

关于c# - aspnet core加密和解密字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43727192/

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