【发布时间】:2014-05-20 01:47:46
【问题描述】:
我收到运行时错误 {"Bad Length.\r\n"} 就行了:
return rsa.Encrypt(bytes, true);
这是在函数中:
private static byte[] Encrypt(byte[] bytes)
{
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
string test = Properties.Settings.Default.PublicKeyXml;
rsa.FromXmlString("<RSAKeyValue><Modulus>mfXS3Na0XfkjhpjS3sL5XcC9o+j6KXi1LB9yBc4SsTMo1Yk/pFsXr74gNj4aRxKB45+hZH/lSo933NCDEh25du1iMsaH4TGQNkCqi+HDLQjOrdXMMNmaQrLXGlY7UCCfFUnkEUxX51AlyVLzqLycaAt6zm5ljnDXojMC7JoCrTM=</Modulus><Exponent>AQAB</Exponent></RSAKeyFile>");
return rsa.Encrypt(bytes, true);
}
}
我使用的密钥大小为 8192:
CspParameters cspParams = new CspParameters();
cspParams.KeyContainerName = "XML_ENC_RSA_KEY";
RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(8192, cspParams);
string keyXml = rsaKey.ToXmlString(true);
XML 文件很小。根据运行时的长度,只有225字节:
string fileName = System.IO.Path.Combine(Application.StartupPath, "alphaService.xml");
XDocument doc = new XDocument();
XElement xml = new XElement("Info",
new XElement("DatabaseServerName", txtServerName.Text),
new XElement("DatabaseUserName", txtDatabaseUserName.Text),
new XElement("DatabasePassword", txtDatabasePassword.Text),
new XElement("ServiceAccount", txtAccount.Text),
new XElement("ServicePassword", txtServicePassword.Text),
new XElement("RegistrationCode", txtRegistrationCode.Text));
doc.Add(xml);
doc.Save(fileName);
// Convert XML doc to byte stream
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(fileName);
byte[] fileBytes = Encoding.Default.GetBytes(xmlDoc.OuterXml);
int fileBytesLength = fileBytes.Length;
Encrypt(fileBytes);
根据this SO post,4096 字节的密钥大小应该足够了:
((KeySize - 384) / 8) + 7
我必须使用多大的密钥?为什么 8096 字节不起作用?我怎样才能让它工作?
【问题讨论】:
-
我强烈建议不要使用 RSA 密钥直接加密您的 XML。它无法扩展,并且比对称加密慢得多。更好的方法是使用对称算法(如 AES)加密您的 XML,然后使用您的 RSA 密钥加密 AES 对称密钥。
-
您能否在答案中显示执行此操作的代码?
-
@vcsjones 是对的,不要依赖 RSA 对任意数量的数据进行加密。用它来安全地交换一个已知长度的对称密钥。
-
第一个代码 sn-p 中包含的密钥是您实际使用的密钥吗?如果是这样,它只是 1024 位,而不是 8192。
-
你做错了。 RSA 用于密钥传输(加密其他密钥),而不是数据加密。
标签: c# xml encryption cryptography rsa