C# RSA算法實現 - 利用openssl生成的證書 - 加密解密


1.利用openssl生成key文件

openssl genpkey -algorithm RSA -out key.pem -aes-256-cbc -pass pass:123456 -pkeyopt rsa_keygen_bits:2048

2.生成自簽名證書

openssl req -new -x509 -key key.pem -days 365 -out my-cert.crt

3.利用openssl中的pkcs12將證書格式變為pfx(p12)格式

openssl pkcs12 -export -in my-cert.crt -inkey key.pem -out mycert.pfx

中間會提示輸入key.pem的pass phrase 即第一步中的123456

然后會提示為mycert.pfx輸入加密密鑰,比如:654321

C#讀取pfx並利用RSA算法加密解密

static void main()
{
    //讀取pfx證書
    X509Certificate2 x509 = new X509Certificate2(@"mycert.pfx", "654321", X509KeyStorageFlags.Exportable);
    
    String plaintext = "hello,world!";
    //利用證書中的公鑰加密
    String enc = RSAEncrypt(x509.PublicKey.Key.ToXmlString(false), plaintext);
    Console.WriteLine(enc);
    //利用證書中的私鑰解密
    String plain = RSADecrypt(x509.PrivateKey.ToXmlString(true), enc);
    Console.WriteLine(plain);
}

//string xmlPublicKey : xml 格式的公鑰字符串
//string m_strEncryptString: 明文字符串
public static string RSAEncrypt(string xmlPublicKey, string plainText)
{
    RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
    provider.FromXmlString(xmlPublicKey);
    byte[] bytes = new UnicodeEncoding().GetBytes(plainText);
    return Convert.ToBase64String(provider.Encrypt(bytes, false));
}

//string xmlPrivateKey :xml 格式的私鑰字符串
//string encryptedText : 先加密然后經過Base64編碼的字符串
public static string RSADecrypt(string xmlPrivateKey, string encryptedText)
{
    RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
    provider.FromXmlString(xmlPrivateKey);
    byte[] rgb = Convert.FromBase64String(m_strDecryptString);
    byte[] bytes = provider.Decrypt(rgb, false);
    return new UnicodeEncoding().GetString(bytes);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM