[英]Encrypt string using public key as text in C#
我收到了一個 txt 格式的公鑰。 (BEGIN CERTIFICATE---END CERTIFICATE)我想使用 C# 中的此密鑰加密我的消息並將其發送出去。
同樣,我有我的文本格式的私鑰。 我已經與第三方共享了我的公鑰,他們用它來加密消息。 我想使用我的私鑰以 TEXT 格式解密消息。 我如何在 C# 中做到這一點?
請幫忙。
public class MyCrypto
{
public X509Certificate2 GetDecryptionCertificate(string certificateName)
{
var my = new X509Store(StoreName.My, StoreLocation.LocalMachine);
my.Open(OpenFlags.ReadOnly);
var collection = my.Certificates.Find(X509FindType.FindBySubjectName, certificateName, false);
if (collection.Count == 1)
{
return collection[0];
}
else if (collection.Count > 1)
{
throw new Exception(string.Format("More than one certificate with name '{0}' found in store LocalMachine/My.", certificateName));
}
else
{
throw new Exception(string.Format("Certificate '{0}' not found in store LocalMachine/My.", certificateName));
}
}
public X509Certificate2 GetEncryptionCertificate(string filePath)
{
var collection = new X509Certificate2Collection();
collection.Import(filePath);
return collection[0];
}
public string EncryptRsa(string input, X509Certificate2 x509Certificate2)
{
var output = string.Empty;
using (RSA csp = (RSA)x509Certificate2.PublicKey.Key)
{
byte[] bytesData = Encoding.UTF8.GetBytes(input);
byte[] bytesEncrypted = csp.Encrypt(bytesData, RSAEncryptionPadding.OaepSHA1);
output = Convert.ToBase64String(bytesEncrypted);
}
return output;
}
public string DecryptRsa(string encrypted, X509Certificate2 x509Certificate2)
{
var text = string.Empty;
using (RSA csp = (RSA)x509Certificate2.PrivateKey)
{
byte[] bytesEncrypted = Convert.FromBase64String(encrypted);
byte[] bytesDecrypted = csp.Decrypt(bytesEncrypted, RSAEncryptionPadding.OaepSHA1);
text = Encoding.UTF8.GetString(bytesDecrypted);
}
return text;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.