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)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/258071.html
標籤:區塊鏈
上一篇:集合體系中介面和類的特點總結
