c#版RSA非对称加解密函数(PEM格式文件读写,能与php进行互通)

using System;
using System.Security.Cryptography;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Encodings;

class RSAUtils
{
    protected static string pubpath = Directory.GetCurrentDirectory() + "\\public.pem";
    protected static string pripath = Directory.GetCurrentDirectory() + "\\private.pem";

    public static string DeEncrypt(string data)
    {
        if(string.IsNullOrEmpty(data))
            throw new Exception("字符串不能为空");

        byte[] bytes = Convert.FromBase64String(data);
        AsymmetricCipherKeyPair keypair;
        AsymmetricKeyParameter prikey;
        using (var reader = File.OpenText(pripath))
        {
            keypair = new PemReader(reader).ReadObject() as AsymmetricCipherKeyPair;
            prikey = keypair.Private;
        }

        if(prikey == null)
            throw new Exception("私钥读取失败");

        /*这种方式也可以解密
        IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
        c.Init(false, prikey);
        bytes = c.DoFinal(bytes);
        */
        try
        {
            var engine = new Pkcs1Encoding(new RsaEngine());
            engine.Init(false, keypair.Private);
            bytes = engine.ProcessBlock(bytes, 0, bytes.Length);

            return Encoding.UTF8.GetString(bytes);
        }
        catch {
            throw new Exception("解密失败");
        }
    }

    public static string Encrypt(string data) {
        AsymmetricKeyParameter publickey;
        using (var reader = File.OpenText(pubpath)) {
            publickey = new PemReader(reader).ReadObject() as AsymmetricKeyParameter;
        }

        if (publickey == null)
            throw new Exception("私钥读取失败");

        try
        {
            var engine = new Pkcs1Encoding(new RsaEngine());
            engine.Init(true, publickey);

            byte[] bytes = Encoding.UTF8.GetBytes(data);
            bytes = engine.ProcessBlock(bytes, 0, bytes.Length);

            return Convert.ToBase64String(bytes);
        }
        catch {
            throw new Exception("加密失败");
        }
    }

    public static bool CreateRSAPems() {

        RsaKeyPairGenerator generator = new RsaKeyPairGenerator();
        RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(Org.BouncyCastle.Math.BigInteger.ValueOf(3), new SecureRandom(), 1024, 25);

        generator.Init(param);
        AsymmetricCipherKeyPair keypair = generator.GenerateKeyPair();

        AsymmetricKeyParameter publickey = keypair.Public;
        AsymmetricKeyParameter privatekey = keypair.Private;

        if( ((RsaKeyParameters)publickey).Modulus.BitLength<1024 ){
            return false;
        }

        using (TextWriter tw = new StringWriter())
        using(StreamWriter sw = new StreamWriter(pubpath))
        {
            new PemWriter(tw).WriteObject(publickey);
            sw.Write(tw.ToString());
        }

        using (TextWriter writer = new StreamWriter(pripath, false, Encoding.UTF8))
        {
            new PemWriter(writer).WriteObject(privatekey);
        }

        return true;

    }

}

  

posted @ 2016-04-05 12:15  TheLuther  阅读(1949)  评论(0编辑  收藏  举报