友情鏈接 :RSA 非對稱加密解密算法封裝
一、AESUtil
import lombok.extern.slf4j.Slf4j;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Base64;
/**
* @author Andon
* 2020/5/27
* <p>
* AES對稱密碼算法
*/
@Slf4j
public class AESUtil {
public static final String KEY = "KEY";
public static final ThreadLocal<SimpleDateFormat> FORMAT_DAY = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
/**
* 加密
*/
public static byte[] encrypt(String content) {
byte[] encryptResult = null; //密文
try {
// 創建AES的Key生成器
KeyGenerator aes = KeyGenerator.getInstance("AES");
// 由自定義的key+時間作爲隨機數初始化256位的密鑰生成器
aes.init(256, new SecureRandom((KEY + FORMAT_DAY.get().format(System.currentTimeMillis())).getBytes(StandardCharsets.UTF_8)));
// 生成祕鑰
SecretKey secretKey = aes.generateKey();
// 轉換爲AES專用祕鑰
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
// 創建密碼器
Cipher cipher = Cipher.getInstance("AES");
// 初始化加密模式的密碼器
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
// 加密
encryptResult = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
log.error("encrypt failure!! error={}", e.getMessage());
e.printStackTrace();
}
return encryptResult;
}
/**
* 解密
*/
public static byte[] decrypt(byte[] content) {
byte[] decryptResult = null; //明文
try {
// 創建AES的Key生成器
KeyGenerator aes = KeyGenerator.getInstance("AES");
// 由自定義的key+時間作爲隨機數初始化256位的祕鑰生成器
aes.init(256, new SecureRandom((KEY + FORMAT_DAY.get().format(System.currentTimeMillis())).getBytes(StandardCharsets.UTF_8)));
// 生成祕鑰
SecretKey secretKey = aes.generateKey();
// 轉換爲AES專用祕鑰
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
// 創建密碼器
Cipher cipher = Cipher.getInstance("AES");
// 初始化加密模式的密碼器
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
// 解密
decryptResult = cipher.doFinal(content);
} catch (Exception e) {
log.error("decrypt failure!! error={}", e.getMessage());
e.printStackTrace();
}
return decryptResult;
}
/**
* 字節數組轉換成16進制
*/
public static String parseByteToHexStr(byte[] bytes) {
StringBuilder stringBuffer = new StringBuilder();
for (byte aByte : bytes) {
String hexString = Integer.toHexString(aByte & 0xFF);
if (hexString.length() == 1) {
hexString = '0' + hexString;
}
stringBuffer.append(hexString.toUpperCase());
}
return stringBuffer.toString();
}
/**
* 16進制轉換成字節數組
*/
public static byte[] parseHexStrToByte(String hexStr) {
if (hexStr.length() < 1) {
return null;
}
byte[] bytes = 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);
bytes[i] = (byte) (high * 16 + low);
}
return bytes;
}
/**
* Base64處理字節數組轉換爲字符串
*/
public static String base64EncodeToString(byte[] bytes) {
try {
return Base64.getEncoder().encodeToString(bytes);
} catch (Exception e) {
log.error("base64EncodeToString failure!! error={}", e.getMessage());
return null;
}
}
/**
* Base64處理字符串轉換爲字節數組
*/
public static byte[] base64DecodeToByte(String String) {
try {
return Base64.getDecoder().decode(String);
} catch (Exception e) {
log.error("base64DecodeToByte failure!! error={}", e.getMessage());
return null;
}
}
}
二、測試
@Slf4j
public class AESUtilTest {
@Test
public void test() {
String content = "test"; //明文內容
log.info("明文:{}", content);
System.out.println("AES加密==========");
// AES加密
byte[] encrypt = AESUtil.encrypt(content);
log.info("密文:{}", encrypt);
String parseByteToHexStr = AESUtil.parseByteToHexStr(encrypt);
log.info("密文--字節數組轉換成16進制:{}", parseByteToHexStr);
String base64EncodeToString = AESUtil.base64EncodeToString(encrypt);
log.info("密文--Base64處理字節數組轉換爲字符串:{}", base64EncodeToString);
System.out.println("AES解密==========");
// AES解密
byte[] parseHexStrToByte = AESUtil.parseHexStrToByte(parseByteToHexStr);
log.info("密文--16進制轉換成字節數組:{}", parseHexStrToByte);
byte[] base64DecodeToByte = AESUtil.base64DecodeToByte(base64EncodeToString);
log.info("密文--Base64處理字符串轉換爲字節數組:{}", base64DecodeToByte);
byte[] decryptParseHexStrToByte = AESUtil.decrypt(parseHexStrToByte);
log.info("解密後的明文--16進制轉換成字節數組:{}", decryptParseHexStrToByte);
byte[] decryptBase64DecodeToByte = AESUtil.decrypt(base64DecodeToByte);
log.info("解密後的明文--Base64處理字符串轉換爲字節數組:{}", decryptBase64DecodeToByte);
String decryptParseHexStrToByteString = new String(decryptParseHexStrToByte, StandardCharsets.UTF_8);
log.info("明文--字節數組轉換成16進制:{}", decryptParseHexStrToByteString);
String decryptBase64DecodeToByteString = new String(decryptBase64DecodeToByte, StandardCharsets.UTF_8);
log.info("明文--Base64處理字節數組轉換爲字符串:{}", decryptBase64DecodeToByteString);
}
}
三、測試結果
友情鏈接 :RSA 非對稱加密解密算法封裝