0
這是this SO post的後續操作,我學會了生成RSA密鑰對並將公鑰存儲在設置中。我生成我的鑰匙:RSA加密xml文件轉換爲字節時出錯[]
CspParameters cspParams = new CspParameters();
cspParams.KeyContainerName = "XML_ENC_RSA_KEY";
RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);
string keyXml = rsaKey.ToXmlString(true);
我複製該字符串的公鑰部分到我的程序設置,它看起來像:
"<RSAKeyValue><Modulus>mfXS3Na0XfkjhpjS3sL5XcC9o+j6KXi1LB9yBc4SsTMo1Yk/pFsXr74gNj4aRxKB45+hZH/lSo933NCDEh25du1iMsaH4TGQNkCqi+HDLQjOrdXMMNmaQrLXGlY7UCCfFUnkEUxX51AlyVLzqLycaAt6zm5ljnDXojMC7JoCrTM=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"
確實看起來有效嗎?
然後我把我的XML文檔,並試圖將其轉換爲一個byte []的加密功能:
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);
Encrypt(fileBytes);
我從加密功能獲得「語法錯誤行1」是:
private static byte[] Encrypt(byte[] bytes)
{
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(Properties.Settings.Default.PublicKeyXml);
return rsa.Encrypt(bytes, true);
}
}
任何想法?編輯:實際的錯誤是:
rsa.FromXmlString(Properties.Settings.Default.PublicKeyXml);
@TDSapp ....不知道爲什麼OP從來沒有給你信用的答案,但它對我很好。我打你的答案嘗試rsa加密一個非常小的XML文件,但得到了錯誤的長度錯誤。 – GPGVM