简体   繁体   中英

How do I base64 encode data (not a string) in Javascript?

I'm porting functionality from an Objective-C iPhone app to a Javascript iPhone app (Appcelerator Titanium). In Objective-C I have an NSData object that represents this token:

//NSData object printed to the console:
<0cd9f571 b0e66e6d ca410d12 f67a404a 7e64b9b5 d2483fd9 63a9267b 1c7609e2>

It's not a string, it's an NSData object -- an object-oriented wrapper for a byte buffer. When I base64 encode the object, I get this result:

//base64 encoded NSData object
DNn1cbDmbm3KQQ0S9npASn5kubXSSD/ZY6kmexx2CeI=

In my javascript implementation, I have a string representation of the same token. It looks like this:

//string version of the token in my javascript implementation
0cd9f571b0e66e6dca410d12f67a404a7e64b9b5d2483fd963a9267b1c7609e2

When I base64 encode the string object in javascript, I get this result:

//base64 encoded token (string) in javascript
MGNkOWY1NzFiMGU2NmU2ZGNhNDEwZDEyZjY3YTQwNGE3ZTY0YjliNWQyNDgzZmQ5NjNhOTI2N2IxYzc2MDllMg==

The problem is, the web service I'm posting to doesn't want the base64 encoded string, it wants the base64 encoded data? How can I do this in javascript?

Convert the hexadecimal string before base64 encoding it should fix the issue. To do this in JS:

if (! Array.prototype.map) {
    Array.prototype.map = function(f) {
        var result = [];
        for (var i=0; i < this.length; ++i) {
            result[i] = f(this[i], i);
        }
        return result;
    }
}
String.prototype.b16decode = function() {
    return this.match(/../g).map(
        function (x) {
            return String.fromCharCode(parseInt(x, 16));
        }
    ).join('');
}

For example, running

btoa('0cd9f571b0e66e6dca410d12f67a404a7e64b9b5d2483fd963a9267b1c7609e2'.b16decode())

(where btoa is a base64 encoding function some browsers supply) results in

"DNn1cbDmbm3KQQ0S9npASn5kubXSSD/ZY6kmexx2CeI="

You need to read the original hex string as list of integers. See How to convert decimal to hex in JavaScript?

Then you need to modify one of the many base64 js algorithms to use the integers instead of charCodeAt . See http://www.webtoolkit.info/javascript-base64.html Also see http://www.codeproject.com/KB/cs/base64encoder.aspx which is a direct integer to base64 algo (most are byte or string to base64).

Even though that last example C# you should be able to convert it to JS.

If I have the time later on I will see if I can write the code.

search for toDataUrl() function

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