java Aes 用一个字符串 加密另一个字符串 生成一个新的字符串
时间: 2024-11-18 10:12:11 浏览: 8
在Java中,我们可以使用`javax.crypto.Cipher`和`javax.crypto.spec.SecretKeySpec`类配合`AES`(Advanced Encryption Standard)算法来进行字符串加密。这里是一个简单的例子,假设你有一个预共享的密钥作为字符串:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESExample {
private static final String ALGORITHM = "AES";
private static final byte[] keyValue = // 你的密钥字符串转为字节数组,例如 "mysecretkey".getBytes();
public static String encrypt(String plainText) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(keyValue, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(keyValue, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(decryptedBytes, "UTF-8");
}
public static void main(String[] args) throws Exception {
String inputString = "Hello, World!";
String encrypted = encrypt(inputString);
System.out.println("Encrypted: " + encrypted);
String decrypted = decrypt(encrypted);
System.out.println("Decrypted: " + decrypted);
}
}
```
这个示例首先将明文字符串转换为字节,然后使用AES加密,最后将加密后的字节编码成Base64字符串以便于存储和传输。解密时,再从Base64字符串还原并解密回原始文本。
阅读全文