blob: cc582e2ae927575a111e0f6d7b6ea4b3c6df2fdb [file] [log] [blame]
Meki Cherkaoui88d59cd2012-05-14 07:34:58 -07001var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2var b64pad="=";
3
4function hex2b64(h) {
5 var i;
6 var c;
7 var ret = "";
8 for(i = 0; i+3 <= h.length; i+=3) {
9 c = parseInt(h.substring(i,i+3),16);
10 ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
11 }
12 if(i+1 == h.length) {
13 c = parseInt(h.substring(i,i+1),16);
14 ret += b64map.charAt(c << 2);
15 }
16 else if(i+2 == h.length) {
17 c = parseInt(h.substring(i,i+2),16);
18 ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4);
19 }
20 while((ret.length & 3) > 0) ret += b64pad;
21 return ret;
22}
23
24// convert a base64 string to hex
25function b64tohex(s) {
26 var ret = ""
27 var i;
28 var k = 0; // b64 state, 0-3
29 var slop;
30 for(i = 0; i < s.length; ++i) {
31 if(s.charAt(i) == b64pad) break;
Jeff Thompson48ff28a2013-02-18 22:53:29 -080032 var v = b64map.indexOf(s.charAt(i));
Meki Cherkaoui88d59cd2012-05-14 07:34:58 -070033 if(v < 0) continue;
34 if(k == 0) {
35 ret += int2char(v >> 2);
36 slop = v & 3;
37 k = 1;
38 }
39 else if(k == 1) {
40 ret += int2char((slop << 2) | (v >> 4));
41 slop = v & 0xf;
42 k = 2;
43 }
44 else if(k == 2) {
45 ret += int2char(slop);
46 ret += int2char(v >> 2);
47 slop = v & 3;
48 k = 3;
49 }
50 else {
51 ret += int2char((slop << 2) | (v >> 4));
52 ret += int2char(v & 0xf);
53 k = 0;
54 }
55 }
56 if(k == 1)
57 ret += int2char(slop << 2);
58 return ret;
59}
60
61// convert a base64 string to a byte/number array
62function b64toBA(s) {
63 //piggyback on b64tohex for now, optimize later
64 var h = b64tohex(s);
65 var i;
66 var a = new Array();
67 for(i = 0; 2*i < h.length; ++i) {
68 a[i] = parseInt(h.substring(2*i,2*i+2),16);
69 }
70 return a;
71}