I have a simple question: how to encode a byte [ ]
to base64
format?
I have the following code:
var hash = CryptoJS.SHA1("payLoad");
document.writeln(hash);
hash = hash.toString();
var bytes = [];
for (var i = 0; i < hash.length; ++i)
{
bytes.push(hash.charCodeAt(i));
}
Now I would like to encode bytes[ ]
to base64
format. Is there a library to do that?
I will appreciate your help!
btoa
and atob
work with strings, which they treat as arrays of bytes, so to use these two functions, you should first convert your array of integers (provided they fall in the range 0-255) into a string.
something that worked here for me was these two simple functions:
b64encode = function(x) {
return btoa(x.map(function(v){return String.fromCharCode(v)}).join(''))
};
b64decode = function(x) {
return atob(x).split('').map(function(v) {return v.codePointAt(0)});
};
I'm sure you can write them in better style.
in your case though your data was already in the correct format, before you converted it to a 32 bit integer array. the fact that you call the array bytes
is only misleading you I think. after that, btoa
converted the bloated array, instead of the array of bytes you had in your hash
.
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.