2

我有一个从服务器获得的 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 获得了不同的价值。任何帮助,将不胜感激。
谢谢。

4

0 回答 0