Rsa算法是非对称加密,一般公钥加密,私钥解密,本文主要解决java端生成密钥对,使用公钥加密数据,把私钥发给golang端,golang端使用私钥解密,支持大数据的分段加密。
java代码:
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.ArrayUtils;
import javax.crypto.Cipher;
import java.io.*;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
public class RSAEncrypt {
private static Map<Integer, String> keyMap = new HashMap<Integer, String>(); //用于封装随机产生的公钥与私钥
public static void main(String[] args) throws Exception {
//生成公钥和私钥
genKeyPair();
//加密字符串
String message = readString4("D:\\3575.txt");
System.out.println("随机生成的公钥为:" + keyMap.get(0));
System.out.println("随机生成的私钥为:" + keyMap.get(1));
String messageEn = encrypt(message,keyMap.get(0));
// System.out.println(message + "\t加密后的字符串为:" + messageEn);
FileOutputStream os = new FileOutputStream("D:\\3575.dat");
os.write(messageEn.getBytes());
String messageDe = decrypt(messageEn,keyMap.get(1));
// System.out.println("还原后的字符串为:" + messageDe);
}
private static String readString4(String filePath)
{
int len=0;
StringBuffer str=new StringBuffer("");
File file=new File(filePath);
try {
FileInputStream is=new FileInputStream(file);
InputStreamReader isr= new InputStreamReader(is);
BufferedReader in= new BufferedReader(isr);
String line=null;
while( (line=in.readLine())!=null )
{
if(len != 0) // 处理换行符的问题
{
str.append("\r\n"+line);
}
else
{
str.append(line);
}
len++;
}
in.close();
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str.toString();
}
/**
* 随机生成密钥对
* @throws NoSuchAlgorithmException
*/
public static void genKeyPair() throws NoSuchAlgorithmException {
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// 初始化密钥对生成器,密钥大小为96-1024位
keyPairGen.initialize(1024,new SecureRandom());
// 生成一个密钥对,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 得到私钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 得到公钥
String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
// 得到私钥字符串
String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
// 将公钥和私钥保存到Map
keyMap.put(0,publicKeyString); //0表示公钥
keyMap.put(1,privateKeyString); //1表示私钥
}
/**
* RSA公钥加密
*
* @param str
* 加密字符串
* @param publicKey
* 公钥
* @return 密文
* @throws Exception
* 加密过程中的异常信息
*/
public static String encrypt( String str, String publicKey ) throws Exception{
//base64编码的公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
//RSA加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] b = str.getBytes("utf-8");
byte[] b1 = null;
/** 执行加密操作 */
for (int i = 0; i < b.length; i += 117) {
byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(b, i,i + 117));
b1 = ArrayUtils.addAll(b1, doFinal);
}
String outStr = Base64.encodeBase64String(b1);
return outStr;
}
/**
* RSA私钥解密
*
* @param str
* 加密字符串
* @param privateKey
* 私钥
* @return 铭文
* @throws Exception
* 解密过程中的异常信息
*/
public static String decrypt(String str, String privateKey) throws Exception{
//64位解码加密后的字符串
byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
//base64编码的私钥
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
byte[] b1 = inputByte;
/** 执行解密操作 */
byte[] b = null;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < b1.length; i += 128) {
byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(b1, i, i + 128));
sb.append(new String(doFinal,"utf-8"));
}
return sb.toString();
}
}
把java生成好的私钥发给golang端,这里只截取的一个代码,具体git地址:https://github.com/Lyafei/go-rsa
package gorsa
import (
"bytes"
"errors"
"crypto"
"crypto/sha1"
"crypto/rand"
"crypto/sha256"
"crypto/rsa"
"encoding/base64"
"io/ioutil"
)
var RSA = &RSASecurity{}
type RSASecurity struct {
pubStr string //公钥字符串
priStr string //私钥字符串
pubkey *rsa.PublicKey //公钥
prikey *rsa.PrivateKey //私钥
}
// 设置公钥
func (rsas *RSASecurity) SetPublicKey(pubStr string) (err error) {
rsas.pubStr = pubStr
rsas.pubkey, err = rsas.GetPublickey()
return err
}
// 设置私钥
func (rsas *RSASecurity) SetPrivateKey(priStr string) (err error) {
rsas.priStr = priStr
rsas.prikey, err = rsas.GetPrivatekey()
return err
}
// *rsa.PublicKey
func (rsas *RSASecurity) GetPrivatekey() (*rsa.PrivateKey, error) {
return getPriKey([]byte(rsas.priStr))
}
// *rsa.PrivateKey
func (rsas *RSASecurity) GetPublickey() (*rsa.PublicKey, error) {
return getPubKey([]byte(rsas.pubStr))
}
// 公钥加密
func (rsas *RSASecurity) PubKeyENCTYPT(input []byte) ([]byte, error) {
if rsas.pubkey == nil {
return []byte(""), errors.New(`Please set the public key in advance`)
}
output := bytes.NewBuffer(nil)
err := pubKeyIO(rsas.pubkey, bytes.NewReader(input), output, true)
if err != nil {
return []byte(""), err
}
return ioutil.ReadAll(output)
}
// 公钥解密
func (rsas *RSASecurity) PubKeyDECRYPT(input []byte) ([]byte, error) {
if rsas.pubkey == nil {
return []byte(""), errors.New(`Please set the public key in advance`)
}
output := bytes.NewBuffer(nil)
err := pubKeyIO(rsas.pubkey, bytes.NewReader(input), output, false)
if err != nil {
return []byte(""), err
}
return ioutil.ReadAll(output)
}
// 私钥加密
func (rsas *RSASecurity) PriKeyENCTYPT(input []byte) ([]byte, error) {
if rsas.prikey == nil {
return []byte(""), errors.New(`Please set the private key in advance`)
}
output := bytes.NewBuffer(nil)
err := priKeyIO(rsas.prikey, bytes.NewReader(input), output, true)
if err != nil {
return []byte(""), err
}
return ioutil.ReadAll(output)
}
// 私钥解密
func (rsas *RSASecurity) PriKeyDECRYPT(input []byte) ([]byte, error) {
if rsas.prikey == nil {
return []byte(""), errors.New(`Please set the private key in advance`)
}
output := bytes.NewBuffer(nil)
err := priKeyIO(rsas.prikey, bytes.NewReader(input), output, false)
if err != nil {
return []byte(""), err
}
return ioutil.ReadAll(output)
}
/**
* 使用RSAWithSHA1算法签名
*/
func (rsas *RSASecurity) SignSha1WithRsa(data string) (string, error) {
sha1Hash := sha1.New()
s_data := []byte(data)
sha1Hash.Write(s_data)
hashed := sha1Hash.Sum(nil)
signByte, err := rsa.SignPKCS1v15(rand.Reader, rsas.prikey, crypto.SHA1, hashed)
sign := base64.StdEncoding.EncodeToString(signByte)
return string(sign), err
}
/**
* 使用RSAWithSHA256算法签名
*/
func (rsas *RSASecurity) SignSha256WithRsa(data string) (string, error) {
sha256Hash := sha256.New()
s_data := []byte(data)
sha256Hash.Write(s_data)
hashed := sha256Hash.Sum(nil)
signByte, err := rsa.SignPKCS1v15(rand.Reader, rsas.prikey, crypto.SHA256, hashed)
sign := base64.StdEncoding.EncodeToString(signByte)
return string(sign), err
}
/**
* 使用RSAWithSHA1验证签名
*/
func (rsas *RSASecurity) VerifySignSha1WithRsa(data string, signData string) error {
sign, err := base64.StdEncoding.DecodeString(signData)
if err != nil {
return err
}
hash := sha1.New()
hash.Write([]byte(data))
return rsa.VerifyPKCS1v15(rsas.pubkey, crypto.SHA1, hash.Sum(nil), sign)
}
/**
* 使用RSAWithSHA256验证签名
*/
func (rsas *RSASecurity) VerifySignSha256WithRsa(data string, signData string) error {
sign, err := base64.StdEncoding.DecodeString(signData)
if err != nil {
return err
}
hash := sha256.New()
hash.Write([]byte(data))
return rsa.VerifyPKCS1v15(rsas.pubkey, crypto.SHA256, hash.Sum(nil), sign)
}