该回答引用ChatGPT
有疑问可以回复我
Java 中实现 Laravel 中的加密和解密功能,您可以使用 Java Cryptography Extension (JCE) 提供的 API。下面是一个示例代码:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class LaravelEncryption {
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
private static final String SECRET_KEY_ALGORITHM = "AES";
private static final String KEY = "base64:+90gHlNsoj6J0G9OepRfOkW/9IJHiK+bGS1Lt+wzn+M=";
private static final String IV = "0000000000000000";
public static String encrypt(String plainText) throws Exception {
byte[] keyBytes = Base64.getDecoder().decode(KEY.split(":")[1]);
SecretKeySpec secretKey = new SecretKeySpec(keyBytes, SECRET_KEY_ALGORITHM);
IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String cipherText) throws Exception {
byte[] keyBytes = Base64.getDecoder().decode(KEY.split(":")[1]);
SecretKeySpec secretKey = new SecretKeySpec(keyBytes, SECRET_KEY_ALGORITHM);
IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] cipherBytes = Base64.getDecoder().decode(cipherText);
byte[] decryptedBytes = cipher.doFinal(cipherBytes);
return new String(decryptedBytes);
}
public static void main(String[] args) {
String plainText = "hello, world!";
try {
String cipherText = encrypt(plainText);
System.out.println("Cipher text: " + cipherText);
String decryptedText = decrypt(cipherText);
System.out.println("Decrypted text: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
}