aes-gcm-256 php加密 java解密 chatgpt的回答!

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);


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值