Base64 encoding and decoding in client-side Javascript

前端 未结 14 2050
挽巷
挽巷 2020-11-22 04:27

Are there any methods in JavaScript that could be used to encode and decode a string using base64 encoding?

相关标签:
14条回答
  • 2020-11-22 04:52

    Internet Explorer 10+

    // Define the string
    var string = 'Hello World!';
    
    // Encode the String
    var encodedString = btoa(string);
    console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
    
    // Decode the String
    var decodedString = atob(encodedString);
    console.log(decodedString); // Outputs: "Hello World!"
    

    Cross-Browser

    Re-written and modularized UTF-8 and Base64 Javascript Encoding and Decoding Libraries / Modules for AMD, CommonJS, Nodejs and Browsers. Cross-browser compatible.


    with Node.js

    Here is how you encode normal text to base64 in Node.js:

    //Buffer() requires a number, array or string as the first parameter, and an optional encoding type as the second parameter. 
    // Default is utf8, possible encoding types are ascii, utf8, ucs2, base64, binary, and hex
    var b = new Buffer('JavaScript');
    // If we don't use toString(), JavaScript assumes we want to convert the object to utf8.
    // We can make it convert to other formats by passing the encoding type to toString().
    var s = b.toString('base64');
    

    And here is how you decode base64 encoded strings:

    var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
    var s = b.toString();
    

    with Dojo.js

    To encode an array of bytes using dojox.encoding.base64:

    var str = dojox.encoding.base64.encode(myByteArray);
    

    To decode a base64-encoded string:

    var bytes = dojox.encoding.base64.decode(str)
    

    bower install angular-base64

    <script src="bower_components/angular-base64/angular-base64.js"></script>
    
    angular
        .module('myApp', ['base64'])
        .controller('myController', [
    
        '$base64', '$scope', 
        function($base64, $scope) {
        
            $scope.encoded = $base64.encode('a string');
            $scope.decoded = $base64.decode('YSBzdHJpbmc=');
    }]);
    

    But How?

    If you would like to learn more about how base64 is encoded in general, and in JavaScript in-particular, I would recommend this article: Computer science in JavaScript: Base64 encoding

    0 讨论(0)
  • 2020-11-22 04:52

    I'd rather use the bas64 encode/decode methods from CryptoJS, the most popular library for standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns.

    0 讨论(0)
  • 2020-11-22 04:53

    Short and fast Base64 JavaScript Decode Function without Failsafe:

    function decode_base64 (s)
    {
        var e = {}, i, k, v = [], r = '', w = String.fromCharCode;
        var n = [[65, 91], [97, 123], [48, 58], [43, 44], [47, 48]];
    
        for (z in n)
        {
            for (i = n[z][0]; i < n[z][1]; i++)
            {
                v.push(w(i));
            }
        }
        for (i = 0; i < 64; i++)
        {
            e[v[i]] = i;
        }
    
        for (i = 0; i < s.length; i+=72)
        {
            var b = 0, c, x, l = 0, o = s.substring(i, i+72);
            for (x = 0; x < o.length; x++)
            {
                c = e[o.charAt(x)];
                b = (b << 6) + c;
                l += 6;
                while (l >= 8)
                {
                    r += w((b >>> (l -= 8)) % 256);
                }
             }
        }
        return r;
    }
    
    0 讨论(0)
  • 2020-11-22 04:56

    For what it's worth, I got inspired by the other answers and wrote a small utility which calls the platform specific APIs to be used universally from either Node.js or a browser:

    /**
     * Encode a string of text as base64
     *
     * @param data The string of text.
     * @returns The base64 encoded string.
     */
    function encodeBase64(data: string) {
        if (typeof btoa === "function") {
            return btoa(data);
        } else if (typeof Buffer === "function") {
            return Buffer.from(data, "utf-8").toString("base64");
        } else {
            throw new Error("Failed to determine the platform specific encoder");
        }
    }
    
    /**
     * Decode a string of base64 as text
     *
     * @param data The string of base64 encoded text
     * @returns The decoded text.
     */
    function decodeBase64(data: string) {
        if (typeof atob === "function") {
            return atob(data);
        } else if (typeof Buffer === "function") {
            return Buffer.from(data, "base64").toString("utf-8");
        } else {
            throw new Error("Failed to determine the platform specific decoder");
        }
    }

    0 讨论(0)
  • 2020-11-22 04:58

    function b64_to_utf8( str ) {
      return decodeURIComponent(escape(window.atob( str )));
    }

    https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_.22Unicode_Problem.22

    0 讨论(0)
  • 2020-11-22 05:01

    I have tried the Javascript routines at phpjs.org and they have worked well.

    I first tried the routines suggested in the chosen answer by Ranhiru Cooray - http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html

    I found that they did not work in all circumstances. I wrote up a test case where these routines fail and posted them to GitHub at:

    https://github.com/scottcarter/base64_javascript_test_data.git

    I also posted a comment to the blog post at ntt.cc to alert the author (awaiting moderation - the article is old so not sure if comment will get posted).

    0 讨论(0)
提交回复
热议问题