有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用Java和PHP的AES加密

我最近在Java中使用了AES算法来加密文本。 现在我需要用PHP重建算法,但我不知道如何重建,因为互联网上的PHP算法返回不同的结果。也许你能帮我

这是要加密的Java代码:

private static final String KEY = "57238004e784498bbc2f8bf984565090";

public static String encrypt(final String plaintext) throws GeneralSecurityException {
    SecretKeySpec sks = new SecretKeySpec(hexStringToByteArray(KEY), "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters());
    byte[] encrypted = cipher.doFinal(plaintext.getBytes());
    return byteArrayToHexString(encrypted);
}

public static byte[] hexStringToByteArray(String s) {
    byte[] b = new byte[s.length() / 2];
    for (int i = 0; i < b.length; i++) {
        int index = i * 2;
        int v = Integer.parseInt(s.substring(index, index + 2), 16);
        b[i] = (byte) v;
    }
    return b;
}

public static String byteArrayToHexString(byte[] b) {
    StringBuilder sb = new StringBuilder(b.length * 2);
    for (int i = 0; i < b.length; i++) {
        int v = b[i] & 0xff;
        if (v < 16) {
            sb.append('0');
        }
        sb.append(Integer.toHexString(v));
    }
    return sb.toString().toUpperCase();
}

你们能帮我建立一个PHP脚本,返回相同的结果吗

例如: 明文“STACKOVERFLOW”被加密为“FA652ECCD39A11A93D2458AA2A0793C”

提前谢谢


共 (1) 个答案

  1. # 1 楼答案

    这应该做到:

    function encrypt($plaintext, $key) {
        $plaintext = pkcs5_pad($plaintext, 16);
        return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, hex2bin($key), $plaintext, MCRYPT_MODE_ECB));
    }
    
    function decrypt($encrypted, $key) {
        $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, hex2bin($key), hex2bin($encrypted), MCRYPT_MODE_ECB);
        $padSize = ord(substr($decrypted, -1));
        return substr($decrypted, 0, $padSize*-1);
    }
    
    function pkcs5_pad ($text, $blocksize)
    {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }
    

    您发现的其他PHP算法返回不同结果的原因可能是填充。Java中AES的默认值是PKCS5,但PHP不支持这一点(因此使用了PKCS5_pad函数)

    正如SLacks所说,你真的不应该使用ECB。如果需要,可以更改Java代码或重新加密现有数据。只要你继续使用ECB,你的数据就有风险

    Credit:Padding函数取自here