Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/microsoft-authentication/src/cryptoUtils.ts
3314 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
import { base64Encode } from './node/buffer';
6
7
export function randomUUID() {
8
return crypto.randomUUID();
9
}
10
11
function dec2hex(dec: number): string {
12
return ('0' + dec.toString(16)).slice(-2);
13
}
14
15
export function generateCodeVerifier(): string {
16
const array = new Uint32Array(56 / 2);
17
crypto.getRandomValues(array);
18
return Array.from(array, dec2hex).join('');
19
}
20
21
function sha256(plain: string | undefined) {
22
const encoder = new TextEncoder();
23
const data = encoder.encode(plain);
24
return crypto.subtle.digest('SHA-256', data);
25
}
26
27
function base64urlencode(a: ArrayBuffer) {
28
let str = '';
29
const bytes = new Uint8Array(a);
30
const len = bytes.byteLength;
31
for (let i = 0; i < len; i++) {
32
str += String.fromCharCode(bytes[i]);
33
}
34
return base64Encode(str)
35
.replace(/\+/g, '-')
36
.replace(/\//g, '_')
37
.replace(/=+$/, '');
38
}
39
40
export async function generateCodeChallenge(v: string) {
41
const hashed = await sha256(v);
42
const base64encoded = base64urlencode(hashed);
43
return base64encoded;
44
}
45
46