跳到主要内容

Go 与 Java Rsa加密算法

· 阅读需 4 分钟
ahKevinXy

⚡️ 和 甲方对接系统 遇到 java Rsa 加密 go 无法解密的问题

备注
  1. go 生成的公钥 不能直接给Java使用
  2. java的 公钥 需要把 go 生成的头 -----BEGIN RSA Public Key----------END RSA Public Key----- 删除 不能保存即可

go 代码

package rsa

import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"os"
)

//RSA解密
func Decrypt(cipherText []byte, path string) []byte {
//打开文件
file, err := os.Open(path)
if err != nil {
panic(err)
}
defer file.Close()
//获取文件内容
info, _ := file.Stat()
buf := make([]byte, info.Size())
file.Read(buf)
//pem解码
block, _ := pem.Decode(buf)
//X509解码
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
panic(err)
}
//对密文进行解密
plainText, _ := rsa.DecryptPKCS1v15(rand.Reader, privateKey, cipherText)
//返回明文
return plainText
}

// DecryptByString
// @Description: 解密
// @Author ahKevinXy
// @Date 2022-11-22 16:50:15
func DecryptByString(cipherText string, key string) []byte {
//打开文件
content := Base64Decode(cipherText)
//X509解码

block, _ := pem.Decode([]byte(key))

privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
panic(err)
}
//对密文进行解密
plainText, _ := rsa.DecryptPKCS1v15(rand.Reader, privateKey, content)
//返回明文
return plainText
}

//RSA加密 通过私钥路径
func Encrypt(plainText []byte, path string) []byte {
//打开文件
file, err := os.Open(path)
if err != nil {
panic(err)
}

defer file.Close()
//读取文件的内容
info, _ := file.Stat()
buf := make([]byte, info.Size())
file.Read(buf)
//pem解码
block, _ := pem.Decode(buf)
//x509解码
publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
panic(err)
}
//类型断言
publicKey := publicKeyInterface.(*rsa.PublicKey)
//对明文进行加密
cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plainText)
if err != nil {
panic(err)
}
//返回密文
return cipherText
}

// 通过直接传 string 方式
func EncryptByString(plainText string, public string) string {

block, _ := pem.Decode([]byte(public))
//x509解码
publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
panic(err)
}
//类型断言
publicKey := publicKeyInterface.(*rsa.PublicKey)
//对明文进行加密
cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, []byte(plainText))
if err != nil {
panic(err)
}
fmt.Println(cipherText)
//返回密文
fmt.Println(string(cipherText))

return Base64EncodeString(string(cipherText))

}

func Base64EncodeString(str string) string {
return base64.StdEncoding.EncodeToString([]byte(str))
}

// Base64Decode
// @Description: base64解码
// @Author ahKevinXy
// @Date 2022-11-22 17:04:52
func Base64Decode(data string) []byte {
decodedByte, _ := base64.StdEncoding.DecodeString(data)
return decodedByte
}

java 代码


import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;



public class RSATest {

public static final String KEY_ALGORITHM = "RSA";
// 公钥
private static final String PUBLIC_KEY = "xxxxx加密公钥";
private static final int MAX_ENCRYPT_BLOCK = 117;
private static final int MAX_DECRYPT_BLOCK = 128;
public static void main(String[] args) throws Exception {

String cipherText;
String content = "这是一个测试加密密码";
String publicKey = PUBLIC_KEY;

cipherText = encrypt(content, publicKey);
System.out.println(cipherText);
}



// 获取公钥
public static PublicKey getPublicKey(String publicKeyString) throws NoSuchAlgorithmException, InvalidKeySpecException {
byte[] publicKeyByte = Base64.getDecoder().decode(publicKeyString);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyByte);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
return keyFactory.generatePublic(keySpec);
}
public static String encrypt(String text, String publicKeyStr) {
try {

Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKeyStr));
byte[] tempBytes = cipher.doFinal(text.getBytes("UTF-8"));
return Base64.getEncoder().encodeToString(tempBytes);
} catch (Exception e) {
throw new RuntimeException("加密字符串[" + text + "]时遇到异常", e);
}
}





}