一个APP的接口使用了AES/GCM/NoPadding加密,但使用PHP做对称解密时,遇到了返回数据为false的情况,导致无法解密,但好在最终解决了这个问题。

import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;


public class Main {
    public static void main(String[] args) {
		String str = "https://www.kaixing.wang/";
		String key = "14e1b600b1fd579f47433b88e8d85291";
		String iv = "000000000000";
		String ens = en(key, iv, str);
        System.out.println("加密结果:"+ens);

        String des = de(key, iv, ens);
        System.out.println("加密内容:"+des);
    }

    public static String en(String str, String str2, String str3) {
        try {
            byte[] bytes = str.getBytes("UTF-8");
            byte[] bytes2 = str2.getBytes("UTF-8");
            SecretKeySpec secretKeySpec = new SecretKeySpec(bytes, "AES");
            GCMParameterSpec gCMParameterSpec = new GCMParameterSpec(128, bytes2);
            Cipher instance = Cipher.getInstance("AES/GCM/NoPadding");
            instance.init(1, secretKeySpec, gCMParameterSpec);
            byte[] doFinal = instance.doFinal(str3.getBytes("UTF-8"));
            if (doFinal != null) {
                return Base64.getEncoder().encodeToString(doFinal);
            }
        } catch (Exception e7) {
            e7.printStackTrace();
        }
        return "";
    }


    public static String de(String str, String str2, String str3) {
        try {
            byte[] bytes = str.getBytes("UTF-8");
            byte[] bytes2 = str2.getBytes("UTF-8");
            SecretKeySpec secretKeySpec = new SecretKeySpec(bytes, "AES");
            GCMParameterSpec gCMParameterSpec = new GCMParameterSpec(128, bytes2);
            Cipher instance = Cipher.getInstance("AES/GCM/NoPadding");
            instance.init(2, secretKeySpec, gCMParameterSpec);
            byte[] doFinal = instance.doFinal(Base64.getDecoder().decode(str3));
            if (doFinal != null) {
                return new String(doFinal, "UTF-8");
            }
        } catch (Exception e7) {
            e7.printStackTrace();
        }
        return "";
    }

}

对称的PHP解密函数如下:

<?php
function decrypt($ciphertext, $key, $iv,$cipher = 'aes-256-gcm') {
	$ciphertext = base64_decode($ciphertext);
	$tag_length = 16;
	$tag = substr($ciphertext, -$tag_length);
	$ciphertext = substr($ciphertext, 0, -$tag_length);
    $text = openssl_decrypt($ciphertext, $cipher, $key, OPENSSL_RAW_DATA, $iv,$tag);
    return $text;
}

最后推荐一个网站:https://codeshare.frida.re/