
club.zhcs.utils.codec.RSA Maven / Gradle / Ivy
package club.zhcs.utils.codec;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
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 javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.nutz.lang.Files;
import org.nutz.lang.Lang;
import org.nutz.repo.Base64;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
*
* @author Kerbores([email protected])
*
*/
public class RSA {
private static final String RSA_GCM = "RSA";
private RSA() {}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class KeyPair {
String publicKey;
String privateKey;
}
/**
* 生成公私钥对
*
* @return 公私钥对
*/
public static KeyPair genKeyPair() {
KeyPairGenerator keyPairGen = null;
try {
keyPairGen = KeyPairGenerator.getInstance("RSA");
}
catch (NoSuchAlgorithmException e) {
throw Lang.wrapThrow(e);
}
keyPairGen.initialize(2048, new SecureRandom());
java.security.KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
String publicKeyString = Base64.encodeToString(publicKey.getEncoded(), false);
String privateKeyString = Base64.encodeToString(privateKey.getEncoded(), false);
return KeyPair.builder()
.publicKey(publicKeyString)
.privateKey(privateKeyString)
.build();
}
/**
* 随机生成密钥对
*
* @param filePath
* keystore path
*/
public static void genKeyPair(String filePath) {
KeyPairGenerator keyPairGen = null;
try {
keyPairGen = KeyPairGenerator.getInstance("RSA");
}
catch (NoSuchAlgorithmException e) {
throw Lang.wrapThrow(e);
}
keyPairGen.initialize(2048, new SecureRandom());
java.security.KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
try {
String publicKeyString = Base64.encodeToString(publicKey.getEncoded(), false);
String privateKeyString = Base64.encodeToString(privateKey.getEncoded(), false);
Files.write(filePath + "/publicKey.keystore", publicKeyString);
Files.write(filePath + "/privateKey.keystore", privateKeyString);
}
catch (Exception e) {
throw Lang.wrapThrow(e);
}
}
/**
* 从文件中输入流中加载公钥
*
* @param path
* 公钥路径
* @return 公钥
*/
public static String loadPublicKeyByFile(String path) {
try (BufferedReader br = new BufferedReader(new FileReader(path
+ "/publicKey.keystore"))) {
String readLine = null;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
sb.append(readLine);
}
return sb.toString();
}
catch (IOException e) {
throw Lang.makeThrow("公钥数据流读取错误");
}
catch (NullPointerException e) {
throw Lang.makeThrow("公钥输入流为空");
}
}
/**
* 从文件中加载私钥
*
* @param path
* 私钥路径
* @return 私钥
*/
public static String loadPrivateKeyByFile(String path) {
try (BufferedReader br = new BufferedReader(new FileReader(path
+ "/privateKey.keystore"))) {
String readLine = null;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
sb.append(readLine);
}
return sb.toString();
}
catch (IOException e) {
throw Lang.makeThrow("私钥数据读取错误");
}
catch (NullPointerException e) {
throw Lang.makeThrow("私钥输入流为空");
}
}
/**
* 从字符串中加载公钥
*
* @param publicKeyStr
* 公钥字符串
* @return 公钥
*/
public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr) {
try {
byte[] buffer = Base64.decode(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
}
catch (NoSuchAlgorithmException e) {
throw Lang.makeThrow("无此算法");
}
catch (InvalidKeySpecException e) {
throw Lang.makeThrow("公钥非法");
}
catch (NullPointerException e) {
throw Lang.makeThrow("公钥数据为空");
}
}
/**
* 字符串中加载私钥
*
* @param privateKeyStr
* 私钥字符串
* @return 私钥
*/
public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr) {
try {
byte[] buffer = Base64.decode(privateKeyStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
}
catch (NoSuchAlgorithmException e) {
throw Lang.makeThrow("无此算法");
}
catch (InvalidKeySpecException e) {
throw Lang.makeThrow("私钥非法");
}
catch (NullPointerException e) {
throw Lang.makeThrow("私钥数据为空");
}
}
/**
* 使用公钥加密明文
*
* @param publicKey
* 公钥
* @param plainTextData
* 明文
* @return 密文
*/
public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData) {
if (publicKey == null) {
throw Lang.makeThrow("加密公钥为空, 请设置");
}
Cipher cipher = null;
try {
// 使用默认RSA
cipher = Cipher.getInstance(RSA_GCM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(plainTextData);
}
catch (NoSuchAlgorithmException e) {
throw Lang.makeThrow("无此加密算法");
}
catch (NoSuchPaddingException e) {
throw Lang.wrapThrow(e);
}
catch (InvalidKeyException e) {
throw Lang.makeThrow("加密公钥非法,请检查");
}
catch (IllegalBlockSizeException e) {
throw Lang.makeThrow("明文长度非法");
}
catch (BadPaddingException e) {
throw Lang.makeThrow("明文数据已损坏");
}
}
/**
* 使用私钥加密明文
*
* @param privateKey
* 私钥
* @param plainTextData
* 明文
* @return 密文
*/
public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData) {
if (privateKey == null) {
throw Lang.makeThrow("加密私钥为空, 请设置");
}
Cipher cipher = null;
try {
// 使用默认RSA
cipher = Cipher.getInstance(RSA_GCM);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return cipher.doFinal(plainTextData);
}
catch (NoSuchAlgorithmException e) {
throw Lang.makeThrow("无此加密算法");
}
catch (NoSuchPaddingException e) {
throw Lang.wrapThrow(e);
}
catch (InvalidKeyException e) {
throw Lang.makeThrow("加密私钥非法,请检查");
}
catch (IllegalBlockSizeException e) {
throw Lang.makeThrow("明文长度非法");
}
catch (BadPaddingException e) {
throw Lang.makeThrow("明文数据已损坏");
}
}
/**
* 使用公钥加密明文
*
* @param publicKey
* 公钥
* @param plainTextData
* 明文
* @return 密文
*/
public static String encryptToString(RSAPublicKey publicKey, byte[] plainTextData) {
return Base64.encodeToString(encrypt(publicKey, plainTextData), false);
}
/**
* 使用私钥加密明文
*
* @param privateKey
* 私钥
* @param plainTextData
* 明文
* @return 密文
*/
public static String encryptToString(RSAPrivateKey privateKey, byte[] plainTextData) {
return Base64.encodeToString(encrypt(privateKey, plainTextData), false);
}
/**
* 使用公钥加密明文
*
* @param publicKey
* 公钥
* @param plainText
* 明文
* @return 密文
*/
public static String encryptToString(RSAPublicKey publicKey, String plainText) {
return encryptToString(publicKey, plainText.getBytes());
}
/**
* 使用私钥加密明文
*
* @param privateKey
* 私钥
* @param plainText
* 明文
* @return 密文
*/
public static String encryptToString(RSAPrivateKey privateKey, String plainText) {
return encryptToString(privateKey, plainText.getBytes());
}
/**
* 使用公钥加密明文
*
* @param publicKey
* 公钥
* @param plainText
* 明文
* @return 密文
*/
public static String encryptUsePublicKey(String publicKey, String plainText) {
return encryptToString(loadPublicKeyByStr(publicKey), plainText.getBytes());
}
/**
* 使用私钥加密明文
*
* @param privateKey
* 私钥
* @param plainText
* 明文
* @return 密文
*/
public static String encryptUsePrivateKey(String privateKey, String plainText) {
return encryptToString(loadPrivateKeyByStr(privateKey), plainText.getBytes());
}
/**
* 使用私钥解码
*
* @param privateKey
* 私钥
* @param cipherData
* 密文
* @return 明文
*/
public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) {
if (privateKey == null) {
throw Lang.makeThrow("解密私钥为空, 请设置");
}
Cipher cipher = null;
try {
// 使用默认RSA
cipher = Cipher.getInstance(RSA_GCM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(cipherData);
}
catch (NoSuchAlgorithmException e) {
throw Lang.makeThrow("无此解密算法");
}
catch (NoSuchPaddingException e) {
throw Lang.wrapThrow(e);
}
catch (InvalidKeyException e) {
throw Lang.makeThrow("解密私钥非法,请检查");
}
catch (IllegalBlockSizeException e) {
throw Lang.makeThrow("密文长度非法");
}
catch (BadPaddingException e) {
throw Lang.makeThrow("密文数据已损坏");
}
}
/**
* 使用公钥解密
*
* @param publicKey
* 公钥
* @param cipherData
* 密文
* @return 明文
*/
public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData) {
if (publicKey == null) {
throw Lang.makeThrow("解密公钥为空, 请设置");
}
Cipher cipher = null;
try {
// 使用默认RSA
cipher = Cipher.getInstance(RSA_GCM);
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(cipherData);
}
catch (NoSuchAlgorithmException e) {
throw Lang.makeThrow("无此解密算法");
}
catch (NoSuchPaddingException e) {
throw Lang.wrapThrow(e);
}
catch (InvalidKeyException e) {
throw Lang.makeThrow("解密公钥非法,请检查");
}
catch (IllegalBlockSizeException e) {
throw Lang.makeThrow("密文长度非法");
}
catch (BadPaddingException e) {
throw Lang.makeThrow("密文数据已损坏");
}
}
/**
* 使用私钥解密
*
* @param privateKey
* 私钥
* @param cipherData
* 密文
* @return 明文
*/
public static String decryptToString(RSAPrivateKey privateKey, byte[] cipherData) {
return new String(decrypt(privateKey, cipherData));
}
/**
* 使用公钥解密
*
* @param publicKey
* 公钥
* @param cipherData
* 密文
* @return 明文
*/
public static String decryptToString(RSAPublicKey publicKey, byte[] cipherData) {
return new String(decrypt(publicKey, cipherData));
}
/**
* 使用私钥解密
*
* @param privateKey
* 私钥
* @param cipher
* 密文
* @return 明文
*/
public static String decryptToString(RSAPrivateKey privateKey, String cipher) {
return decryptToString(privateKey, Base64.decode(cipher));
}
/**
* 使用公钥解密
*
* @param publicKey
* 公钥
* @param cipher
* 密文
* @return 明文
*/
public static String decryptToString(RSAPublicKey publicKey, String cipher) {
return decryptToString(publicKey, Base64.decode(cipher));
}
/**
* 使用私钥解密
*
* @param privateKey
* 私钥
* @param cipher
* 密文
* @return 明文
*/
public static String decryptUsePrivateKey(String privateKey, String cipher) {
return decryptToString(loadPrivateKeyByStr(privateKey), cipher);
}
/**
* 使用公钥解密
*
* @param publicKey
* 公钥
* @param cipher
* 密文
* @return 明文
*/
public static String decryptUsePublicKey(String publicKey, String cipher) {
return decryptToString(loadPublicKeyByStr(publicKey), cipher);
}
/**
* 私钥签名
*
* @param plainText
* 明文
* @param privateKey
* 私钥
* @return 签名信息
*/
public static String sign(String plainText, PrivateKey privateKey) {
Signature privateSignature;
try {
privateSignature = Signature.getInstance("SHA256withRSA");
privateSignature.initSign(privateKey);
privateSignature.update(plainText.getBytes());
byte[] signature = privateSignature.sign();
return Base64.encodeToString(signature, false);
}
catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
throw Lang.wrapThrow(e);
}
}
/**
* 私钥签名
*
* @param plainText
* 明文
* @param privateKey
* 私钥
* @return 签名信息
*/
public static String sign(String plainText, String privateKey) {
return sign(plainText, loadPrivateKeyByStr(privateKey));
}
/**
* 签名验证
*
* @param plainText
* 明文
* @param signature
* 签名值
* @param publicKey
* 公钥
* @return 是否通过验证
*/
public static boolean verify(String plainText, String signature, PublicKey publicKey) {
Signature publicSignature;
try {
publicSignature = Signature.getInstance("SHA256withRSA");
publicSignature.initVerify(publicKey);
publicSignature.update(plainText.getBytes());
byte[] signatureBytes = Base64.decode(signature);
return publicSignature.verify(signatureBytes);
}
catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
throw Lang.wrapThrow(e);
}
}
/**
* 签名验证
*
* @param plainText
* 明文
* @param signature
* 签名值
* @param publicKey
* 公钥
* @return 是否通过验证
*/
public static boolean verify(String plainText, String signature, String publicKey) {
return verify(plainText, signature, loadPublicKeyByStr(publicKey));
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy