AES加密算法的开源代码
时间: 2023-11-10 14:52:31 浏览: 81
以下是使用Java实现的AES加密算法的开源代码示例:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
public class AES {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
public static byte[] encrypt(String key, String plaintext) throws Exception {
Key aesKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
return cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
}
public static String decrypt(String key, byte[] ciphertext) throws Exception {
Key aesKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, aesKey);
return new String(cipher.doFinal(ciphertext), StandardCharsets.UTF_8);
}
}
```
使用示例:
```java
String key = "mykey";
String plaintext = "Hello, world!";
byte[] ciphertext = AES.encrypt(key, plaintext);
String decryptedText = AES.decrypt(key, ciphertext);
System.out.println(decryptedText); // Output: Hello, world!
```
请注意,此示例使用的是ECB模式和PKCS5Padding填充。对于更高级别的安全性,您可能需要使用其他模式和填充。另外,此示例中的密钥应该更长,并且应该从更安全的源生成。
阅读全文