在PHP中解密Java 3DES ECB NoPadding加密值

时间:2012-04-20 08:07:35

标签: java php encryption mcrypt 3des

我有一个3des加密的十六进制字符串,我从服务器获得。当我用Java ECB / NoPadding解密它时,我得到了预期的值,但是当我尝试用PHP解密它时,我得到了不同的值。这是PHP代码:

<?php

$key = "428982f4658cfeb679bae2bf85ebcde9";
$input = "9CB39217A434F6339EF27C503B561342";
$encrypted_data = bin2hex(
    mcrypt_ecb(MCRYPT_3DES, pack("H*", $key), pack("H*", $input), MCRYPT_DECRYPT)
);

?>

以及以main开头的部分java代码:

String input = "F414E86894D996F8658F9327C8EC786404192012174729";
String key = "05aa58f38a0883d1439750a2495d36ad";

byte2hex(doCryto("F414E86894D996F8658F9327C8EC7864",  "05aa58f38a0883d1439750a2495d36ad", Cipher.DECRYPT_MODE));

public static byte[] doCryto(String data, String key, int CipherMode) throws Exception {
    byte result[];
    try {
        byte data1[] = hex2byte(data);
        Key key1 = formDESKey(key);
        transformation = key1.getAlgorithm() + "/ECB/NoPadding";

        Cipher c1 = Cipher.getInstance(transformation);
        c1.init(CipherMode, key1);
        result = c1.doFinal(data1);
    } catch (Exception e) {
        throw new Exception(e);
    }
    return result;
}

public static Key formDESKey(String key) throws Exception {
    short len = (short) ((key.length() / 2) * 8);
    return formDESKey(len, hex2byte(key));
}

  public static Key formDESKey(short keyLength, byte clearKeyBytes[]) throws Exception {
    Key key = null;
    switch (keyLength) {
        case 64: // '@'
            key = new SecretKeySpec(clearKeyBytes, "DES");
            break;

        case 128:
            clearKeyBytes = concat(clearKeyBytes, 0, 128/8, clearKeyBytes, 0, getBytesLength((short) 64));
        // fall through

        case 192:
            key = new SecretKeySpec(clearKeyBytes, "DESede");
            break;
    }
    if (key == null) {
        throw new Exception("Unsupported DES key length: " + keyLength + " bits");
    } else {
        return key;
    }
}

private static byte[] concat(byte array1[], int beginIndex1, int length1, byte array2[], int beginIndex2, int length2) {
    byte concatArray[] = new byte[length1 + length2];
    System.arraycopy(array1, beginIndex1, concatArray, 0, length1);
    System.arraycopy(array2, beginIndex2, concatArray, length1, length2);
    return concatArray;
}

Java结果:31303031464646464646464646464646
PHP结果为:411C689D687F2F118EA05BF234F4E582

我不知道为什么PHP会获得不同的价值。任何帮助将不胜感激 感谢。

0 个答案:

没有答案