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);
}

 

转载于:https://www.cnblogs.com/un4sure/archive/2012/12/12/2815366.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值