简介:
由于在工作使用中需要各种语言进行RSA加密,并在Java端进行解密,但由于RSA再进行加解密时,由于待加密字符串长度有限制,故在不考虑性能得情况下,自己封装了一下加解密程序
java端代码如下:
package com.example.demo;
import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Base64;
public class RSAHelperBak {
/**
*私有数据成员,主要是公钥和私钥
*由程序自己产生,公钥需传递给通信另一方
*/
private static String publicKey;
private static String privateKey;
/**
* 产生公钥和私钥
*/
private static void genKeys() throws Exception{
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
//密钥位数
keyPairGen.initialize(1024);
//密钥对
KeyPair keyPair = keyPairGen.generateKeyPair();
// 公钥
PublicKey pubKey = (RSAPublicKey) keyPair.getPublic();
// 私钥
PrivateKey privKey = (RSAPrivateKey) keyPair.getPrivate();
publicKey= getKeyString(pubKey);
privateKey= getKeyString(privKey);
}
/**
*获取程序自动生成的公钥
* @return 返回公钥
*/
public static String getPubKey()
{
return publicKey;
}
/**
*获取程序自动生成的私钥
* @return 返回私钥
*/
public static String getPrivKey()
{
return privateKey;
}
/**
* 得到公钥
* @param key 密钥字符串(经过base64编码)
* @throws Exception
*/
public static PublicKey getPublicKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = Base64.getDecoder().decode(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
/**
* 得到私钥
* @param key 密钥字符串(经过base64编码)
* @throws Exception
*/
public static PrivateKey getPrivateKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = Base64.getDecoder().decode(key);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
/**
* 得到密钥字符串(经过base64编码)
* @return
*/
public static String getKeyString(Key key) throws Exception {
byte[] keyBytes = key.getEncoded();
String s = Base64.getEncoder().encodeToString(keyBytes);
return s;
}
/**
*利用Go语言产生的公钥加密
* @param pubkey_from_go 从服务器(go语言实现)获取的公钥
* @param plainText 需要加密的字符串
*/
public static String encByGoPubKey(String pubkey_from_go,String plainText) throws Exception {
//加解密类
Cipher cipher = Cipher.getInstance("RSA&