引入jar包
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.56</version>
</dependency>
@Test
@SneakyThrows
public void test01(){
try {
Security.addProvider(new BouncyCastleProvider());
String encryptedText = "myNa9ijJROB0GFQ8XtOeZDVz3SG3T85ZbklJj1Wfjteo6Y9LI/MxGa+NnJ5QnlIkszkaSVzoQHVzGtVLT8Q9LQ=="; // 加密的字符串
String key = "7faca8f987d3fe8279307deb98a6ceXX"; // 256位的密钥
// 解密
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
// 将解密后的字节转换为字符串
String decryptedText = new String(decryptedBytes);
System.out.println("解密后的字符串: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
@SneakyThrows
public void test02(){
Security.addProvider(new BouncyCastleProvider());
String keyString = "7faca8f987d3fe8279307deb98a6ceXX";
String textToEncrypt = "{\"phone_md5\":\"64b534b1893bdb387d2712fe5ce8fcf3\",\"age\":30}";
SecretKeySpec secretKey = new SecretKeySpec(keyString.getBytes(StandardCharsets.UTF_8), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encrypted = cipher.doFinal(textToEncrypt.getBytes());
String s = Base64.getEncoder().encodeToString(encrypted);
System.out.println("加密结果:"+s);
}