用java写一个aes算法
时间: 2023-05-17 09:03:10 浏览: 126
Aes算法设计java实现.txt
好的,以下是用Java写的AES算法的示例代码:
```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 key, String plainText) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherText = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(cipherText);
}
public static String decrypt(String key, String cipherText) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(cipherText));
return new String(plainText);
}
}
```
这个示例代码使用了Java内置的加密库,可以对字符串进行AES加密和解密。其中,加密和解密都需要一个密钥,这个密钥可以是任意长度的字符串。在加密时,使用密钥对明文进行加密,并将密文进行Base64编码,以便于传输。在解密时,先将密文进行Base64解码,再使用密钥对密文进行解密,得到明文。
阅读全文