如何在Javascript中使用DES算法加密字符串?

时间:2018-03-12 12:10:34

标签: javascript encryption des

我有以下shell脚本,它使用openssl加密字符串:

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
}

我试图在javascript中使用相同的功能(在postman中使用它)。目前我有以下代码:

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

我完全坚持使用“des”进行加密。有人可以帮助我将最后一个字符串转换为javascript吗?

1 个答案:

答案 0 :(得分:0)

好的,所以我用我的代码玩了一点点,现在我有了工作:

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();

因此,此代码与使用openssl

的shell脚本产生相同的结果