EDIT2:似乎 Convert.FromBase64String 是我的救星。有谁知道逗号是否会在这样的字符串中?我正在做基本的 csv 解析。如果是的话,我总是可以使用引号(但我猜引号也可以在这样的字符串中)但这对我自己来说只是一个小项目,所以通过用','分割更容易解析。
编辑:好的,所以看起来我的问题是当我将加密的字节转换为字符串,然后将该字符串转换回要解密的字节。我怎么能这样做,因为我想将加密的字符串实际存储在某个地方并能够解密该字符串。
我正在尝试将公钥(以及仅用于测试的私钥)保存到 xml 文件中,以便以后可以读取相同的文件,但在尝试解密时出现“错误数据”错误。谁能看到我做错了什么?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace EncryptionTest
{
class Program
{
static void Main(string[] args)
{
UnicodeEncoding ByteConverter = new UnicodeEncoding();
byte[] dataToEncrypt = ByteConverter.GetBytes("Test data");
WriteRSAInfoToFile();
string enc = Encrypt(dataToEncrypt);
enc = Decrypt(enc);
}
static void WriteRSAInfoToFile()
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
TextWriter writer = new StreamWriter("C:\\publicKey.xml");
string publicKey = RSA.ToXmlString(false);
writer.Write(publicKey);
writer.Close();
writer = new StreamWriter("C:\\privateKey.xml");
string privateKey = RSA.ToXmlString(true);
writer.Write(privateKey);
writer.Close();
}
static string Encrypt(byte[] data)
{
UnicodeEncoding ByteConverter = new UnicodeEncoding();
RSACryptoServiceProvider encrypt = new RSACryptoServiceProvider();
TextReader reader = new StreamReader("C:\\publicKey.xml");
string publicKey = reader.ReadToEnd();
reader.Close();
encrypt.FromXmlString(publicKey);
byte[] encryptedData = encrypt.Encrypt(data, false);
return ByteConverter.GetString(encryptedData);
}
static string Decrypt(string data)
{
UnicodeEncoding ByteConverter = new UnicodeEncoding();
RSACryptoServiceProvider decrypt = new RSACryptoServiceProvider();
TextReader reader = new StreamReader("C:\\privateKey.xml");
string privateKey = reader.ReadToEnd();
reader.Close();
decrypt.FromXmlString(privateKey);
byte[] d = ByteConverter.GetBytes(data);
byte[] decryptedData = decrypt.Decrypt(d, false); // ERROR: bad data
return ByteConverter.GetString(decryptedData);
}
}
}