java AES加密算法
时间: 2023-11-04 22:56:59 浏览: 90
Java中的AES加密算法可以使用JCE(Java Cryptography Extension)库来实现。以下是一个简单的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AES {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
private static final String KEY = "mysecretkey12345";
public static String encrypt(String plainText) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
public static void main(String[] args) throws Exception {
String plainText = "Hello World!";
String encryptedText = encrypt(plainText);
String decryptedText = decrypt(encryptedText);
System.out.println("Plain Text: " + plainText);
System.out.println("Encrypted Text: " + encryptedText);
System.out.println("Decrypted Text: " + decryptedText);
}
}
```
在上面的代码中,我们使用AES算法和ECB模式进行加密,并使用PKCS5填充。我们使用一个128位的密钥来加密和解密数据。在这个示例中,我们使用相同的密钥进行加密和解密。在实际应用中,密钥应该妥善保管,并使用更安全的方式来生成和存储密钥。
阅读全文