zoukankan      html  css  js  c++  java
  • 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);
    }
  • 相关阅读:
    Appium学习实践(二)Python简单脚本以及元素的属性设置
    Appium学习实践(三)测试用例脚本以及测试报告输出
    Appium学习实践(一)简易运行Appium
    Appium学习实践(四)结构优化
    js中对小数取整的函数
    C#基础 面试中常出现的问题
    repeater中的删除按钮实现
    js对fck编辑器取值 赋值
    jQuery对select操作
    进制转换(二进制 八进制 十进制 十六进制)
  • 原文地址:https://www.cnblogs.com/un4sure/p/2815366.html
Copyright © 2011-2022 走看看