依赖
1 2 3 4 5
| <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.13</version> </dependency>
|
实现
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 112 113 114 115 116
| package cn.idea360.idc;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.Key; import java.security.SecureRandom; import java.util.UUID;
public class AESUtils {
private static final String KEY_ALGORITHM = "AES";
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
public static String encrypt(String content, String slatKey, String vectorKey) throws Exception { Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); SecretKey secretKey = new SecretKeySpec(slatKey.getBytes(), KEY_ALGORITHM); IvParameterSpec iv = new IvParameterSpec(vectorKey.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv); byte[] encrypted = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8)); return new String(Base64.encodeBase64(encrypted)); }
public static String decrypt(String base64Content, String slatKey, String vectorKey) throws Exception { Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); SecretKey secretKey = new SecretKeySpec(slatKey.getBytes(), KEY_ALGORITHM); IvParameterSpec iv = new IvParameterSpec(vectorKey.getBytes()); cipher.init(Cipher.DECRYPT_MODE, secretKey, iv); byte[] content = Base64.decodeBase64(base64Content.getBytes()); byte[] encrypted = cipher.doFinal(content); return new String(encrypted, StandardCharsets.UTF_8); }
private static Key getSlatKey(String slatKey) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(slatKey.getBytes()); kgen.init(128, random); Key key = kgen.generateKey(); return key; }
public static String generateSalt() { String pass = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16); return pass; }
public static void main(String[] args) throws Exception{
String slatKey = generateSalt(); String vectorKey = generateSalt();
String content = "当我遇上你";
System.out.println("加密前:" + content); String encrypt = encrypt(content, slatKey, vectorKey);
System.out.println("加密后:" + encrypt);
String decrypt = decrypt(encrypt, slatKey, vectorKey); System.out.println("解密后:" + decrypt); }
}
|
最后
本文到此结束,感谢阅读。如果您觉得不错,请关注公众号【当我遇上你】,您的支持是我写作的最大动力。