-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathoauthServicesDecrypt.js
85 lines (71 loc) · 1.71 KB
/
oauthServicesDecrypt.js
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
//@ts-check
const { subtle } = globalThis.crypto;
/**
*
* @param {string} s
* @returns {string}
*/
export function b64ToUTF8(s) {
return decodeURIComponent(escape(atob(s)))
}
/**
*
* @param {string} base64String
* @returns {Uint8Array}
*/
export function base64ToUint8Array(base64String){
const str = b64ToUTF8(base64String)
return Uint8Array.from(str, char => char.charCodeAt(0))
}
/**
*
* @param {Uint8Array} typedArray
* @returns {string}
*/
export function typedArrayToString(typedArray){
const string = typedArray.reduce((data, byte) => {
return data + String.fromCharCode(byte)
}, '')
return string;
}
/**
*
* @param {string} k
* @returns {Promise<CryptoKey>}
*/
export function makeCryptoKey(k){
return subtle.importKey('raw', base64ToUint8Array(k), "AES-CBC", true, ["encrypt", "decrypt"])
}
/**
*
* @param {string} string
* @returns { Promise<{k: CryptoKey, iv: Uint8Array}> }
*/
export async function keyAndIvFromString(string){
const [k, iv] = string.split('-')
const key = await makeCryptoKey(k)
const initializationVector = base64ToUint8Array(iv)
return {
k: key,
iv: initializationVector
}
}
/**
*
* @param {string} base64encryptedContent
* @param {string} keyWithIV
* @returns {Promise<string>}
*/
export async function decryptOauthServicesContent(base64encryptedContent, keyWithIV){
const {k, iv} = await keyAndIvFromString(keyWithIV)
const ciphertext = base64ToUint8Array(base64encryptedContent);
const plaintext = await subtle.decrypt(
{
name: "AES-CBC",
iv
},
k,
ciphertext
);
return typedArrayToString(new Uint8Array(plaintext))
}