简体   繁体   English

用Java解密PHP AES-256-CFB

[英]Decrypt PHP AES-256-CFB in Java

I created a Helper function for encrypt data with OpenSSL in PHP . 我创建了一个Helper函数,用于在PHP中使用OpenSSL加密数据。

private const METHOD = 'AES-256-CFB';
private const KEY = 'g5(Mt2-2x=wsS8^K';

public static function encrypt($data) {
    $crypted = openssl_encrypt($data, self::METHOD, self::KEY, 1, substr(hash('sha256', self::KEY_1), 0, 16));
    return base64_encode($crypted);
}

For decrypt the AES-CFB-256 data in Java, i've made a Helper class too. 为了用Java解密AES-CFB-256数据,我也做了一个Helper类。

private String decrypt(String sdata) throws Exception {
    String sKey = "g5(Mt2-2x=wsS8^K";

    byte[] key = sKey.getBytes();
    byte[] iv = Arrays.copyOfRange(hash("SHA-256", key).getBytes(), 0, 16);
    byte[] data = Base64.getDecoder().decode(sdata.getBytes());

    Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
    SecretKey aesSecret = new SecretKeySpec(key, "AES");
    IvParameterSpec ivps = new IvParameterSpec(iv);

    cipher.init(Cipher.DECRYPT_MODE, aesSecret, ivps);
    byte[] result = cipher.doFinal(data);

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < result.length; i++) {
        sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
    }

    System.out.println(new String(result, StandardCharsets.UTF_8) + " : " + sb.toString());
    return sb.toString();
}

private String hash(String type, byte[] data) throws Exception {
    MessageDigest digest = MessageDigest.getInstance(type);
    data = digest.digest(data);

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < data.length; i++) {
        sb.append(Integer.toString((data[i] & 0xff) + 0x100, 16).substring(1));
    }

    return sb.toString();
}

I noticed that the hash function in JAVA works and gives me the same result as the hash function in PHP. 我注意到JAVA中的哈希函数可以工作,并且给我与PHP中的哈希函数相同的结果。 The problem is that the result of the cipher is totally different and I don't see were is the mistake. 问题是密码的结果完全不同,我看不出是错误。

Thanks for your help 谢谢你的帮助

After few test, Java appear to use AES-128 instead of AES-256 . 经过几次测试,Java似乎使用AES-128而不是AES-256
If I modify this part of the PHP code. 如果我修改这部分PHP代码。

private const METHOD = 'AES-256-CFB';

To this 对此

private const METHOD = 'AES-128-CFB';

Java and PHP return the same result now. Java和PHP现在返回相同的结果。
I hope that it will help 我希望这会有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM