AES-128加密算法Java代码
时间: 2024-09-10 12:05:45 浏览: 18
AES(Advanced Encryption Standard)是一种对称加密算法,常用于保护数据的安全传输。以下是使用Java实现AES-128位加密的基本步骤和一个简化的示例:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
public class AESExample {
private static final String ALGORITHM = "AES";
private static final byte[] keyValue = "1234567890123456".getBytes(); // 示例密钥,实际应用应生成更安全的Key
public static void main(String[] args) throws Exception {
Key secretKey = new SecretKeySpec(keyValue, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
// 加密
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal("Hello, world!".getBytes());
System.out.println("Encrypted data: " + new String(encryptedBytes));
// 解密
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
System.out.println("Decrypted data: " + new String(decryptedBytes));
}
}
```
在这个例子中,我们首先创建一个`SecretKeySpec`对象,指定加密算法(AES)和密钥。然后实例化`Cipher`对象,并设置其模式(ENCRYPT_MODE for 加密,DECRYPT_MODE for 解密)。接着使用`doFinal`方法处理明文并得到加密后的密文。