Base64 Encode CryptoJS

base64 encoding using CryptoJS

HTML

<script src="//crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js"></script>
<script src="//crypto-js.googlecode.com/svn/tags/3.1.2/build/components/enc-base64-min.js"></script>
<script>
		var helloworld = "Hello World";
    document.write("String: " + helloworld);
    document.write("<br>");
    var helloword_sha1 = CryptoJS.SHA1(helloworld);
    document.write("SHA1: " + helloword_sha1);
    document.write("<br>");
    var helloword_base64 = helloword_sha1.toString(CryptoJS.enc.Base64);
    document.write("1) Base64: " + helloword_base64);
    document.write("<br>");
    document.write("2) Base64: " + base64_encode(helloword_sha1.toString()));
    document.write("<br>");
</script>

JavaScript

function base64_encode (s) {
    // the result/encoded string, the padding string, and the pad count
    var r = ""; 
    var p = ""; 
    var c = s.length % 3;
    
    // add a right zero pad to make this string a multiple of 3 characters
    if (c > 0) { 
        for (; c < 3; c++) { 
            p += '='; 
            s += "\0"; 
        }
    }
    
    // increment over the length of the string, three characters at a time
    for (c = 0; c < s.length; c += 3) {
        // we add newlines after every 76 output characters, according to the MIME specs
        if (c > 0 && (c / 3 * 4) % 76 == 0) { 
        r += "\r\n"; 
        }
        
        // these three 8-bit (ASCII) characters become one 24-bit number
        var n = (s.charCodeAt(c) << 16) + (s.charCodeAt(c+1) << 8) + s.charCodeAt(c+2);
        
        // this 24-bit number gets separated into four 6-bit numbers
        n = [(n >>> 18) & 63, (n >>> 12) & 63, (n >>> 6) & 63, n & 63];
        
        // those four 6-bit numbers are used as indices into the base64 character list
        var base64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        r += base64chars[n[0]] + base64chars[n[1]] + base64chars[n[2]] + base64chars[n[3]];
    }
    // add the actual padding string, after removing the zero pad
    return r.substring(0, r.length - p.length) + p;
}