QUIC - cleanup changes to sync chromium tree with internal source.
[chromium-blink-merge.git] / chrome / browser / resources / cryptotoken / b64.js
blobd3c1e805102f2423dc6c91b78375131ffd4eafdd
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // WebSafeBase64Escape and Unescape.
6 function B64_encode(bytes, opt_length) {
7 if (!opt_length) opt_length = bytes.length;
8 var b64out =
9 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
10 var result = '';
11 var shift = 0;
12 var accu = 0;
13 var inputIndex = 0;
14 while (opt_length--) {
15 accu <<= 8;
16 accu |= bytes[inputIndex++];
17 shift += 8;
18 while (shift >= 6) {
19 var i = (accu >> (shift - 6)) & 63;
20 result += b64out.charAt(i);
21 shift -= 6;
24 if (shift) {
25 accu <<= 8;
26 shift += 8;
27 var i = (accu >> (shift - 6)) & 63;
28 result += b64out.charAt(i);
30 return result;
33 // Normal base64 encode; not websafe, including padding.
34 function base64_encode(bytes, opt_length) {
35 if (!opt_length) opt_length = bytes.length;
36 var b64out =
37 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
38 var result = '';
39 var shift = 0;
40 var accu = 0;
41 var inputIndex = 0;
42 while (opt_length--) {
43 accu <<= 8;
44 accu |= bytes[inputIndex++];
45 shift += 8;
46 while (shift >= 6) {
47 var i = (accu >> (shift - 6)) & 63;
48 result += b64out.charAt(i);
49 shift -= 6;
52 if (shift) {
53 accu <<= 8;
54 shift += 8;
55 var i = (accu >> (shift - 6)) & 63;
56 result += b64out.charAt(i);
58 while (result.length % 4) result += '=';
59 return result;
62 var B64_inmap =
64 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 63, 0, 0,
65 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 0, 0, 0, 0, 0, 0,
66 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
67 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 0, 0, 0, 64,
68 0, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
69 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 0, 0, 0, 0, 0
72 function B64_decode(string) {
73 var bytes = [];
74 var accu = 0;
75 var shift = 0;
76 for (var i = 0; i < string.length; ++i) {
77 var c = string.charCodeAt(i);
78 if (c < 32 || c > 127 || !B64_inmap[c - 32]) return [];
79 accu <<= 6;
80 accu |= (B64_inmap[c - 32] - 1);
81 shift += 6;
82 if (shift >= 8) {
83 bytes.push((accu >> (shift - 8)) & 255);
84 shift -= 8;
87 return bytes;