package com.ffcs.cop.pub.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.InvalidParameterException;
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.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* RSA工具类,实现RSA各种操作
* @author Administrator
*
*/
public class RSAUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(RSAUtils.class);
/** 算法名称 */
private static final String ALGORITHOM = "RSA";
/** 填充模式 RSA/ECB/NoPadding、RSA/ECB/PKCS1Padding */
private static final String FILL_MODE = "RSA/ECB/PKCS1Padding";
/** 密钥大小 */
private static final int KEY_SIZE = 1024;
/** 签名算法*/
public static final String DEFAULT_SIGNATURE_ALGORITHM = “md”;
/** RSA最大加密明文大小*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/** RSA最大解密密文大小*/
private static final int MAX_DECRYPT_BLOCK = 128;
private static KeyPairGenerator keyPairGen = null;
private static KeyFactory keyFactory = null;
static {
try {
keyPairGen = KeyPairGenerator.getInstance(ALGORITHOM);
keyFactory = KeyFactory.getInstance(ALGORITHOM);
} catch (NoSuchAlgorithmException ex) {
LOGGER.error(ex.getMessage());
}
}
private RSAUtils(){}
/**
* 生成并返回RSA密钥对。
*/
public static synchronized KeyPair generateKeyPair() {
try {
keyPairGen.initialize(KEY_SIZE);
// keyPairGen.initialize(KEY_SIZE, new SecureRandom(keyword.getBytes()));
// keyPairGen.initialize(KEY_SIZE, new SecureRandom(DateFormatUtils.format(Calendar.getInstance(), "yyyyMMdd").getBytes()));
return keyPairGen.generateKeyPair();
} catch (InvalidParameterException ex) {
LOGGER.error("KeyPairGenerator does not support a key length of " + KEY_SIZE + ".", ex);
}
return null;
}
/**
* 根据给定的系数和专用指数构造一个RSA专用的公钥对象。
*
* @param modulus 系数。
* @param publicExponent 专用指数。
* @return RSA专用公钥对象。
*/
public static PublicKey generatePublicKey(BigInteger modulus, BigInteger publicExponent) {
RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(modulus, publicExponent);
try {
return keyFactory.generatePublic(publicKeySpec);
} catch (InvalidKeySpecException ex) {
LOGGER.error("RSAPublicKeySpec is unavailable.", ex);
}
return null;
}
/**
* 根据给定的系数和专用指数构造一个RSA专用的公钥对象。
*
* @param modulus 系数。
* @param publicExponent 专用指数。
* @return RSA专用公钥对象。
*/
public static PublicKey generatePublicKey(byte[] modulus, byte[] publicExponent) {
return generatePublicKey(new BigInteger(modulus), new BigInteger(publicExponent));
}
/**
* 根据给定的16进制系数和专用指数字符串构造一个RSA专用的公钥对象。
*
* @param hexModulus 系数。
* @param hexPublicExponent 专用指数。
* @return RSA专用公钥对象。
*/
public static PublicKey generatePublidKey(String hexModulus, String hexPublicExponent) {
/*if(StringUtils.isBlank(hexModulus) || StringUtils.isBlank(hexPublicExponent)) {
if(LOGGER.isDebugEnabled()) {
LOGGER.debug("hexModulus and hexPublicExponent cannot be empty. return null(RSAPublicKey).");
}
return null;
}
byte[] modulus = null;
byte[] publicExponent = null;
try {
modulus = Hex.decodeHex(hexModulus.toCharArray());
publicExponent = Hex.decodeHex(hexPublicExponent.toCharArray());
} catch(DecoderException ex) {
LOGGER.error("hexModulus or hexPublicExponent value is invalid. return null(RSAPublicKey).");
}
if(modulus != null && publicExponent != null) {
return generatePublicKey(modulus, publicExponent);
}
return null;*/
BigInteger m = new BigInteger(hexModulus,16);
BigInteger e = new BigInteger(hexPublicExponent,16);
return generatePublicKey(m, e);
}
/**
* 根据给定的系数和专用指数构造一个RSA专用的私钥对象。
*
* @param modulus 系数。
* @param privateExponent 专用指数。
* @return RSA专用私钥对象。
*/
public static PrivateKey generatePrivateKey(BigInteger modulus, BigInteger privateExponent) {
RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(modulus, privateExponent);
try {
return keyFactory.generatePrivate(privateKeySpec);
} catch (InvalidKeySpecException ex) {
LOGGER.error("RSAPrivateKeySpec is unavailable.", ex);
}
return null;
}
/**
* 根据给定的系数和专用指数构造一个RSA专用的私钥对象。
*
* @param modulus 系数。
* @param privateExponent 专用指数。
* @return RSA专用私钥对象。
*/
public static PrivateKey generatePrivateKey(byte[] modulus, byte[] privateExponent) {
return generatePrivateKey(new BigInteger(modulus), new BigInteger(privateExponent));
}
/**
* 根据给定的16进制系数和专用指数字符串构造一个RSA专用的私钥对象。
*
* @param hexModulus 系数。
* @param hexPrivateExponent 专用指数。
* @return RSA专用私钥对象。
*/
public static PrivateKey generatePrivateKey(String hexModulus, String hexPrivateExponent) {
/*if(StringUtils.isBlank(hexModulus) || StringUtils.isBlank(hexPrivateExponent)) {
if(LOGGER.isDebugEnabled()) {
LOGGER.debug("hexModulus and hexPrivateExponent cannot be empty. RSAPrivateKey value is null to return.");
}
return null;
}
byte[] modulus = null;
byte[] privateExponent = null;
try {
modulus = Hex.decodeHex(hexModulus.toCharArray());
privateExponent = Hex.decodeHex(hexPrivateExponent.toCharArray());
} catch(DecoderException ex) {
LOGGER.error("hexModulus or hexPrivateExponent value is invalid. return null(RSAPrivateKey).");
}
if(modulus != null && privateExponent != null) {
return generatePrivateKey(modulus, privateExponent);
}
return null;*/
BigInteger m = new BigInteger(hexModulus,16);
BigInteger e = new BigInteger(hexPrivateExponent,16);
return generatePrivateKey(m, e);
}
/**
* 公钥对象转Base64串
* @param publicKey 公钥对象
* @return
*/
public static String publicKey2Base64(PublicKey publicKey){
return Base64.encodeBase64String(publicKey.getEncoded());
}
/**
* Base64公钥串转公钥对象
* @param publicKeyBase64Str Base64公钥
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey base642PublicKey(String publicKeyBase64Str) throws InvalidKeySpecException{
byte[] publicKeyBytes = Base64.decodeBase64(publicKeyBase64Str);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyBytes);
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
return publicKey;
}
/**
* 私钥对象转Base64串
* @param privateKey 私钥对象
* @return
*/
public static String privateKey2Base64(PrivateKey privateKey){
return Base64.encodeBase64String(privateKey.getEncoded());
}
/**
* Base64私钥串转私钥对象
* @param privateKeyBase64Str Base64公钥
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PrivateKey base642PrivateKey(String privateKeyBase64Str) throws InvalidKeySpecException{
byte[] privateKeyBytes = Base64.decodeBase64(privateKeyBase64Str);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
return privateKey;
}
/**
* <p>
* 用私钥对象对信息生成数字签名
* </p>
* @param signatureAlgorithm 签名算法
* @param data 已加密数据
* @param privateKey 私钥
*
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws SignatureException
*/
public static byte[] sign(String signatureAlgorithm, byte[] data, PrivateKey privateKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
Signature signature = Signature.getInstance(signatureAlgorithm);
signature.initSign(privateKey);
signature.update(data);
return signature.sign();
}
/**
* <p>
* 用私钥Base64串对信息生成数字签名
* </p>
* @param signatureAlgorithm 签名算法
* @param data 已加密数据
* @param privateKeyBase64Str 私钥(BASE64编码)
*
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws SignatureException
* @throws InvalidKeySpecException
*/
public static byte[] sign(String signatureAlgorithm, byte[] data, String privateKeyBase64Str) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, InvalidKeySpecException {
return sign(signatureAlgorithm, data, base642PrivateKey(privateKeyBase64Str));
}
/**
* <p>
* 默认签名算法用私钥对象对信息生成数字签名
* </p>
* @param data 已加密数据
* @param privateKey 私钥
*
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws SignatureException
*/
public static byte[] sign(byte[] data, PrivateKey privateKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
return sign(DEFAULT_SIGNATURE_ALGORITHM, data, privateKey);
}
/**
* <p>
* 默认签名算法用私钥Base64串对信息生成数字签名
* </p>
* @param data 已加密数据
* @param privateKeyBase64Str 私钥(BASE64编码)
*
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws SignatureException
* @throws InvalidKeySpecException
*/
public static byte[] sign(byte[] data, String privateKeyBase64Str) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, InvalidKeySpecException {
return sign(DEFAULT_SIGNATURE_ALGORITHM, data, privateKeyBase64Str);
}
/**
* <p>
* 根据指定签名算法,校验数字签名
* </p>
*
* @param data 签名的明文
* @param publicKey 公钥
* @param sign 数字签名
*
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws SignatureException
*
*/
public static boolean verify(String signatureAlgorithm, byte[] data, PublicKey publicKey, byte[] sign) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
Signature signature = Signature.getInstance(signatureAlgorithm);
signature.initVerify(publicKey);
signature.update(data);
return signature.verify(sign);
}
/**
* <p>
* 根据指定签名算法,校验数字签名
* </p>
*
* @param data 签名的明文
* @param publicKeyBase64Str 公钥(BASE64编码)
* @param sign 数字签名
*
* @return
* @throws InvalidKeySpecException
* @throws SignatureException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*
*/
public static boolean verify(String signatureAlgorithm, byte[] data, String publicKeyBase64Str, byte[] sign) throws InvalidKeyException, NoSuchAlgorithmException, SignatureException, InvalidKeySpecException{
return verify(signatureAlgorithm, data, base642PublicKey(publicKeyBase64Str), sign);
}
/**
* <p>
* 根据默认签名算法,校验数字签名
* </p>
*
* @param data 签名的明文
* @param publicKeyBase64Str 公钥(BASE64编码)
* @param sign 数字签名
*
* @return
* @throws InvalidKeySpecException
* @throws SignatureException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*
*/
public static boolean verify(byte[] data, String publicKeyBase64Str, byte[] sign) throws InvalidKeyException, NoSuchAlgorithmException, SignatureException, InvalidKeySpecException{
return verify(DEFAULT_SIGNATURE_ALGORITHM, data, publicKeyBase64Str, sign);
}
/**
* <p>
* 根据默认签名算法,校验数字签名
* </p>
*
* @param data 签名的明文
* @param publicKey 公钥
* @param sign 数字签名
*
* @return
* @throws InvalidKeySpecException
* @throws SignatureException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*
*/
public static boolean verify(byte[] data, PublicKey publicKey, byte[] sign) throws InvalidKeyException, NoSuchAlgorithmException, SignatureException, InvalidKeySpecException{
return verify(DEFAULT_SIGNATURE_ALGORITHM, data, publicKey, sign);
}
/**
* <p>
* 根据指定填充方式进行公钥加密
* </p>
* @param fillMode 填充方式
* @param data 源数据
* @param publicKey 公钥
* @return
* @throws Exception
*/
public static byte[] encrypt(String fillMode, byte[] data, PublicKey publicKey) throws GeneralSecurityException,IOException{
// 对数据加密
Cipher cipher = Cipher.getInstance(fillMode);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
/**
* <p>
* 根据指定填充方式进行公钥加密
* </p>
*
* @param fillMode 填充方式
* @param data 源数据
* @param publicKeyBase64Str 公钥(Base64编码)
* @return
* @throws Exception
*/
public static byte[] encrypt(String fillMode, byte[] data, String publicKeyBase64Str) throws GeneralSecurityException,IOException{
return encrypt(fillMode, data, base642PublicKey(publicKeyBase64Str));
}
/**
* <p>
* 根据默认填充方式进行公钥加密
* </p>
*
* @param data 源数据
* @param publicKey 公钥
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] data, PublicKey publicKey) throws GeneralSecurityException,IOException{
return encrypt(FILL_MODE, data, publicKey);
}
/**
* <p>
* 根据默认填充方式进行公钥加密
* </p>
*
* @param data 源数据
* @param publicKeyBase64Str 公钥(Base64编码)
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] data, String publicKeyBase64Str) throws GeneralSecurityException,IOException{
return encrypt(FILL_MODE, data, publicKeyBase64Str);
}
/**
* <P>
* 根据指定填充方式进行私钥解密
* </p>
* @param fillMode 填充方式
* @param encryptedData 已加密数据
* @param privateKey 私钥
* @return
* @throws Exception
*/
public static byte[] decrypt(String fillMode, byte[] encryptedData, PrivateKey privateKey) throws GeneralSecurityException,IOException {
Cipher cipher = Cipher.getInstance(fillMode);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
}
/**
* <P>
* 根据指定填充方式进行私钥解密
* </p>
* @param fillMode 填充方式
* @param encryptedData 已加密数据
* @param privateKeyBase64Str 私钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] decrypt(String fillMode, byte[] encryptedData, String privateKeyBase64Str) throws GeneralSecurityException,IOException {
return decrypt(fillMode, encryptedData, base642PrivateKey(privateKeyBase64Str));
}
/**
* <P>
* 根据默认填充方式进行私钥解密
* </p>
* @param encryptedData 已加密数据
* @param privateKeyBase64Str 私钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] encryptedData, String privateKeyBase64Str) throws GeneralSecurityException,IOException {
return decrypt(FILL_MODE, encryptedData, privateKeyBase64Str);
}
/**
* <P>
* 根据默认填充方式进行私钥解密
* </p>
* @param encryptedData 已加密数据
* @param privateKey 私钥
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] encryptedData, PrivateKey privateKey) throws GeneralSecurityException,IOException {
return decrypt(FILL_MODE, encryptedData, privateKey);
}
private static final char[] EOP_HEX_CHAR= {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
/**
* 转换方式字节数据转十六进制字符串
* @param data 输入数据
* @return 十六进制内容
*/
public static String byteArray2HexString(byte[] data){
StringBuilder stringBuilder= new StringBuilder();
for (int i=0; i<data.length; i++){
//取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移
stringBuilder.append(EOP_HEX_CHAR[(data[i] & 0xf0)>>> 4]);
//取出字节的低四位 作为索引得到相应的十六进制标识符
stringBuilder.append(EOP_HEX_CHAR[(data[i] & 0x0f)]);
if (i<data.length-1){
stringBuilder.append(' ');
}
}
return stringBuilder.toString().replace(" ", "");
}
/**
* 数组转换成十六进制字符串
* @param byte[]
* @return HexString
*/
/*public static final String byteArray2HexString(byte[] bArray) {
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = Integer.toHexString(0xFF & bArray[i]);
if (sTemp.length() < 2)
sb.append(0);
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}*/
/**
* 把16进制字符串转换成字节数组
*
* @param hex 16进制字符串
* @return byte[]
*/
public static byte[] hexString2ByteArray(String hex) {
hex = hex.toUpperCase();
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
}
return result;
}
private static int toByte(char c) {
byte b = (byte) "0123456789ABCDEF".indexOf(c);
return b;
}
}
RSAUtils工具类
最新推荐文章于 2024-03-19 18:38:26 发布