crypto.js
6.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/* global window */
Object.defineProperty(exports, "__esModule", { value: true });
exports.BrowserCrypto = void 0;
// This file implements crypto functions we need using in-browser
// SubtleCrypto interface `window.crypto.subtle`.
const base64js = require("base64-js");
// Not all browsers support `TextEncoder`. The following `require` will
// provide a fast UTF8-only replacement for those browsers that don't support
// text encoding natively.
// eslint-disable-next-line node/no-unsupported-features/node-builtins
if (typeof process === 'undefined' && typeof TextEncoder === 'undefined') {
require('fast-text-encoding');
}
const crypto_1 = require("../crypto");
class BrowserCrypto {
constructor() {
if (typeof window === 'undefined' ||
window.crypto === undefined ||
window.crypto.subtle === undefined) {
throw new Error("SubtleCrypto not found. Make sure it's an https:// website.");
}
}
async sha256DigestBase64(str) {
// SubtleCrypto digest() method is async, so we must make
// this method async as well.
// To calculate SHA256 digest using SubtleCrypto, we first
// need to convert an input string to an ArrayBuffer:
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const inputBuffer = new TextEncoder().encode(str);
// Result is ArrayBuffer as well.
const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer);
return base64js.fromByteArray(new Uint8Array(outputBuffer));
}
randomBytesBase64(count) {
const array = new Uint8Array(count);
window.crypto.getRandomValues(array);
return base64js.fromByteArray(array);
}
static padBase64(base64) {
// base64js requires padding, so let's add some '='
while (base64.length % 4 !== 0) {
base64 += '=';
}
return base64;
}
async verify(pubkey, data, signature) {
const algo = {
name: 'RSASSA-PKCS1-v1_5',
hash: { name: 'SHA-256' },
};
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const dataArray = new TextEncoder().encode(data);
const signatureArray = base64js.toByteArray(BrowserCrypto.padBase64(signature));
const cryptoKey = await window.crypto.subtle.importKey('jwk', pubkey, algo, true, ['verify']);
// SubtleCrypto's verify method is async so we must make
// this method async as well.
const result = await window.crypto.subtle.verify(algo, cryptoKey, signatureArray, dataArray);
return result;
}
async sign(privateKey, data) {
const algo = {
name: 'RSASSA-PKCS1-v1_5',
hash: { name: 'SHA-256' },
};
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const dataArray = new TextEncoder().encode(data);
const cryptoKey = await window.crypto.subtle.importKey('jwk', privateKey, algo, true, ['sign']);
// SubtleCrypto's sign method is async so we must make
// this method async as well.
const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray);
return base64js.fromByteArray(new Uint8Array(result));
}
decodeBase64StringUtf8(base64) {
const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base64));
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const result = new TextDecoder().decode(uint8array);
return result;
}
encodeBase64StringUtf8(text) {
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const uint8array = new TextEncoder().encode(text);
const result = base64js.fromByteArray(uint8array);
return result;
}
/**
* Computes the SHA-256 hash of the provided string.
* @param str The plain text string to hash.
* @return A promise that resolves with the SHA-256 hash of the provided
* string in hexadecimal encoding.
*/
async sha256DigestHex(str) {
// SubtleCrypto digest() method is async, so we must make
// this method async as well.
// To calculate SHA256 digest using SubtleCrypto, we first
// need to convert an input string to an ArrayBuffer:
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const inputBuffer = new TextEncoder().encode(str);
// Result is ArrayBuffer as well.
const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer);
return crypto_1.fromArrayBufferToHex(outputBuffer);
}
/**
* Computes the HMAC hash of a message using the provided crypto key and the
* SHA-256 algorithm.
* @param key The secret crypto key in utf-8 or ArrayBuffer format.
* @param msg The plain text message.
* @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer
* format.
*/
async signWithHmacSha256(key, msg) {
// Convert key, if provided in ArrayBuffer format, to string.
const rawKey = typeof key === 'string'
? key
: String.fromCharCode(...new Uint16Array(key));
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const enc = new TextEncoder();
const cryptoKey = await window.crypto.subtle.importKey('raw', enc.encode(rawKey), {
name: 'HMAC',
hash: {
name: 'SHA-256',
},
}, false, ['sign']);
return window.crypto.subtle.sign('HMAC', cryptoKey, enc.encode(msg));
}
}
exports.BrowserCrypto = BrowserCrypto;
//# sourceMappingURL=crypto.js.map