1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| import org.slf4j.Logger; import org.slf4j.LoggerFactory;
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.NoSuchAlgorithmException; import java.security.Provider; import java.security.SecureRandom; import java.util.Base64; import java.util.Optional; import java.util.UUID;
public class SecretUtil { private static final Logger log = LoggerFactory.getLogger(SecretUtil.class); private static final String AES = "AES";
private SecretUtil() { }
public static String generateAesKey() { return generateAesKey(null); }
public static String generateAesKey(String word) { try { KeyGenerator gen = KeyGenerator.getInstance(AES); gen.init(128, new SecureRandom((Optional.ofNullable(word).orElse("") + UUID.randomUUID()).getBytes())); SecretKey secretKey = gen.generateKey(); return Base64.getEncoder().encodeToString(secretKey.getEncoded()); } catch (NoSuchAlgorithmException e) { log.error("生成 AES key 失败:{}", e.getMessage(), e); } return null; }
public static String aesEncrypt(String content, String key) { return encrypt(content, Base64.getDecoder().decode(key), AES, null); }
public static String aesDecrypt(String content, String key) { return decrypt(content, Base64.getDecoder().decode(key), AES, null); }
public static String encrypt(String content, byte[] key, String algorithm, Provider provider) { try { Cipher cipher = provider == null ? Cipher.getInstance(algorithm) : Cipher.getInstance(algorithm, provider); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, algorithm)); byte[] encryptStr = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(encryptStr); } catch (Exception e) { log.error("{} 数据加密失败:{}", algorithm, e.getMessage(), e); return null; } }
public static String decrypt(String content, byte[] key, String algorithm, Provider provider) { try { byte[] encryptByte = Base64.getDecoder().decode(content); Cipher cipher = provider == null ? Cipher.getInstance(algorithm) : Cipher.getInstance(algorithm, provider); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, algorithm)); byte[] decryptBytes = cipher.doFinal(encryptByte); return new String(decryptBytes); } catch (Exception e) { log.error("{} 数据解密失败:{}", algorithm, e.getMessage(), e); return null; } } }
|