AES加密 Java代码
时间: 2023-05-17 14:03:24 浏览: 92
以下是一个简单的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 KEY = "mysecretkey12345";
public static String encrypt(String value) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] encryptedValue = cipher.doFinal(value.getBytes());
return Base64.getEncoder().encodeToString(encryptedValue);
}
public static String decrypt(String value) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] decodedValue = Base64.getDecoder().decode(value);
byte[] decryptedValue = cipher.doFinal(decodedValue);
return new String(decryptedValue);
}
public static void main(String[] args) throws Exception {
String originalValue = "Hello World!";
String encryptedValue = encrypt(originalValue);
String decryptedValue = decrypt(encryptedValue);
System.out.println("Original Value: " + originalValue);
System.out.println("Encrypted Value: " + encryptedValue);
System.out.println("Decrypted Value: " + decryptedValue);
}
}
```
这个代码使用AES算法对字符串进行加密和解密。请注意,这个示例中使用的密钥是硬编码在代码中的,实际应用中应该使用更安全的方式来存储密钥。