gpt4 book ai didi

c# - DESCryptoServiceProvider 解密不起作用。获取包含\0 个字符且只有第一个字母的输出

转载 作者:行者123 更新时间:2023-11-30 20:32:12 24 4
gpt4 key购买 nike

我正在根据以下逻辑使用加密的以下代码创建许可证:

private void SaveLicenseInfoWithEncryption(LicenseInfo obj)
{

string strLicenseString = "Kamran";
//string strLicenseString = JsonConvert.SerializeObject(obj, Formatting.None);
byte[] buffer = new byte[strLicenseString.Length * sizeof(char)];
Buffer.BlockCopy(strLicenseString.ToCharArray(), 0, buffer, 0, buffer.Length);


DESCryptoServiceProvider desCryptSrvckey = new DESCryptoServiceProvider
{
Key = new UTF8Encoding().GetBytes(ConfigurationManager.AppSettings["EncryptionKey"])
};
desCryptSrvckey.IV = desCryptSrvckey.Key;

using (MemoryStream stmCipherText = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(stmCipherText, desCryptSrvckey.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(buffer, 0, buffer.Length);
cs.FlushFinalBlock();
string licPath = Path.Combine(txtFolderPath.Text, @"Test.lic");
File.WriteAllBytes(licPath, stmCipherText.ToArray());
MessageBox.Show(@"License File Generated Successfully");
}
}
}

许可证生成正常(我暂时放入了示例文本)。问题是我正在尝试解密我的许可证,但我遇到了一些无效行为。

我的代码是:

private void button1_Click(object sender, EventArgs e)
{
var fileDialog = new OpenFileDialog
{
Filter = @"License Files|*.lic",
Title = @"Select a License File"
};
if (fileDialog.ShowDialog() == DialogResult.OK)
{

byte[] buffer = File.ReadAllBytes(fileDialog.FileName);

DESCryptoServiceProvider desCryptSrvckey = new DESCryptoServiceProvider
{
Key = new UTF8Encoding().GetBytes(ConfigurationManager.AppSettings["EncryptionKey"])
};
desCryptSrvckey.IV = desCryptSrvckey.Key;

using (MemoryStream encryptedStream = new MemoryStream(buffer))
{
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(encryptedStream, desCryptSrvckey.CreateDecryptor(), CryptoStreamMode.Read))
{
using (StreamWriter sw = new StreamWriter(ms))
{
using (StreamReader sr = new StreamReader(cs))
{
sw.Write(sr.ReadToEnd());
sw.Flush();
}


ms.Position = 0;
txtContent.Text = new StreamReader(ms).ReadToEnd();
}
}
}
}

}
}

在监 window 口中,我得到文本 K\0a\0m\0r\0a\0n\0 但文本框中的最终输出只是 K

最佳答案

丢失BlockCopy并将字符串转换为UTF-8:

buffer = Encoding.UTF8.GetBytes(strLicenseString); 

或者使用您当前的代码并告诉读者文本是 UTF-16(这就是内部字符串编码,当您进行原始 block 复制时最终会出现在您的缓冲区中)

new StreamReader(cs, Encoding.Unicode)

您还可以简化为:

...

desCryptSrvckey.IV = desCryptSrvckey.Key;

using (MemoryStream encryptedStream = new MemoryStream(buffer))
using (CryptoStream cs = new CryptoStream(encryptedStream, desCryptSrvckey.CreateDecryptor(), CryptoStreamMode.Read))
using (StreamReader sr = new StreamReader(cs))
{
txtContent.Text = sr.ReadToEnd();
}

关于c# - DESCryptoServiceProvider 解密不起作用。获取包含\0 个字符且只有第一个字母的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41893730/

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