|
@@ -0,0 +1,39 @@
|
|
|
+package cn.cslg.pas.service.test;
|
|
|
+
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+
|
|
|
+import javax.crypto.Cipher;
|
|
|
+import javax.crypto.KeyGenerator;
|
|
|
+import javax.crypto.SecretKey;
|
|
|
+import javax.crypto.spec.SecretKeySpec;
|
|
|
+import java.security.SecureRandom;
|
|
|
+import java.util.Base64;
|
|
|
+
|
|
|
+@Component
|
|
|
+public class AESUtils {
|
|
|
+
|
|
|
+ private static final String ALGORITHM = "AES";
|
|
|
+ private static final int KEY_SIZE = 128;
|
|
|
+
|
|
|
+ public static String generateKey() throws Exception {
|
|
|
+ KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
|
|
|
+ keyGenerator.init(KEY_SIZE, new SecureRandom());
|
|
|
+ SecretKey secretKey = keyGenerator.generateKey();
|
|
|
+ return Base64.getEncoder().encodeToString(secretKey.getEncoded());
|
|
|
+ }
|
|
|
+
|
|
|
+ public static String encrypt(String data, String key) throws Exception {
|
|
|
+ Cipher cipher = Cipher.getInstance(ALGORITHM);
|
|
|
+ cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(Base64.getDecoder().decode(key), ALGORITHM));
|
|
|
+ byte[] encryptedData = cipher.doFinal(data.getBytes());
|
|
|
+ return Base64.getEncoder().encodeToString(encryptedData);
|
|
|
+ }
|
|
|
+
|
|
|
+ public static String decrypt(String encryptedData, String key) throws Exception {
|
|
|
+ Cipher cipher = Cipher.getInstance(ALGORITHM);
|
|
|
+ cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Base64.getDecoder().decode(key), ALGORITHM));
|
|
|
+ byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
|
|
|
+ return new String(decryptedData);
|
|
|
+ }
|
|
|
+
|
|
|
+}
|