Search code examples
javascriptencryptiondes

How can I encrypt string with DES algorithm in Javascript?


I have the following shell script which uses openssl to encrypt string:

encrypt() {
STRING_TO_BE_ENCRYPTED=$1
DATE_STRING=$2

MD5=$(/bin/echo -n ${DATE_STRING} | openssl md5)
MD5=${MD5#*=\ }

key=${MD5:0:8}
iv=${MD5:24:8}

key=$(/bin/echo -n "${key}" |od -A n -t x1|sed s/\ //g)
iv=$(/bin/echo -n "${iv}" |od -A n -t x1|sed s/\ //g)

/bin/echo -n "${STRING_TO_BE_ENCRYPTED}" | openssl des -e -nosalt -K ${key} -iv ${iv} -a
}

I am trying to make the same function in javascript(to use it in postman). At the moment I have the following code:

var DATE_STRING = "Tue, 6 Mar 2018 11:47:23 EET";
var STRING_TO_BE_ENCRYPTED = "somestring";

//MD5=$(/bin/echo -n ${DATE_STRING} | openssl md5)
//MD5=${MD5#*=\ }
var MD5 = CryptoJS.MD5(DATE_STRING).toString();

//key=${MD5:0:8}
var key=MD5.substring(0, 8);
//iv=${MD5:24:8}
var iv=MD5.substring(MD5.length - 8);

//key=$(/bin/echo -n "${key}" |od -A n -t x1|sed s/\ //g)
var keyHex = toHex(key);
//iv=$(/bin/echo -n "${iv}" |od -A n -t x1|sed s/\ //g)
var ivHex = toHex(iv);
And the only issue that I have is the last string from my shell script:

// /bin/echo -n "${STRING_TO_BE_ENCRYPTED}" | openssl des -e -nosalt -K ${key} -iv ${iv} -a

I completely stuck with encrypting using "des". Could some please help me with converting the last string to javascript?


Solution

  • Ok, so I played little bit more with my code and now I have the working one:

    var DATE_STRING = "Tue, 6 Mar 2018 11:47:23 EET";
    var str="somestring";
    var MD5 = CryptoJS.MD5(DATE_STRING).toString();
    
    var key=MD5.substring(0, 8);
    var iv=MD5.substring(MD5.length - 8);    
    
    var keyHex = CryptoJS.enc.Utf8.parse(key);
    var ivHex = CryptoJS.enc.Hex.parse(CryptoJS.enc.Utf8.parse(iv).toString(CryptoJS.enc.Hex));
    
    var encrypted = CryptoJS.DES.encrypt(str, keyHex, { iv: ivHex, mode: CryptoJS.mode.CBC });
    var result = encrypted.toString();
    

    So this code produces the same result as my shell script with openssl