Java AES 加解密工具类
程序员文章站
2024-03-14 14:46:46
...
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
* @author potoyang
* Description: AES 加解密工具类
*/
@Slf4j
class AESUtil {
private static final String DEFAULT_CIPHER_ALGORITHM = "AES";
@Setter
private String content;
private String secret;
AESUtil(String content) {
this.content = content;
this.secret = "324iu23094u598ndsofhsiufhaf_+0wq-42q421jiosadiusadiasd";
}
/**
* AES 加密
*/
String encrypt() {
try {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
Key key = getKey();
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
return byte2hex(result);
} catch (Exception e) {
log.error("AES 加密出错: [{}]", e.getMessage());
}
return null;
}
/**
* AES 解密
*/
String decrypt() {
if (content.length() < 1) {
return null;
}
try {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
Key key = getKey();
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] original = cipher.doFinal(hex2byte(content));
return new String(original, StandardCharsets.UTF_8);
} catch (Exception e) {
log.error("AES 解密出错: [{}]", e.getMessage());
}
return null;
}
private Key getKey() {
SecretKey key = null;
try {
KeyGenerator generator = KeyGenerator.getInstance("AES");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(secret.getBytes());
generator.init(128, random);
key = generator.generateKey();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return key;
}
private byte[] hex2byte(String strhex) {
if (strhex == null) {
return null;
}
int len = strhex.length();
if (len % 2 == 1) {
return null;
}
byte[] b = new byte[len / 2];
for (int i = 0; i != len / 2; i++) {
b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2), 16);
}
return b;
}
private static String byte2hex(byte[] b) {
StringBuilder hs = new StringBuilder();
String stmp;
for (byte value : b) {
stmp = (Integer.toHexString(value & 0XFF));
if (stmp.length() == 1) {
hs.append("0").append(stmp);
} else {
hs.append(stmp);
}
}
return hs.toString().toUpperCase();
}
}
上一篇: Java AES加解密工具类
下一篇: 非对称加密算法之Java RSA算法应用