java实现AES不调库
时间: 2023-08-16 08:06:57 浏览: 100
Java提供了javax.crypto包,可以用来实现AES加密算法。以下是一个简单的AES加密和解密示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESUtil {
public static String encrypt(String key, String plainText) throws Exception {
byte[] raw = key.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
public static String decrypt(String key, String encryptedText) throws Exception {
byte[] raw = key.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted = Base64.getDecoder().decode(encryptedText);
byte[] original = cipher.doFinal(encrypted);
return new String(original);
}
public static void main(String[] args) throws Exception {
String key = "mysecretaeskey"; // AES密钥,长度为16或32字节
String plainText = "Hello, world!"; // 待加密的明文
String encryptedText = encrypt(key, plainText);
System.out.println("Encrypted Text: " + encryptedText);
String decryptedText = decrypt(key, encryptedText);
System.out.println("Decrypted Text: " + decryptedText);
}
}
```
以上代码使用AES算法和Base64编码实现了对明文的加密和解密。需要注意的是,AES密钥的长度必须为16或32字节,否则会抛出异常。
阅读全文