我正在根据以下逻辑使用以下代码创建许可证:
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();
}
}
}
}
}
}
在观看窗口中,我收到了文字K\0a\0m\0r\0a\0n\0
,但文本框中的最终输出只是K
。
答案 0 :(得分:4)
丢失BlockCopy
并将字符串转换为UTF-8:
buffer = Encoding.UTF8.GetBytes(strLicenseString);
或使用您当前的代码&告诉读者文本是UTF-16(内部字符串编码&是你在执行原始块复制时最终在缓冲区中的内容)
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();
}