AES-128 java
时间: 2023-10-29 10:57:01 浏览: 145
以下是使用 AES-128 加密和解密数据的 Java 代码示例:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AES {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/ECB/PKCS5PADDING";
public static String encrypt(String data, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encrypted = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
public static String decrypt(String encryptedData, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(decrypted);
}
public static void main(String[] args) throws Exception {
String key = "MySecretKey12345";
String data = "Hello, world!";
String encryptedData = encrypt(data, key);
String decryptedData = decrypt(encryptedData, key);
System.out.println("Original Data: " + data);
System.out.println("Encrypted Data: " + encryptedData);
System.out.println("Decrypted Data: " + decryptedData);
}
}
```
在此示例中,我们使用了密钥 `MySecretKey12345` 来加密和解密数据。请注意,ECB 模式不是最安全的模式,因为它没有使用初始化向量(IV),但是这个示例足以演示 AES 加密和解密的基本原理。
阅读全文