What is the code to convert data to base64 in Javascript when it is not a string?

I am in the process of transferring functionality from an Objective-C iPhone application to a JavaScript iPhone application (using Appcelerator Titanium). In my Objective-C code, I have an NSData object that represents a specific token:

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

This token is not just a string, it's actually an NSData object which serves as an object-oriented wrapper for a byte buffer. When I encode this object using base64, I obtain the following result:

//base64 encoded representation of the NSData object
DNn1cbDmbm3KQQ0S9npASn5kubXSSD/ZY6kmexx2CeI=

Now, in my JavaScript implementation, I have a string version of the same token which appears like this:

//string equivalent of the token in my JavaScript implementation
0cd9f571b0e66e6dca410d12f67a404a7e64b9b5d2483fd963a9267b1c7609e2

When I encode this string object using base64 in JavaScript, the output is as follows:

//base64 encoded token (as a string) in JavaScript
MGNkOWY1NzFiMGU2NmU2ZGNhNDEwZDEyZjY3YTQwNGE3ZTY0YjliNWQyNDgzZmQ5NjNhOTI2N2IxYzc2MDllMg==

The challenge arises because the web service I need to send this token to does not accept the base64 encoded string, but rather requires the base64 encoded data! How can I achieve this conversion in JavaScript?

Answer №1

To fix the issue, you need to convert the hexadecimal string before encoding it in base64. Here is how you can do this in JavaScript:

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 instance, when running

btoa('0cd9f571b0e66e6dca410d12f67a404a7e64b9b5d2483fd963a9267b1c7609e2'.b16decode())

(where btoa is a base64 encoding function available in some browsers), the result will be

"DNn1cbDmbm3KQQ0S9npASn5kubXSSD/ZY6kmexx2CeI="

Answer №2

First, it is important to interpret the original hexadecimal string as a series of integers, rather than characters. You can refer to How to convert decimal to hex in JavaScript? for guidance on this process.

Next, you will need to adapt an existing base64 JavaScript algorithm to work with these integers instead of using charCodeAt. Resources like and http://www.codeproject.com/KB/cs/base64encoder.aspx offer valuable insights into achieving this transformation.

While the latter example provided relates to C#, it should be feasible to translate the logic into JavaScript successfully.

If time permits, I may attempt to develop the necessary code at a later stage.

Answer №3

Look up the toDataUrl() method

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing a Python script asynchronously from a Node.js environment

I am currently managing a node.js program that handles approximately 50 different python script instances. My goal is to implement a throttling mechanism where only 4 processes can run in parallel at any given time. Initially, I attempted to create a simp ...

Building a contact form in Angular and sending emails with Nodemailer

Currently, I am in the process of setting up a contact form for my website. Since I am utilizing a MEAN stack, it made sense to incorporate the nodemailer module for sending emails. In order to handle this functionality, I have established an endpoint &ap ...

When using node.js express, the req.body object does not yield any results

My web server setup with express appears to be functioning correctly, however, I am encountering an issue where the req.body returns nothing. Despite not receiving any errors, the console.log(req.body) doesn't show anything in the console output. Stra ...

Engaging in payment processing

Currently facing a significant dilemma. I am utilizing Stripe as my payment gateway, which functions in a two-step process: Collect billing information to generate a token Charge the client using the generated token The issue arises because the token ca ...

What is the best way to control the overflow length and display only a specific amount of content at once?

I am currently designing the homepage for a social media platform. I have around 45 dummy posts and I am looking for a way to limit the overflow in CSS so that only 5 posts are displayed at a time. Once the user reaches the bottom of those 5 posts, another ...

The scrolling function halts as soon as the element that was middle-clicked is deleted from the

I am knee-deep in developing my own React virtualization feature and encountering a minor annoyance. When I middle click on an item in the list and start scrolling, the scrolling stops once that item is removed from the DOM. My initial thought was that the ...

The webpack vue-loader throws an error message stating "unexpected token {" when processing a single-page .vue component

As a C# backend developer, I am venturing into the world of Vue.js. I typically work with Visual Studio 2017 + ASP.NET MVC (using it as an API + one layout) + Vue.js + Webpack. .vue single-page component files are loaded by vue-loader, while .js files a ...

Can TypeScript and JavaScript be integrated into a single React application?

I recently developed an app using JS react, and now I have a TSX file that I want to incorporate into my project. How should I proceed? Can I import the TSX file and interact with it within a JSX file, or do I need to convert my entire app to TSX for eve ...

How can we incorporate SaxonJS higher-order functions into the Node.js runtime, separate from JS/HTML?

We are currently in the process of transitioning an older C# system that relied on custom functions to enhance XSLT processing. Our plan is to convert it to Node.js/saxon-js. After reviewing the documentation, it appears that while higher order functions ...

Catching exceptions with jQuery Ajax

I'm facing a tricky issue with an exception that seems to slip through my fingers: //myScript.js.coffee try $.ajax async: false type: "GET" url: index_url success: -> //Do something error: -> //Do something els ...

How can you retrieve the `categoryIds` key within an object that holds an array of mongodb's `ObjectId(s)` as its value?

In my Node.js code, I have the following: var getQuestionsByUserId = function (config) { var query = { _id: ObjectId(String(config.userId)) }; var projection = { categoryIds: true, _id: false }; var respondWithCategories = function (error, doc ...

Listening for server updates with jQuery

I am currently working on a web application that communicates with a server for database updates. The issue I am facing is that the update process can vary greatly in time, ranging from milliseconds to tens of seconds for larger updates. I would like to im ...

Creating a custom filter: How to establish seamless interaction between a script and a node application

I am currently working on implementing a filter feature for a blog using a node express/ MongoDB/Mongoose setup. My goal is to add the 'active' class when a filter is clicked, and then add that filter to an array (filterArray). I want to compare ...

Issue with Material UI: An invalid value was detected for the select component, even though the value is within the available options

I am facing an issue with a dropdown list component using material UI. The dropdown is populated by an API call and displays a list of departments with their corresponding IDs and names. Upon selecting a record from a table, the department name associated ...

The image fails to load when attempting to retrieve it from a local JSON file

I successfully managed to fetch data dynamically from a local JSON file created in RN. However, when I tried to add images for each profile to be displayed along with the dynamic profile info, the app encountered an error stating that "The component cannot ...

Tips for changing the content of a td element to an input field and removing the displayed value

I am facing an issue with a dynamic table that displays names and input fields. When a name is displayed in a table row, the user has the option to delete that name. I am able to remove the value from a specific table row, but I am struggling to replace th ...

Is it recommended to incorporate "return" in my callback function when coding in JavaScript?

Utilizing asynchronous functions in my JS application, I've encapsulated them within my own functions that take callback inputs. One question that I have is whether or not it's necessary to use the "return" keyword when calling the callback funct ...

Load grid data only when the tab is clicked in ExtJS

Our app features a dynamic grid loaded with multiple tabs, each containing one or more grids. The issue currently is that when the application loads, it automatically calls all the URLs instead of waiting for the user to click on a tab. We want to optimi ...

Customizing AngularJS Scripts to Include Target Blank

I'm feeling a bit lost. I need to include a target="_blank" on my anchor link. The issue is that the anchor tag is linked to a script in angular. I am not familiar with this JavaScript framework. I have tried searching through the documentation for po ...

Guide to updating a database using ajax and javascript in asp.net mvc without the need to refresh the page

Is there a way to update the value of an enumdropdownlist from "active" to "inactive" in my database through an ajax call without having to refresh the page? I am unsure whether to use a javascript method or ajax.beginform for this task. I attempted to us ...