React native Base64 encoding string

Viewed 67311

I am trying to use the base-64 library from

https://github.com/mathiasbynens/base64

When I run a test to validate the code I am not getting the right result. IS there any other library I can use?

Here is the code that I ran and the result I am getting

import utf8 from 'utf8'
import base64 from 'base-64'

var text = 'foo © bar  baz';
var bytes = utf8.encode(text);
var encoded = base64.encode(bytes);
console.log(encoded);
// → 'Zm9vIMKpIGJhciDwnYyGIGJheg=='

Here is the result I am getting

W29iamVjdCBBcnJheUJ1ZmZlcl0=

Can some one please help

thanks in advance

10 Answers

I think dont need to use any third party package for it. Just below one is working in React-Native

const Buffer = require("buffer").Buffer;
let encodedAuth = new Buffer("your text").toString("base64");

React Native has a binaryToBase64 util that accepts ArrayBuffer for base64 conversions:

var utf8 = require('utf8');
var binaryToBase64 = require('binaryToBase64');

var text = 'foo © bar  baz';
var bytes = utf8.encode(text);
var encoded = binaryToBase64(bytes);
console.log(encoded);
// Zm9vIMKpIGJhciDwnYyGIGJheg==

You might need to install the utf8 package, since it was removed from React Native on version 0.54:

npm install --save utf8

Neither the accepted answer nor the Buffer methods worked for me. Here's what worked as of January 2019:

yarn add react-native-base64

then

import base64 from 'react-native-base64'
base64.encode('Some string to encode to base64');

Tested and working in React Native v0.66.1

import { Buffer } from 'buffer'
    
export function toBase64(input) {
  return Buffer.from(input, 'utf-8').toString('base64')
}

export function fromBase64(encoded) {
  return Buffer.from(encoded, 'base64').toString('utf8')
}

You don't need any extra library. Just use:

let encodedCredentials = new Buffer(username + ":" + password).toString("base64");

I got an error when I tried to use Buffer that it was deprecated. I did this:

  const TOKEN = btoa(clientId + ':' + secret);

I'm using base-64 and utf8

(which are more broadly used than the rn library above - and support utf8 characters)

to base64 encode/decode on our react-native app. I don't see why that has to be react-native specific, it's just javascript, and it works.

npm install base-64 utf8;

and then here's what my code looks like:

    import base64 from 'base-64';
    import utf8 from 'utf8';
    const SALT = 'anyString';
    const PREPENDING_STR = '__enc__';

    function encodeCredential(input) {
        if (input // if the input exists
            && typeof input === 'string' // and it's a string
        ) {
            const newInput = `${input}${SALT}`; // add salt to the input
            const utf8Bytes = utf8.encode(newInput); // utf8 encode it
            const encoded = base64.encode(utf8Bytes); // base64 encode it
            return `${PREPENDING_STR}${encoded}`; // add a prepending string
        }
        return input;
    }

    function decodeCredential(input) {
        if (input // if the input exists
            && typeof input === 'string' // and it's a string
            && input.startsWith(PREPENDING_STR) === true // and it's encoded yet
        ) {
            const newInput = input.replace(PREPENDING_STR, ''); // remove the prepending string
            const utf8Bytes = base64.decode(newInput); // base64 decode it
            const output = utf8.decode(utf8Bytes); // utf8 decode it
            return output.replace(SALT, '');
        }
        return input;
    }
encodeBase64 = (input) => {  
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';  
let str = input;
let output = '';

for (let block = 0, charCode, i = 0, map = chars;
str.charAt(i | 0) || (map = '=', i % 1);
output += map.charAt(63 & block >> 8 - i % 1 * 8)) {

  charCode = str.charCodeAt(i += 3/4);

  if (charCode > 0xFF) {
    console.log("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
  }

  block = block << 8 | charCode;
}

return output;    

}

You can use rn-fetch-blob to do the conversion in native code :

import { fs } from 'rn-fetch-blob';

export const blobToBase64 = async (data, encoding = 'base64') => fs.readFile(data, encoding);
Related