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