决策平台http认证服务器。
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

265 lines
8.0 KiB

package helper;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RSAUtils {
private static final int FRAGMENT_LENGTH = 245;
private static final int FRAGMENT_LENGTH_DECRYPT = 256;
/**
* RSA加密
*
* @param plainText 要加密的文本内容
* @param publicKey 用于加密的公钥
* @return 加密后的内容
*/
public static String encrypt(String plainText, Key publicKey) {
if (StringUtils.isEmpty(plainText)) {
return plainText;
}
try {
byte[] publicEncrypt = encrypt(plainText.getBytes(EncodeConstants.ENCODING_UTF_8), publicKey);
return RSAUtils.byte2Base64(publicEncrypt);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
/**
* RSA解密
*
* @param cipherText 密文数据
* @return 解密后的内容
*/
public static String decrypt(String cipherText, Key privateKey) {
if (StringUtils.isEmpty(cipherText)) {
return cipherText;
}
byte[] bytes = null;
try {
bytes = decrypt(base642Byte(cipherText), privateKey);
} catch (Exception e) {
LoggerFactory.getLogger().error(e.getMessage(), e);
}
if (bytes == null) {
return null;
}
try {
return new String(bytes, EncodeConstants.ENCODING_UTF_8);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
/**
* RSA加密
*
* @param plainTextData 要加密的内容
* @param publicKey 用于加密的公钥
* @return 加密后的内容
*/
public static byte[] encrypt(byte[] plainTextData, Key publicKey) {
if (ArrayUtils.isEmpty(plainTextData)) {
return plainTextData;
}
try {
Cipher c1 = Cipher.getInstance("RSA");
c1.init(Cipher.ENCRYPT_MODE, publicKey);
return dealEncryptFragment(plainTextData, c1);
} catch (Exception e) {
LoggerFactory.getLogger().error(e.getMessage(), e);
}
return null;
}
private static byte[] dealEncryptFragment(byte[] data, Cipher cipher) throws IllegalBlockSizeException, BadPaddingException {
byte[] result = new byte[]{};
int i;
for (i = 0; i < data.length; i += FRAGMENT_LENGTH) {
byte[] fragment = ArrayUtils.subarray(data, i, i + FRAGMENT_LENGTH);
byte[] update = cipher.doFinal(fragment);
result = ArrayUtils.addAll(result, update);
}
return result;
}
/**
* RSA解密
*
* @param cipherData 密文数据
* @param privateKey 用于解密的私钥
* @return 解密后的内容
*/
public static byte[] decrypt(byte[] cipherData, Key privateKey) {
try {
Cipher c1 = Cipher.getInstance("RSA");
c1.init(Cipher.DECRYPT_MODE, privateKey);
return dealDecryptFragment(cipherData, c1);
} catch (Exception e) {
LoggerFactory.getLogger().error(e.getMessage(), e);
}
return null;
}
private static byte[] dealDecryptFragment(byte[] data, Cipher cipher) throws IllegalBlockSizeException, BadPaddingException {
byte[] result = new byte[]{};
int i;
for (i = 0; i < data.length; i += FRAGMENT_LENGTH_DECRYPT) {
byte[] fragment = ArrayUtils.subarray(data, i, i + FRAGMENT_LENGTH_DECRYPT);
byte[] update = cipher.doFinal(fragment);
result = ArrayUtils.addAll(result, update);
}
return result;
}
public static String sha256(String plainTextData) {
if (StringUtils.isEmpty(plainTextData)) {
return plainTextData;
}
try {
byte[] bytes = sha256(plainTextData.getBytes(EncodeConstants.ENCODING_UTF_8));
return byteArrayToHexString(bytes);
} catch (UnsupportedEncodingException e) {
LoggerFactory.getLogger().error(e.getMessage(), e);
}
return plainTextData;
}
private static byte[] sha256(byte[] plainTextData) {
if (plainTextData == null || ArrayUtils.isEmpty(plainTextData)) {
return plainTextData;
}
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(plainTextData);
return messageDigest.digest();
} catch (Exception e) {
LoggerFactory.getLogger().error(e.getMessage(), e);
}
return plainTextData;
}
/**
* 将加密后的字节数组转换成字符串
*
* @param b 字节数组
* @return 字符串
*/
public static String byteArrayToHexString(byte[] b) {
StringBuilder hs = new StringBuilder();
String tempStr;
for (int n = 0; b != null && n < b.length; n++) {
tempStr = Integer.toHexString(b[n] & 0XFF);
if (tempStr.length() == 1)
hs.append('0');
hs.append(tempStr);
}
return hs.toString().toLowerCase();
}
/**
* 生成一个2048位的RSA秘钥对
*
* @return 秘钥对
* @throws Exception 如果无法生成秘钥对则抛出次异常
*/
public static KeyPair getKeyPair() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
}
/**
* 获取RSA公钥的base64编码字符串
*
* @param keyPair 秘钥对
* @return 公钥编码字符串
*/
public static String getPublicKey(KeyPair keyPair) {
PublicKey publicKey = keyPair.getPublic();
byte[] bytes = publicKey.getEncoded();
return byte2Base64(bytes);
}
/**
* 获取RSA私钥的base64编码字符串
*
* @param keyPair 秘钥对
* @return 私钥编码字符串
*/
public static String getPrivateKey(KeyPair keyPair) {
PrivateKey privateKey = keyPair.getPrivate();
byte[] bytes = privateKey.getEncoded();
return byte2Base64(bytes);
}
public static PublicKey string2PublicKey(String pubStr) {
try {
byte[] keyBytes = base642Byte(pubStr);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(keySpec);
} catch (Exception e) {
LoggerFactory.getLogger().error(e.getMessage(), e);
}
return null;
}
public static PrivateKey string2PrivateKey(String priStr) {
try {
byte[] keyBytes = base642Byte(priStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePrivate(keySpec);
} catch (Exception e) {
LoggerFactory.getLogger().error(e.getMessage(), e);
}
return null;
}
public static String byte2Base64(byte[] bytes) {
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(bytes);
}
public static byte[] base642Byte(String base64Key) throws IOException {
BASE64Decoder decoder = new BASE64Decoder();
return decoder.decodeBuffer(base64Key);
}
public static void main(String... args) {
}
}