php代码
encrypt($key, $textToEncrypt){ $cipher = 'aes-256-gcm'; $iv_len = 12; $tag_length = 16; $version_length = 3; $version = "v01"; $iv = openssl_random_pseudo_bytes($iv_len); $tag = ""; // will be filled by openssl_encrypt $ciphertext = openssl_encrypt($textToEncrypt, $cipher, $key, OPENSSL_RAW_DATA, $iv, $tag, "", $tag_length); $encrypted = base64_encode($version.$iv.$ciphertext.$tag); return $encrypted; } echo 'AES GCM in PHP/Java' . PHP_EOL; // ### security warning: never use hardcoded keys in source ### $key = '12345678901234567890123456789012'; $plaintext = 'The quick brown fox jumps over the lazy dog'; $ciphertext = encrypt($key, $plaintext); echo 'ciphertext: ' . $ciphertext . PHP_EOL;
看看chatgpt的回答
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class Decryptor {
public static String decrypt(String key, String encrypted) throws Exception {
// Get the version, iv, ciphertext and tag from the base64-encoded encrypted string
byte[] decoded = Base64.getDecoder().decode(encrypted);
String version = new String(decoded, 0, 3, StandardCharsets.US_ASCII);
byte[] iv = new byte[12];
System.arraycopy(decoded, 3, iv, 0, iv.length);
byte[] ciphertext = new byte[decoded.length - 3 - iv.length - 16];
System.arraycopy(decoded, 3 + iv.length, ciphertext, 0, ciphertext.length);
byte[] tag = new byte[16];
System.arraycopy(decoded, decoded.length - 16, tag, 0, tag.length);
// Decrypt the ciphertext using the provided key, iv and tag
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKey secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.US_ASCII), "AES");
GCMParameterSpec spec = new GCMParameterSpec(128, iv);
cipher.init(Cipher.DECRYPT_MODE, secretKey, spec);
cipher.updateAAD(version.getBytes(StandardCharsets.US_ASCII));
byte[] plaintext = cipher.doFinal(ciphertext);
// Convert the decrypted plaintext back to a string
return new String(plaintext, StandardCharsets.UTF_8);
}
}
String key = "12345678901234567890123456789012";
String encrypted = "v01sU6OaU6hCQiXNsqA6ELyOjk7hUfLlT6x2TbTUNYnnMwsZYftBThJLn9Q=";
String plaintext = Decryptor.decrypt(key, encrypted);
System.out.println("plaintext: " + plaintext);