简体   繁体   中英

Getting MD5 hash in JavaScript and converting it to base 64

I'd like to use a set of REST API through JavaScript and I'm reading the documentation explaining how to implement authentication. The following instructions are illustrated in pseudocode but I have some issue on understanding how to implement it in JavaScript (my JS level is quite basic). This is the unclear part:

= FromBytesToBase64String(MD5Hash("{\n    \"data\": {\n        \"type\": \"company\",\n        \"id\": \"879f2dfc-57ea-4dbb-96c7-c546f8812f1e\",\n        \"external_1_value\": \"Updated value\"\n    }\n}"))

Basically I should calculate MD5 hash of the string in question and then I should encode it in base 64 string If I understood well.

The documentation shows the flow broken in sub-steps:

= FromBytesToBase64String(b'eC\\xcda\\xa3\\xa7\\xaf\\xa53\\x93\\xb4.\\xa2\\xb1\\xe3]')

And then the final result:

"ZUPNYaOnr6Uzk7QuorHjXQ=="

I tried to do the same by using crypto.js library and I get a MD5 hash string but then how can I get this value "ZUPNYaOnr6Uzk7QuorHjXQ==" ? Any idea on how I could do it?

Thanks so much for helping!

使用btoa()函数获取base64编码的字符串。

使用WindowBase64.btoa()

var encodedData = window.btoa(md5Hash);

That final result is the base64 encoded string. The function FromBytesToBase64String is what produces it, but this is not a standard function in JavaScript.

Instead, try using one of the built-in functions documented here . Specifically:

window.btoa(MD5Hash("Your input string"));

window.btoa(MD5Hash("Your input string")); does not work because btoa takes the md5 string and converts that character by character, hence you need to feed it an byte array.I ended up combining ArrayBuffer to base64 encoded string with https://github.com/pvorb/node-md5/issues/25

into :

function md5ToBase64(md5String,boolTrimLast){
    var strRet = arrayBufferToBase64(hexByteStringToByteArray(md5String));
    return boolTrimLast?strRet.slice(0,22):strRet;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM