• 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);
    }
  • 相关阅读:
    jekins构建自动化项目的步骤
    CRT 和mysql 中文乱码解决方式
    Jenkins的配置(rpm red hat方式)
    MapReduce job.setNumReduceTasks(0)思考
    浏览器angent分析工具
    npm中的 --save-dev
    computed与methods的异同
    JS函数种类详解
    Vue.js和Nodejs的关系
    AJAX复习笔记
  • 原文地址:https://www.cnblogs.com/un4sure/p/2815366.html
Copyright © 2020-2023  润新知