Search code examples
javascriptjquerycryptographyfrontend3des

How to get a 8byte Output from a 3DES encryption function using CryptoJS?


I need to encrypt a 8byte block using a 16byte key in the 3DES Algo and get a 8byte output, but currently the output is being bigger.

I've tried the following function:

function test3DES(){

    var keyHex = "01010101010101010101010101010101" 
    var block = "041234CFFFFEFDEE";

    var encrypted = CryptoJS.DES.encrypt(CryptoJS.enc.Hex.parse(block), CryptoJS.enc.Hex.parse(keyHex), {
    mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });

    encrypted = CryptoJS.enc.Hex.parse(encrypted.toString());
    alert(encrypted)

}

Key:01010101010101010101010101010101 Block: 041234CFFFFEFDEE

Using other softwares i am able to calculate the required output 241D6DFE12B470D6

But when trying to run the above function the output is 000100000c0000000d000000

Could you please help me understand why it is happening ?


Solution

  • You're quite close. You're serializing the object in encrypted after performing the DES encryption into a string. The CryptoJS serializes this data into a base64 string. For example.

    Lets take the example you provided.

    var keyHex = "01010101010101010101010101010101" 
    var block = "041234CFFFFEFDEE";
    
    var encrypted = CryptoJS.DES.encrypt(CryptoJS.enc.Hex.parse(block), CryptoJS.enc.Hex.parse(keyHex), {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
    
    // encrypted.toString() returns "JB1t/hK0cNZ+QigidzZmwA=="
    // What you are interested in is the cipherText
    
    var d = encrypted.ciphertext;
    // This size of this ciphertext is 16 bytes. Serializing this
    var encryptedHex = d.toString();
    // which returns : "241d6dfe12b470d67e422822773666c0"
    

    Given this you could read the first 8 bytes equivalent for your use case. The modified version of your code would look as follows:

    function test3DES() {
    
        var keyHex = "01010101010101010101010101010101" 
        var block = "041234CFFFFEFDEE";
    
        var encrypted = CryptoJS.DES.encrypt(CryptoJS.enc.Hex.parse(block), CryptoJS.enc.Hex.parse(keyHex), {
             mode: CryptoJS.mode.ECB,
             padding: CryptoJS.pad.Pkcs7
        });
    
        encrypted = encrypted.ciphertext.toString();
        alert(encrypted.substr(0, 8*2)); // <-- read the first 8 bytes i.e. 16 bytes of hex string.
    }
    

    Hope this helps.