加密:用RSA对数据加密,然后把公钥私钥对和密文一起写到txt文件。
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
byte[] toEncryptData = Encoding.UTF8.GetBytes(richTextBox.Text);
byte[] encryptedData = rsa.Encrypt(toEncryptData, false);
StreamWriter sw = File.CreateText(filePath);
sw.Write(rsa.ToXmlString(true));
sw.Write(Encoding.UTF8.GetString(encryptedData));
sw.Close();
[code]
解密:首先读出公钥私钥数据(长度为915),然后解密
[code=C#]StreamReader sr = File.OpenText(filePath);
string information = sr.ReadToEnd();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(information.Substring(0, 915));//0-915是公钥私钥串,915以后是加密后的数据
byte[] deCryptData = rsa.Decrypt(Encoding.UTF8.GetBytes(information.Substring(915)), false);//报错:数据不正确
richTextBox.Text = Encoding.UTF8.GetString(deCryptData);我十分不理解,怎么就不正确了!?希望前辈们指点
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
byte[] toEncryptData = Encoding.UTF8.GetBytes(richTextBox.Text);
byte[] encryptedData = rsa.Encrypt(toEncryptData, false);
StreamWriter sw = File.CreateText(filePath);
sw.Write(rsa.ToXmlString(true));
sw.Write(Encoding.UTF8.GetString(encryptedData));
sw.Close();
[code]
解密:首先读出公钥私钥数据(长度为915),然后解密
[code=C#]StreamReader sr = File.OpenText(filePath);
string information = sr.ReadToEnd();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(information.Substring(0, 915));//0-915是公钥私钥串,915以后是加密后的数据
byte[] deCryptData = rsa.Decrypt(Encoding.UTF8.GetBytes(information.Substring(915)), false);//报错:数据不正确
richTextBox.Text = Encoding.UTF8.GetString(deCryptData);我十分不理解,怎么就不正确了!?希望前辈们指点
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
byte[] toEncryptData = Encoding.UTF8.GetBytes(richTextBox.Text);
byte[] encryptedData = rsa.Encrypt(toEncryptData, false);
FileStream fs = new FileStream(filePath, FileMode.Create);
byte[] bytes = Encoding.UTF8.GetBytes(rsa.ToXmlString(true));
fs.Write(bytes, 0, bytes.Length);
fs.Write(encryptedData, 0, encryptedData.Length);
fs.Close();//
byte[] bytes = new byte[915];
FileStream fs = new FileStream(filePath, FileMode.Open);
fs.Read(bytes, 0, 915);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(Encoding.UTF8.GetString(bytes));//0-915是公钥私钥串,915以后是加密后的数据
bytes = new byte[fs.Length - 915];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
richTextBox.Text = Encoding.UTF8.GetString(deCryptData);
optione 3点多还帮忙解答问题,太感动了,呵呵。