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

 

posted on 2012-12-12 21:34  shosciation  阅读(3598)  评论(1编辑  收藏  举报