我在寫密碼加密程序。我已經寫了下面的應用程序來說明我的問題。大約20%的時間,此代碼按預期工作。剩下的時間,解密會拋出一個加密異常 - 「數據無效」。ProtectedData.Protect間歇性故障
我相信問題出在加密部分,因爲解密部分每次都是一樣的。也就是說,如果加密例程產生解密例程可以解密的值,則它總是可以解密它。但是,如果加密例程產生一個扼殺解密例程的值,它總是扼流圈。所以解密程序是一致的;加密程序不是。
我懷疑我使用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;
}
}
}
}
此代碼仍然存在一個錯誤...請參閱下面的答案。 – 2011-12-30 19:10:27