1、RSAUtils.java类
package com.sangfor.vpn.client.service.utils;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
* Created by wk on 2017https://cdn.jxasp.com:9143/image/2/14.
private static String RSA = "RSA";
private static final int MAX_ENCRYPT_BLOCK = 117;
* 随机生成RSA密钥对(默认密钥长度为1024)
public static KeyPair generateRSAKeyPair()
return generateRSAKeyPair(1024);
public static KeyPair generateRSAKeyPair(int keyLength)
KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
kpg.initialize(keyLength);
} catch (NoSuchAlgorithmException e)
* 每次加密的字节数,不能超过密钥的长度值减去11
public static byte[] encryptData(byte[] data, PublicKey publicKey)
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
cache = cipher.doFinal(data, offSet, inputLen - offSet);
out.write(cache, 0, cache.length);
offSet = i * MAX_ENCRYPT_BLOCK;
byte[] encryptedData = out.toByteArray();
* 经过encryptedData()加密返回的byte数据
public static byte[] decryptData(byte[] encryptedData, PrivateKey privateKey)
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(encryptedData);
* 通过公钥byte[](publicKey.getEncoded())将公钥还原,适用于RSA算法
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
public static PublicKey getPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException,
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
* 通过私钥byte[]将公钥还原,适用于RSA算法
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
public static PrivateKey getPrivateKey(byte[] keyBytes) throws NoSuchAlgorithmException,
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
public static PublicKey getPublicKey(String modulus, String publicExponent)
throws NoSuchAlgorithmException, InvalidKeySpecException
BigInteger bigIntModulus = new BigInteger(modulus);
BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
public static PrivateKey getPrivateKey(String modulus, String privateExponent)
throws NoSuchAlgorithmException, InvalidKeySpecException
BigInteger bigIntModulus = new BigInteger(modulus);
BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
public static PublicKey loadPublicKey(String publicKeyStr) throws Exception
byte[] buffer = Base64Utils.decode(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e)
throw new Exception("无此算法");
} catch (InvalidKeySpecException e)
throw new Exception("公钥非法");
} catch (NullPointerException e)
throw new Exception("公钥数据为空");
* 加载时使用的是PKCS8EncodedKeySpec(PKCS#8编码的Key指令)。
public static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception
byte[] buffer = Base64Utils.decode(privateKeyStr);
// X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e)
throw new Exception("无此算法");
} catch (InvalidKeySpecException e)
throw new Exception("私钥非法");
} catch (NullPointerException e)
throw new Exception("私钥数据为空");
public static PublicKey loadPublicKey(InputStream in) throws Exception
return loadPublicKey(readKey(in));
throw new Exception("公钥数据流读取错误");
} catch (NullPointerException e)
throw new Exception("公钥输入流为空");
public static PrivateKey loadPrivateKey(InputStream in) throws Exception
return loadPrivateKey(readKey(in));
throw new Exception("私钥数据读取错误");
} catch (NullPointerException e)
throw new Exception("私钥输入流为空");
private static String readKey(InputStream in) throws IOException
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null)
if (readLine.charAt(0) == '-')
public static void printPublicKeyInfo(PublicKey publicKey)
RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
System.out.println("----------RSAPublicKey----------");
System.out.println("Modulus.length=" + rsaPublicKey.getModulus().bitLength());
System.out.println("Modulus=" + rsaPublicKey.getModulus().toString());
System.out.println("PublicExponent.length=" + rsaPublicKey.getPublicExponent().bitLength());
System.out.println("PublicExponent=" + rsaPublicKey.getPublicExponent().toString());
public static void printPrivateKeyInfo(PrivateKey privateKey)
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
System.out.println("----------RSAPrivateKey ----------");
System.out.println("Modulus.length=" + rsaPrivateKey.getModulus().bitLength());
System.out.println("Modulus=" + rsaPrivateKey.getModulus().toString());
System.out.println("PrivateExponent.length=" + rsaPrivateKey.getPrivateExponent().bitLength());
System.out.println("PrivatecExponent=" + rsaPrivateKey.getPrivateExponent().toString());
2、Base64Utils.java类
package com.sangfor.vpn.client.service.utils;
import java.io.UnsupportedEncodingException;
* Created by wk on 2017https://cdn.jxasp.com:9143/image/2/14.
public class Base64Utils {
private static char[] base64EncodeChars = new char[]
{ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', '+', '/' };
private static byte[] base64DecodeChars = new byte[]
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53,
54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1,
public static String encode(byte[] data)
StringBuffer sb = new StringBuffer();
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
sb.append(base64EncodeChars[b3 & 0x3f]);
public static byte[] decode(String str)
return decodePrivate(str);
} catch (UnsupportedEncodingException e)
private static byte[] decodePrivate(String str) throws UnsupportedEncodingException
StringBuffer sb = new StringBuffer();
data = str.getBytes("US-ASCII");
b1 = base64DecodeChars[data[i++]];
} while (i < len && b1 == -1);
b2 = base64DecodeChars[data[i++]];
} while (i < len && b2 == -1);
sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));
return sb.toString().getBytes("iso8859-1");
b3 = base64DecodeChars[b3];
} while (i < len && b3 == -1);
sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));
return sb.toString().getBytes("iso8859-1");
b4 = base64DecodeChars[b4];
} while (i < len && b4 == -1);
sb.append((char) (((b3 & 0x03) << 6) | b4));
return sb.toString().getBytes("iso8859-1");
3、SecurityUtils类
package com.sangfor.vpn.client.service.utils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.security.PrivateKey;
import java.security.PublicKey;
public class SecurityUtils {
public static String decrypt(String cipherText) throws Exception{
FileInputStream inPrivate = new FileInputStream(
SecurityUtils.class.getClassLoader().getResource("").getPath() + "/pkcs8_private_key.pem");
PrivateKey privateKey = RSAUtils.loadPrivateKey(inPrivate);
byte[] decryptByte = RSAUtils.decryptData(Base64Utils.decode(cipherText), privateKey);
String decryptStr = new String(decryptByte,"utf-8");
public static String encrypt(String plainTest) throws Exception{
PublicKey publicKey = RSAUtils.loadPublicKey(plainTest);
byte[] encryptByte = RSAUtils.encryptData(plainTest.getBytes(), publicKey);
String afterencrypt = Base64Utils.encode(encryptByte);
public static String encrypt(String plainTest, String key) throws Exception{
PublicKey publicKey = RSAUtils.loadPublicKey(key);
byte[] encryptByte = RSAUtils.encryptData(plainTest.getBytes(), publicKey);
String afterencrypt = Base64Utils.encode(encryptByte);