package com.macrosky.dnd.util.datacenter;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
//import java.util.Base64;
import com.sun.org .apache.xerces.internal.impl.dv.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* RSA、AES加密解密
* @author hao
*
*/
public class CipherTextUtil {
/**
* 生成公钥和私钥
*
* @throws Exception
*
*/
public static void getKeys() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(1024, new SecureRandom());
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
//Base64.getEncoder().encode(publicKey.getEncoded())
//Base64.getEncoder().encode(privateKey.getEncoded())
String publicKeyStr = new String(Base64.encode(publicKey.getEncoded()));
String privateKeyStr = new String(Base64.encode(privateKey.getEncoded()));
System.out.println("公钥\r\n" + publicKeyStr);
System.out.println("私钥\r\n" + privateKeyStr);
}
/**
* RSA公钥加密明文
*
* @param content 待加密明文
* @param pk 公钥
* @return 密文
*/
public static String publicEnc(String content, String pk) {
try {
KeyFactory keyf = KeyFactory.getInstance("RSA");
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
PublicKey pubkey = null;
InputStream is = new ByteArrayInputStream(pk.getBytes("utf-8"));
byte[] pubbytes = new byte[new Long(pk.length()).intValue()];
is.read(pubbytes);
//Base64.getDecoder().decode(pubbytes)
X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(Base64.decode(new String(pubbytes)));
pubkey = keyf.generatePublic(pubX509);
cipher.init(Cipher.ENCRYPT_MODE, pubkey);
byte[] cipherText = cipher.doFinal(content.getBytes());
// 转换为Base64编码存储,以便于internet传送
return new String(Base64.encode(cipherText));
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* RSA私钥解密密文
*
* @param content 待解密密文
* @param prikeyStr 私钥
* @return 明文
*/
public static String privateDec(String content, String prikeyStr) {
try {
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey privkey = null;
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
InputStream key = new ByteArrayInputStream(prikeyStr.getBytes("utf-8"));
byte[] pribytes = new byte[new Long(prikeyStr.length()).intValue()];
key.read(pribytes);
// 生成私钥
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(new String(pribytes)));
privkey = keyf.generatePrivate(priPKCS8);
cipher.init(Cipher.DECRYPT_MODE, privkey);
byte[] newPlainText = cipher.doFinal(Base64.decode(content));
return (new String(newPlainText));
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* AES 加密
* @param str
* @param key
* @return
*/
public static String AESencode(String str, String key) {
return keyGeneratorES(str, "AES", key, 128, true);
}
/**
* AES 解密
* @param str
* @param key
* @return
*/
public static String AESdecode(String str, String key) {
return keyGeneratorES(str, "AES", key, 128, false);
}
/**
* 使用KeyGenerator双向加密,DES/AES,注意这里转化为字符串的时候是将2进制转为16进制格式的字符串,不是直接转,因为会出错
* @param str 明文
* @param algorithm 加密算法
* @param key 盐值
* @param keysize
* @param isEncode 是否编码转换
* @return
*/
private static String keyGeneratorES(String str,String algorithm,String key,int keysize,boolean isEncode){
try {
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
KeyGenerator kg = KeyGenerator.getInstance(algorithm);
if (keysize == 0) {
byte[] keyBytes = key.getBytes("UTF-8");
secureRandom.setSeed(keyBytes);
kg.init(secureRandom);
}else if (key==null) {
kg.init(keysize);
}else {
byte[] keyBytes = key.getBytes("UTF-8");
secureRandom.setSeed(keyBytes);
kg.init(keysize, secureRandom);
}
SecretKey sk = kg.generateKey();
SecretKeySpec sks = new SecretKeySpec(sk.getEncoded(), algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
if (isEncode) {
cipher.init(Cipher.ENCRYPT_MODE, sks);
byte[] resBytes = str.getBytes("UTF-8");
return parseByte2HexStr(cipher.doFinal(resBytes));
}else {
cipher.init(Cipher.DECRYPT_MODE, sks);
return new String(cipher.doFinal(parseHexStr2Byte(str)),"UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将二进制转换成16进制
* @param buf
* @return
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 将16进制转换为二进制
* @param hexStr
* @return
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length()/2];
for (int i = 0;i< hexStr.length()/2; i++) {
int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
}