RSA非对称性加密
RSA工具类
package com.example.base.utils;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
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.HashMap;
import java.util.Map;
public class RsaUtil {
private static final Logger logger = LoggerFactory.getLogger(RsaUtil.class);
private static final String ALGORITHMSTR = "RSA";
private static final String DEFAULT_CHAR_SET = "UTF-8";
private static final String PUBLIC_KEY = "RSAPublicKey";
private static final String PRIVATE_KEY = "RSAPrivateKey";
public static Map<String, String> genKeyPair(){
Map<String, String> keyMap = new HashMap<>(2);
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHMSTR);
keyPairGen.initialize(1024, new SecureRandom());
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()), DEFAULT_CHAR_SET);
String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())), DEFAULT_CHAR_SET);
keyMap.put(PUBLIC_KEY, publicKeyString);
keyMap.put(PRIVATE_KEY, privateKeyString);
}catch (Exception e){
logger.error("RsaUtil | method=genKeyPair() is error, error_msg:{}, error:{}",e.getMessage(),e);
}
return keyMap;
}
public static String getPublicKey(Map<String, String> keyMap) {
String key = keyMap.get(PUBLIC_KEY);
return (null != key && !"".equals(key)) ? key : null;
}
public static String getPrivateKey(Map<String, String> keyMap) {
String key = keyMap.get(PRIVATE_KEY);
return (null != key && !"".equals(key)) ? key : null;
}
public static String encrypt(String content, String publicKey) throws Exception {
byte[] keyBytes = Base64.decodeBase64(publicKey);
RSAPublicKey rsaPublicKey = (RSAPublicKey) KeyFactory.getInstance(ALGORITHMSTR).generatePublic(new X509EncodedKeySpec(keyBytes));
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
int offSet = 0;
int offlimt = 117;
byte[] bytes = content.getBytes(DEFAULT_CHAR_SET);
byte[] outBytes = splitBytes(cipher, offSet, offlimt, bytes);
return Base64.encodeBase64String(outBytes);
}
public static String decrypt(String encrypt, String privateKey) throws Exception {
byte[] bytes = Base64.decodeBase64(encrypt.getBytes(DEFAULT_CHAR_SET));
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(ALGORITHMSTR).generatePrivate(new PKCS8EncodedKeySpec(decoded));
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.DECRYPT_MODE, priKey);
int offSet = 0;
int offlimt = 128;
byte[] outBytes = splitBytes(cipher, offSet, offlimt, bytes);
return new String(outBytes, DEFAULT_CHAR_SET);
}
private static byte[] splitBytes(Cipher cipher, int offSet, int offlimt, byte[] bytes) throws BadPaddingException, IllegalBlockSizeException, IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int length = bytes.length;
while (length - offSet > 0){
byte[] cache;
if(length - offSet > offlimt){
cache = cipher.doFinal(bytes, offSet, offlimt);
}else{
cache = cipher.doFinal(bytes, offSet, length - offSet);
}
out.write(cache, 0, cache.length);
offSet += offlimt;
}
byte[] outBytes = out.toByteArray();
out.close();
return outBytes;
}
public static String sign(String content, String privateKey) throws Exception {
String signatureAlgorithm = "MD5withRSA";
byte[] keyBytes = Base64.decodeBase64(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHMSTR);
PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Signature signature = Signature.getInstance(signatureAlgorithm);
signature.initSign(privateK);
signature.update(content.getBytes(DEFAULT_CHAR_SET));
return Base64.encodeBase64String(signature.sign());
}
public static boolean verify(String content, String publicKey, String sign) throws Exception {
String signatureAlgorithm = "MD5withRSA";
byte[] keyBytes = Base64.decodeBase64(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHMSTR);
PublicKey publicK = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(signatureAlgorithm);
signature.initVerify(publicK);
signature.update(content.getBytes(DEFAULT_CHAR_SET));
return signature.verify(Base64.decodeBase64(sign));
}
public static void main(String[] args) throws Exception {
String content = "这是一个测试方法";
Map<String, String> keyMap = genKeyPair();
String publicKey = getPublicKey(keyMap);
System.out.println("公钥:" + publicKey);
String privateKey = getPrivateKey(keyMap);
System.out.println("私钥:" + privateKey);
String encrypt = encrypt(content, publicKey);
System.out.println("加密后:" + encrypt);
String decrypt = decrypt(encrypt, privateKey);
System.out.println("解密后:" + decrypt);
String sign = sign(content, privateKey);
System.out.println("签名:" + sign);
System.out.println("验证:" + verify(content, publicKey, sign));
}
}