RSA 加密演算法是一種非對稱加密演算法,網路上已經很有非常多的範例了,我只是將我的 Sample 備份在這邊,以便將來可以參考,以下節錄我有參考到的前輩們的文章。
產生公鑰及私鑰
private Tuple<string, string> GenerateRSAKeys()
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
var publicKey = rsa.ToXmlString(false);
var privateKey = rsa.ToXmlString(true);
return Tuple.Create<string, string>(publicKey, privateKey);
}
加密字串
private string Encrypt(string publicKey, string content)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(publicKey);
var encryptString = Convert.ToBase64String(rsa.Encrypt(Encoding.UTF8.GetBytes(content), false));
return encryptString;
}
解密字串
private string Decrypt(string privateKey, string encryptedContent)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(privateKey);
var decryptString = Encoding.UTF8.GetString(rsa.Decrypt(Convert.FromBase64String(encryptedContent), false));
return decryptString;
}
加密檔案
private void EncryptFile(string publicKey, string rawFilePath, string encryptedFilePath)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(publicKey);
using (FileStream testDataStream = File.OpenRead(rawFilePath))
using (FileStream encrytpStream = File.OpenWrite(encryptedFilePath))
{
var testDataByteArray = new byte[testDataStream.Length];
testDataStream.Read(testDataByteArray, 0, testDataByteArray.Length);
var encryptDataByteArray = rsa.Encrypt(testDataByteArray, false);
encrytpStream.Write(encryptDataByteArray, 0, encryptDataByteArray.Length);
}
}
解密檔案
private void DecryptFile(string privateKey, string encryptedFilePath, string decryptedFilePath)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(privateKey);
using (FileStream encrytpStream = File.OpenRead(encryptedFilePath))
using (FileStream decrytpStream = File.OpenWrite(decryptedFilePath))
{
var encryptDataByteArray = new byte[encrytpStream.Length];
encrytpStream.Read(encryptDataByteArray, 0, encryptDataByteArray.Length);
var decryptDataByteArray = rsa.Decrypt(encryptDataByteArray, false);
decrytpStream.Write(decryptDataByteArray, 0, decryptDataByteArray.Length);
}
}
在加密檔案的過程當中發生了長度錯誤的例外錯誤訊息,原來加密的 KeySize 大小會影響可加密的資料內容大小,可加密的資料內容大小估算公式為 (KeySize / 8) - 11。
如果想要改變 KeySize 大小,可以在宣告 RSACryptoServiceProvider 時就指定給它,例如:
如果想要改變 KeySize 大小,可以在宣告 RSACryptoServiceProvider 時就指定給它,例如:
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);
就將 KeySize 大小指定為 2048。< Source Code >