Search code examples
javascriptencryptioncryptographycryptojsdes

CryptoJS DES (ECB) Encryption - Base64 encoded - not producing the correct result


We have a 3rd party supplier that has pointed us to https://www.tools4noobs.com/online_tools/encrypt/ to generate authentication tokens for their API.

This works fine but we're now at the stage where we need to generate these tokens programmatically. It needs to be DES format, ECB Mode, encoded in Base64.

We've tried the CryptoJS javascript library, but the results don't match the output of https://www.tools4noobs.com/online_tools/encrypt/

var encrypted = CryptoJS.DES.encrypt(text, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7

        });

        var finalEncrypted = CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
        console.log(finalEncrypted); 

Where am I going wrong?


Solution

  • Tools4noobs uses the PHP-method mcyrpt_encrypt, which works with Zero-Byte-Padding. The posted code uses PKCS7-Padding. To use Zero-Byte-Padding, the padding in the code must be changed to CryptoJS.pad.ZeroPadding.

    But if Pkcs7-Padding should be used, then Tools4noobs is not a good choice because the padding cannot be set. In this case another option is TxtWizard.

    Another source of error is the format of the key. Whether this is also a problem here cannot be said, however, since the key generation is not shown in the posted code. It is important that the key is passed as a WordArray and not as a string. If it is passed as a string, then it is interpreted as a passphrase from which the actual key is generated, see The Cipher Input.

    The following code

    var key = CryptoJS.enc.Latin1.parse("12345678"); // key as WordArray
    var text = "The quick brown fox jumps over the lazy dog";
    
    var encrypted = CryptoJS.DES.encrypt(text, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.ZeroPadding // Zero-Byte-Padding
    });
    
    var finalEncrypted = CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
    console.log(finalEncrypted); 
    

    has the output

    XokzhoQlYFGG7ZfTNqdvr0QGMsFF24oSZ5v+vsPDNlPA+GbJ2peAY/7pNhpOerOV 
    

    in accordance with the Tools4noobs output.