3 changed files with 93 additions and 37 deletions
@ -0,0 +1,55 @@
|
||||
package com.biutag.lan; |
||||
|
||||
import javax.crypto.Cipher; |
||||
import javax.crypto.spec.SecretKeySpec; |
||||
import java.nio.charset.StandardCharsets; |
||||
import java.util.Base64; |
||||
|
||||
public class AESUtil { |
||||
|
||||
// AES加密算法
|
||||
public static String encrypt(String data, String key) { |
||||
try { |
||||
// 创建AES密钥
|
||||
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"); |
||||
|
||||
// 创建密码器
|
||||
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); |
||||
|
||||
// 初始化为加密模式的密码器
|
||||
cipher.init(Cipher.ENCRYPT_MODE, secretKey); |
||||
|
||||
// 加密
|
||||
byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)); |
||||
|
||||
// 使用Base64编码
|
||||
return Base64.getEncoder().encodeToString(encrypted); |
||||
} catch (Exception e) { |
||||
throw new RuntimeException("Error encrypting data", e); |
||||
} |
||||
} |
||||
|
||||
// AES解密算法
|
||||
public static String decrypt(String encryptedData, String key) { |
||||
try { |
||||
// 创建AES密钥
|
||||
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"); |
||||
|
||||
// 创建密码器
|
||||
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); |
||||
|
||||
// 初始化为解密模式的密码器
|
||||
cipher.init(Cipher.DECRYPT_MODE, secretKey); |
||||
|
||||
// 解密
|
||||
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedData)); |
||||
|
||||
// 返回解密后的字符串
|
||||
return new String(decrypted, StandardCharsets.UTF_8); |
||||
} catch (Exception e) { |
||||
throw new RuntimeException("Error decrypting data", e); |
||||
} |
||||
} |
||||
} |
||||
|
||||
|
||||
Loading…
Reference in new issue