wangzhibo
2026-05-09 53418655c061ac26f66058253f39200aced1ab1d
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
/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
 
import { Constants } from "@azure/msal-common/node";
 
export class EncodingUtils {
    /**
     * 'utf8': Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.
     * 'base64': Base64 encoding.
     *
     * @param str text
     */
    static base64Encode(str: string, encoding?: BufferEncoding): string {
        return Buffer.from(str, encoding).toString(
            Constants.EncodingTypes.BASE64
        );
    }
 
    /**
     * encode a URL
     * @param str
     */
    static base64EncodeUrl(str: string, encoding?: BufferEncoding): string {
        return EncodingUtils.base64Encode(str, encoding)
            .replace(/=/g, "")
            .replace(/\+/g, "-")
            .replace(/\//g, "_");
    }
 
    /**
     * 'utf8': Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.
     * 'base64': Base64 encoding.
     *
     * @param base64Str Base64 encoded text
     */
    static base64Decode(base64Str: string): string {
        return Buffer.from(base64Str, Constants.EncodingTypes.BASE64).toString(
            "utf8"
        );
    }
 
    /**
     * @param base64Str Base64 encoded Url
     */
    static base64DecodeUrl(base64Str: string): string {
        let str = base64Str.replace(/-/g, "+").replace(/_/g, "/");
        while (str.length % 4) {
            str += "=";
        }
        return EncodingUtils.base64Decode(str);
    }
}