RSA加密算法互通-java、.net、golang

java版本RSA算法:

package cn.com.gome.utils;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;

import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.encodings.PKCS1Encoding;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.generators.RSAKeyPairGenerator;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.util.PrivateKeyFactory;
import org.bouncycastle.crypto.util.PrivateKeyInfoFactory;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory;
import org.bouncycastle.util.encoders.Base64;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
import org.bouncycastle.util.io.pem.PemWriter;

import sun.misc.BASE64Encoder;

/**
 * sra加密
 * @author
 *
 */
public class RSAUtils {

    /**
     * 生成公钥和私钥
     * @throws NoSuchAlgorithmException 
     *
     */
    public static Map<String,String> getKeys(Boolean isGenerateFile) throws NoSuchAlgorithmException{
        Map<String,String> map = new HashMap<String,String>();
        //生成参数配置
        RSAKeyPairGenerator rsaKeyPairGenerator = new RSAKeyPairGenerator();
        //设置秘钥生成参数
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        //secureRandom.setSeed(seed);
        RSAKeyGenerationParameters rsaKeyGenerationParameters = new RSAKeyGenerationParameters(BigInteger.valueOf(65537), secureRandom, 1024, 16);
        rsaKeyPairGenerator.init(rsaKeyGenerationParameters);
        
        //生成秘钥
        AsymmetricCipherKeyPair keyPair = rsaKeyPairGenerator.generateKeyPair();
        RSAKeyParameters publicKey = (RSAKeyParameters) keyPair.getPublic();//公钥  
        RSAKeyParameters privateKey = (RSAKeyParameters) keyPair.getPrivate();//私钥 
        
        //使用x509证书进行处理
        SubjectPublicKeyInfo subjectPublicKeyInfo;
        PrivateKeyInfo privateKeyInfo;
        try {
            subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(publicKey);
            privateKeyInfo = PrivateKeyInfoFactory.createPrivateKeyInfo(privateKey);
        
            //pem格式处理
            ASN1Object asn1ObjectPublic = subjectPublicKeyInfo.toASN1Primitive();
            byte[] publicInfoByte = asn1ObjectPublic.getEncoded("DER");

            ASN1Object asn1ObjectPrivate = privateKeyInfo.toASN1Primitive();
            byte[] privateInfoByte = asn1ObjectPrivate.getEncoded("DER");
            
            //写入map中
            map.put("public", new String((new BASE64Encoder()).encode(publicInfoByte)));
            map.put("private", new String((new BASE64Encoder()).encode(privateInfoByte)));
//            map.put("public", new String(Base64.decode(publicInfoByte)));
//            map.put("private", new String(Base64.decode(privateInfoByte)));
            
            //生成文件
            if(isGenerateFile){
                //写入文件private
                Writer r = new FileWriter("private.pem");
                PemWriter pemWriter = new PemWriter(r);
                pemWriter.writeObject(new PemObject("PRIVATE KEY",Base64.encode(privateInfoByte)));
                //写入硬盘
                pemWriter.flush();
                pemWriter.close();
                //public
                Writer rp = new FileWriter("public.pem");
                PemWriter pemWriterp = new PemWriter(rp);
                pemWriterp.writeObject(new PemObject("PUBLIC KEY",Base64.encode(publicInfoByte)));
                //写入硬盘
                pemWriterp.flush();
                pemWriterp.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return map;
    }
    
    /**
     * 获取pem格式
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static Map<String,String> getKeysPem(Map<String,String> map) throws NoSuchAlgorithmException{
        
        if (map==null){
            map = getKeys(false);
        }
        
        StringBuffer str_Public_Key = new StringBuffer();
        str_Public_Key.append("-----BEGIN PUBLIC KEY-----");
        str_Public_Key.append("\n");
        str_Public_Key.append(map.get("public"));
        str_Public_Key.append("\n");
        str_Public_Key.append("-----END PUBLIC KEY-----");
        map.put("public", str_Public_Key.toString());
        
        StringBuffer str_Private_Key = new StringBuffer();
        str_Private_Key.append("-----BEGIN PRIVATE KEY-----");
        str_Private_Key.append("\n");
        str_Private_Key.append(map.get("private"));
        str_Private_Key.append("\n");
        str_Private_Key.append("-----END PRIVATE KEY-----");
        map.put("private", str_Private_Key.toString());
        
        return map;
    }

    
    /**
     * 解密
     * @return
     */
    public static byte[] decryptPrivateKey(String privateKey,byte[] data){
        
        //获取原始数据并进行64为解码
        byte[] bytes = new byte[0];
        
        AsymmetricBlockCipher engine = new PKCS1Encoding(new RSAEngine());
        Reader r = null;
        try {
            if(privateKey==null ||privateKey==""){
                r = new FileReader("private.pem");
                //获取秘钥
                PemReader pemReader = new PemReader(r);     //载入私钥
                PemObject readObject = pemReader.readPemObject();
                //生成key
                AsymmetricKeyParameter priKey = PrivateKeyFactory.createKey(Base64.decode(readObject.getContent()));
                engine.init(false, priKey);
                //进行
                pemReader.close();
            }else{
                //生成key
                AsymmetricKeyParameter priKey = PrivateKeyFactory.createKey(Base64.decode(privateKey.getBytes()));
                engine.init(false, priKey);
            }
            //解密
            bytes = engine.processBlock(data, 0, data.length);

        } catch (InvalidCipherTextException | IOException e) {
            e.printStackTrace();
        }finally{
            if(r!=null){
                try {
                    r.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bytes;
    }
    
    /**
     * 加密
     * @param publicKey
     * @param data
     * @return
     */
    public static byte[] encryptByPublicKey(String publicKey,byte[] data){
        //获取原始数据并进行64为解码
        byte[] bytes = new byte[0];
        
        AsymmetricBlockCipher engine = new PKCS1Encoding(new RSAEngine());
        Reader r = null;
        try {
            if(publicKey==null || publicKey==""){
                r = new FileReader("public.pem");
                //获取秘钥
                PemReader pemReader = new PemReader(r);     //载入私钥
                PemObject readObject = pemReader.readPemObject();
                AsymmetricKeyParameter pubKey = PublicKeyFactory.createKey(Base64.decode(readObject.getContent()));
                engine.init(true, pubKey);
                
                //关闭pem读取流
                pemReader.close();
            }else{
                AsymmetricKeyParameter pubKey = PublicKeyFactory.createKey(Base64.decode(publicKey.getBytes()));
                engine.init(true, pubKey);
            }
            //解密
            bytes = engine.processBlock(data, 0, data.length);
            
        } catch (InvalidCipherTextException | IOException e) {
            e.printStackTrace();
        }finally{
            if(r!=null){
                try {
                    r.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return bytes;
    }
    
}

  golang版本 RSA算法:

1、生成钥匙

package rsahelper

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "encoding/asn1"
    "encoding/pem"
    "flag"
    "log"
    "os"
    "sync"
)

//当前类的指针
var rsaGkey *rsaGenerateKey

//同步锁
var rsaGenerateKeyonce sync.Once

//实现单例
type rsaGenerateKey struct {
}

//生成密钥
func RSAGenerateKeys() *rsaGenerateKey {
    rsaGenerateKeyonce.Do(func() {
        rsaGkey = new(rsaGenerateKey)
    })
    return rsaGkey
}

//生成文件
func (r *rsaGenerateKey) GenerateKey() {
    var bits int
    flag.IntVar(&bits, "b", 1024, "密钥长度,默认为1024位")
    if err := r.GenRsaKey(bits); err != nil {
        log.Fatal("密钥文件生成失败!")
    }
}

//生成公私私钥--return(私钥,公私,错误)
func (r *rsaGenerateKey) Generate() ([]byte, []byte, error) {
    //定义变量并赋值
    var bits int
    bits = 1024 //密钥长度,默认为128位"
    //主线程中只用定义一次
    //flag.IntVar(&bits, "bint", 512, "密钥长度,默认为128位")
    // 生成私钥文件
    privateKey, err := rsa.GenerateMultiPrimeKey(rand.Reader, 3, bits)
    if err != nil {
        return nil, nil, err
    }
    //生成私钥
    derStream := MarshalPKCS8PrivateKey(privateKey)
    blockpri := &pem.Block{
        Type:  "PRIVATE KEY",
        Bytes: derStream,
    }
    // 生成公钥文件
    publicKey := &privateKey.PublicKey
    derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
    if err != nil {
        return nil, nil, err
    }
    blockpub := &pem.Block{
        Type:  "PUBLIC KEY",
        Bytes: derPkix,
    }

    return pem.EncodeToMemory(blockpri), pem.EncodeToMemory(blockpub), nil
}

//转化成pkcs8
func MarshalPKCS8PrivateKey(key *rsa.PrivateKey) []byte {
    info := struct {
        Version             int
        PrivateKeyAlgorithm []asn1.ObjectIdentifier
        PrivateKey          []byte
    }{}
    info.Version = 0
    info.PrivateKeyAlgorithm = make([]asn1.ObjectIdentifier, 1)
    info.PrivateKeyAlgorithm[0] = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
    info.PrivateKey = x509.MarshalPKCS1PrivateKey(key)

    k, err := asn1.Marshal(info)
    if err != nil {
        log.Panic(err.Error())
    }
    return k
}

//生成文件
func (r *rsaGenerateKey) GenRsaKey(bits int) error {
    // 生成私钥文件
    privateKey, err := rsa.GenerateKey(rand.Reader, bits)
    if err != nil {
        return err
    }
    derStream := x509.MarshalPKCS1PrivateKey(privateKey)
    block := &pem.Block{
        Type:  "RSA PRIVATE KEY",
        Bytes: derStream,
    }
    file, err := os.Create("private.pem")
    if err != nil {
        return err
    }
    err = pem.Encode(file, block)
    if err != nil {
        return err
    }
    // 生成公钥文件
    publicKey := &privateKey.PublicKey
    derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
    if err != nil {
        return err
    }
    block = &pem.Block{
        Type:  "PUBLIC KEY",
        Bytes: derPkix,
    }
    file, err = os.Create("public.pem")
    if err != nil {
        return err
    }
    err = pem.Encode(file, block)
    if err != nil {
        return err
    }
    return nil
}

  2、加密解密

package rsahelper

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "encoding/pem"
    "errors"
    "io/ioutil"
    "os"
    "sync"
)

//rsa
type rsaUtils struct {
    PrivateKey []byte
    PublicKey  []byte
}

//当前类的指针
var rasUtilsClass *rsaUtils

//同步锁
var rasUtilsClassonce sync.Once

//rsa工具
func RSAUtils() *rsaUtils {
    rasUtilsClassonce.Do(func() {
        rasUtilsClass = new(rsaUtils)
    })
    //返回处理对象
    return rasUtilsClass
}

func (r *rsaUtils) init() bool {
    //读取文件
    pubkey, err := r.readFile("public.pem")
    if err != nil {
        return false
    }
    r.PublicKey = pubkey

    //获取私钥
    prikey, err := r.readFile("private.pem")
    if err != nil {
        return false
    }
    r.PrivateKey = prikey
    return true
}

func (r *rsaUtils) readFile(filePth string) ([]byte, error) {
    f, err := os.Open(filePth)
    if err != nil {
        return nil, err
    }
    return ioutil.ReadAll(f)
}

// 加密
func (r *rsaUtils) RsaEncrypt(origData []byte, publicKey []byte) ([]byte, error) {
    block, _ := pem.Decode(publicKey)
    if block == nil {
        return nil, errors.New("public key error")
    }
    pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
    if err != nil {
        return nil, err
    }
    pub := pubInterface.(*rsa.PublicKey)
    return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
}

// 解密
func (r *rsaUtils) RsaDecrypt(ciphertext []byte, privateKey []byte) ([]byte, error) {
    block, _ := pem.Decode(privateKey)
    if block == nil {
        return nil, errors.New("private key error!")
    }
    priv, err := x509.ParsePKCS8PrivateKey(block.Bytes)
    if err != nil {
        return nil, err
    }
    priKey := priv.(*rsa.PrivateKey)
    return rsa.DecryptPKCS1v15(rand.Reader, priKey, ciphertext)
}

  .net版本的RSA算法:

using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.IO.Pem;
using Org.BouncyCastle.X509;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sys.Common.Helper
{
    /// <summary>
    /// RSA加密解密
    /// </summary>
    public class RSAHelper
    {
        /// <summary>
        /// 生成公钥和私钥
        /// </summary>
        /// <param name="isGenerateFile"></param>
        /// <returns></returns>
        public static Dictionary<string, string> getKeys(bool isGenerateFile)
        {
            Dictionary<String, String> dic = new Dictionary<String, String>();
            //生成参数配置
            RsaKeyPairGenerator rsaKeyPairGenerator = new RsaKeyPairGenerator();
            //设置秘钥生成参数
            SecureRandom secureRandom = SecureRandom.GetInstance("SHA1PRNG");
            //secureRandom.setSeed(seed);
            RsaKeyGenerationParameters rsaKeyGenerationParameters = new RsaKeyGenerationParameters(BigInteger.ValueOf(65537), secureRandom, 1024, 16);
            rsaKeyPairGenerator.Init(rsaKeyGenerationParameters);

            //生成秘钥
            AsymmetricCipherKeyPair keyPair = rsaKeyPairGenerator.GenerateKeyPair();
            RsaKeyParameters publicKey = (RsaKeyParameters)keyPair.Public;//公钥  
            RsaKeyParameters privateKey = (RsaKeyParameters)keyPair.Private;//私钥 

            //使用x509证书进行处理
            SubjectPublicKeyInfo subjectPublicKeyInfo;
            PrivateKeyInfo privateKeyInfo;
            try
            {
                subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
                privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);

                //pem格式处理
                Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();
                byte[] publicInfoByte = asn1ObjectPublic.GetEncoded("DER");

                Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();
                byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded("DER");

                //写入map中
                dic.Add("public", Convert.ToBase64String(publicInfoByte));
                dic.Add("private", Convert.ToBase64String(privateInfoByte));

                //生成文件
                if (isGenerateFile)
                {
                    //写入文件private
                    TextWriter r = new StreamWriter("private.pem");
                    PemWriter pemWriter = new PemWriter(r);
                    PemObjectGenerator priPem = new PemObject("PRIVATE KEY", System.Text.Encoding.Default.GetBytes(Convert.ToBase64String(privateInfoByte)));
                    pemWriter.WriteObject(priPem);
                    //写入硬盘
                    pemWriter.Writer.Flush(); //写入文件
                    pemWriter.Writer.Dispose(); //手动释放资源
                    pemWriter.Writer.Close(); //关闭资源
                    //public
                    TextWriter rp = new StreamWriter("public.pem");
                    PemWriter pemWriterp = new PemWriter(rp);
                    PemObjectGenerator pubPem = new PemObject("PUBLIC KEY", System.Text.Encoding.Default.GetBytes(Convert.ToBase64String(publicInfoByte)));
                    pemWriterp.WriteObject(pubPem);
                    //写入硬盘
                    pemWriterp.Writer.Flush(); //写入文件
                    pemWriterp.Writer.Dispose(); //手动释放资源
                    pemWriterp.Writer.Close(); //关闭资源
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return dic;
        }

        /// <summary>
        /// 生成公钥和私钥
        /// </summary>
        /// <param name="map"></param>
        /// <returns></returns>
        public static Dictionary<String, String> getKeysPem(Dictionary<String, String> dic)
        {

            if (dic == null)
            {
                dic = getKeys(false);
            }

            StringBuilder str_Public_Key = new StringBuilder();
            str_Public_Key.Append("-----BEGIN PUBLIC KEY-----");
            str_Public_Key.Append("\n");
            string pubKey = string.Empty;
            dic.TryGetValue("public", out pubKey);
            str_Public_Key.Append(pubKey);
            str_Public_Key.Append("\n");
            str_Public_Key.Append("-----END PUBLIC KEY-----");
            dic.Add("public", str_Public_Key.ToString());

            StringBuilder str_Private_Key = new StringBuilder();
            str_Private_Key.Append("-----BEGIN PRIVATE KEY-----");
            str_Private_Key.Append("\n");
            string priKey = string.Empty;
            dic.TryGetValue("private", out priKey);
            str_Private_Key.Append(priKey);
            str_Private_Key.Append("\n");
            str_Private_Key.Append("-----END PRIVATE KEY-----");
            dic.Add("private", str_Private_Key.ToString());

            return dic;
        }


        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="privateKey">不是pem格式</param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] decryptPrivateKey(String privateKey, byte[] data)
        {

            //获取原始数据并进行64为解码
            byte[] bytes = new byte[0];

            IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
            TextReader r = null;
            try
            {
                if (privateKey == null || privateKey == "")
                {
                    r = new StreamReader("private.pem");
                    //获取秘钥
                    PemReader pemReader = new PemReader(r);     //载入私钥
                    PemObject readObject = pemReader.ReadPemObject();
                    //生成key
                    AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(Convert.FromBase64String(System.Text.Encoding.Default.GetString(readObject.Content)));
                    engine.Init(false, priKey);
                    //进行
                    pemReader.Reader.Dispose();
                    pemReader.Reader.Close();
                }
                else
                {
                    //生成key
                    AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
                    engine.Init(false, priKey);
                }
                //解密
                bytes = engine.ProcessBlock(data, 0, data.Length);

            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                if (r != null)
                {
                    r.Dispose(); //手动释放资源
                    r.Close();
                }
            }
            return bytes;
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="publicKey">不是pem格式</param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] encryptByPublicKey(String publicKey, byte[] data)
        {
            //获取原始数据并进行64为解码
            byte[] bytes = new byte[0];

            IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
            TextReader r = null;
            try
            {
                if (publicKey == null || publicKey == "")
                {
                    r = new StreamReader("public.pem");
                    //获取秘钥
                    PemReader pemReader = new PemReader(r);     //载入私钥
                    PemObject readObject = pemReader.ReadPemObject();
                    AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(Convert.FromBase64String(System.Text.Encoding.Default.GetString(readObject.Content)));
                    engine.Init(true, pubKey);

                    //关闭pem读取流
                    pemReader.Reader.Dispose();
                    pemReader.Reader.Close();
                }
                else
                {
                    AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
                    engine.Init(true, pubKey);
                }
                //解密
                bytes = engine.ProcessBlock(data, 0, data.Length);

            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                r.Dispose();
                r.Close();
            }
            return bytes;
        }
    }
}

  

posted @ 2019-05-03 10:08  林台山人  阅读(236)  评论(0)    收藏  举报