Why did the result of DES Encryption executed in Java different from executed in PHP?

Gabriel Shell :

I ran the Trible DES Encryption in Java, with null IV (I have run cipher.getIV() method and indeed it's IV is null) and the same string ran the Triple DES Encryption in PHP with null IV, but I get a different result. Why is that?

Java Code:

private static final String model = "DESede/ECB/PKCS5Padding";
public static String desEncrypt(String message, String key) throws Exception {
    byte[] keyBytes = null;
    if(key.length() == 16){
        keyBytes = newInstance8Key(ByteUtil.convertHexString(key));
    } else if(key.length() == 32){
        keyBytes = newInstance16Key(ByteUtil.convertHexString(key));
    } else if(key.length() == 48){
        keyBytes = newInstance24Key(ByteUtil.convertHexString(key));
    }

    SecretKey deskey = new SecretKeySpec(keyBytes, "DESede");

    Cipher cipher = Cipher.getInstance(model);
    cipher.init(1, deskey);
    return ByteUtil.toHexString(cipher.doFinal(message.getBytes("UTF-8")));
}

PHP Code:

// composer require phpseclib/phpseclib
use phpseclib\Crypt\TripleDES;

function desEncrypt($str,$key){
    $cipher = new TripleDES();
    $cipher->setKey(hex2bin($key));

    $cryptText = $cipher->encrypt($str);

   return unpack("H*",$cryptText)[1];
}

I want to modify my PHP code to fit the Java Encryption Process,how should I do? where is the proplem?

Java Encrypt Result:

before: 622700300000
key: 0123456789ABCDEFFEDCBA98765432100123456789ABCDEF
after: c9aa8ebfcc12ce13e22a33b05d4c18cf

PHP Encrypt Result:

before: 622700300000
key: 0123456789ABCDEFFEDCBA98765432100123456789ABCDEF
after: a6e7a000d4ce79ac8b3db9f6acf73de3

Fixed PHP Code:

/**
 * Triple DES (ECB) Encryption Function
 * PKCS5Padding
 * 
 * @param string $message String needed to be encode
 * @param string $key Hex encoded key
 * @return string Hex Encoded
 */
function desEncrypt($message,$key){
    $cipher = new TripleDES(TripleDES::MODE_ECB);
    $cipher->setKey(hex2bin($key));

    $cryptText = $cipher->encrypt($message);

   return bin2hex($cryptText);
}
Maarten Bodewes :

You forgot to hex decode the key before using it. You're also using CBC mode instead of ECB mode, but as your IV is all zero's, that amounts to the same thing for the first block of data that is encrypted.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=106596&siteId=1