这是一个非常古老的问题,但我的回答可能会对某人有所帮助。
- 在 encrypt 方法中,不要忘记将您的字符串编码为 Base64
- 在解密方法中,不要忘记将您的字符串解码为 Base64
下面是工作代码
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class EncryptionDecryptionUtil {
public static String encrypt(final String secret, final String data) {
byte[] decodedKey = Base64.getDecoder().decode(secret);
try {
Cipher cipher = Cipher.getInstance("AES");
// rebuild key using SecretKeySpec
SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
cipher.init(Cipher.ENCRYPT_MODE, originalKey);
byte[] cipherText = cipher.doFinal(data.getBytes("UTF-8"));
return Base64.getEncoder().encodeToString(cipherText);
} catch (Exception e) {
throw new RuntimeException(
"Error occured while encrypting data", e);
}
}
public static String decrypt(final String secret,
final String encryptedString) {
byte[] decodedKey = Base64.getDecoder().decode(secret);
try {
Cipher cipher = Cipher.getInstance("AES");
// rebuild key using SecretKeySpec
SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
cipher.init(Cipher.DECRYPT_MODE, originalKey);
byte[] cipherText = cipher.doFinal(Base64.getDecoder().decode(encryptedString));
return new String(cipherText);
} catch (Exception e) {
throw new RuntimeException(
"Error occured while decrypting data", e);
}
}
public static void main(String[] args) {
String data = "This is not easy as you think";
String key = "---------------------------------";
String encrypted = encrypt(key, data);
System.out.println(encrypted);
System.out.println(decrypt(key, encrypted));
}
}
对于生成密钥,您可以使用下面的类
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class SecretKeyGenerator {
public static void main(String[] args) throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = new SecureRandom();
int keyBitSize = 256;
keyGenerator.init(keyBitSize, secureRandom);
SecretKey secretKey = keyGenerator.generateKey();
System.out.println(Base64.getEncoder().encodeToString(secretKey.getEncoded()));
}
}