我正在编写密码加密例程。我写了下面的应用程序来说明我的问题。大约 20% 的时间,此代码按预期工作。其余时间,解密会抛出加密异常 - “数据无效”。
我认为问题出在加密部分,因为解密部分每次都一样。也就是说,如果加密例程产生一个解密例程可以解密的值,它总能解密它。但是,如果加密例程产生一个阻塞解密例程的值,它就会一直阻塞。所以解密例程是一致的;加密例程不是。
我怀疑我对 Unicode 编码的使用不正确,但我已经尝试过其他的结果相同。
我做错了什么?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
namespace DataProtectionTest
{
public partial class Form1 : Form
{
private static readonly byte[] entropy = { 1, 2, 3, 4, 1, 2, 3, 4 };
private string password;
public Form1()
{
InitializeComponent();
}
private void btnEncryptIt_Click(object sender, EventArgs e)
{
Byte[] pw = Encoding.Unicode.GetBytes(textBox1.Text);
Byte[] encryptedPw = ProtectedData.Protect(pw, entropy, DataProtectionScope.LocalMachine);
password = Encoding.Unicode.GetString(encryptedPw);
}
private void btnDecryptIt_Click(object sender, EventArgs e)
{
Byte[] pwBytes = Encoding.Unicode.GetBytes(password);
try
{
Byte[] decryptedPw = ProtectedData.Unprotect(pwBytes, entropy, DataProtectionScope.LocalMachine);
string pw = Encoding.Unicode.GetString(decryptedPw);
textBox2.Text = pw;
}
catch (CryptographicException ce)
{
textBox2.Text = ce.Message;
}
}
}
}
最佳答案
在同事的建议下,我选择了 Convert.ToBase64String。效果很好。更正了下面的程序。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
namespace DataProtectionTest
{
public partial class Form1 : Form
{
private static readonly byte[] entropy = { 1, 2, 3, 4, 1, 2, 3, 4 };
private string password;
public Form1()
{
InitializeComponent();
}
private void btnEncryptIt_Click(object sender, EventArgs e)
{
Byte[] pw = Encoding.Unicode.GetBytes(textBox1.Text);
Byte[] encryptedPw = ProtectedData.Protect(pw, entropy, DataProtectionScope.LocalMachine);
//password = Encoding.Unicode.GetString(encryptedPw);
password = Convert.ToBase64String(encryptedPw);
}
private void btnDecryptIt_Click(object sender, EventArgs e)
{
//Byte[] pwBytes = Encoding.Unicode.GetBytes(password);
Byte[] pwBytes = Convert.FromBase64String(password);
try
{
Byte[] decryptedPw = ProtectedData.Unprotect(pwBytes, entropy, DataProtectionScope.LocalMachine);
string pw = Encoding.Unicode.GetString(decryptedPw);
textBox2.Text = pw;
}
catch (CryptographicException ce)
{
textBox2.Text = ce.Message;
}
}
}
}
关于c# - ProtectedData.Protect 间歇性故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/246822/