ethers.js/src.ts/utils/base64.ts

57 lines
1.5 KiB
TypeScript
Raw Permalink Normal View History

2022-11-27 21:50:34 -05:00
/**
2022-12-30 11:28:26 -05:00
* [Base64 encoding](link-wiki-base64) using 6-bit words to encode
2022-11-27 21:50:34 -05:00
* arbitrary bytes into a string using 65 printable symbols, the
* upper-case and lower-case alphabet, the digits ``0`` through ``9``,
* ``"+"`` and ``"/"`` with the ``"="`` used for padding.
*
2022-12-02 21:23:13 -05:00
* @_subsection: api/utils:Base64 Encoding [about-base64]
2022-11-27 21:50:34 -05:00
*/
import { getBytes, getBytesCopy } from "./data.js";
2022-09-05 16:14:43 -04:00
import type { BytesLike } from "./data.js";
2022-09-09 03:37:38 -04:00
/**
2022-11-27 21:50:34 -05:00
* Decodes the base-64 encoded %%value%%.
2023-02-12 21:21:11 -05:00
*
* @example:
* // The decoded value is always binary data...
* result = decodeBase64("SGVsbG8gV29ybGQhIQ==")
* //_result:
*
* // ...use toUtf8String to convert it to a string.
* toUtf8String(result)
* //_result:
*
* // Decoding binary data
* decodeBase64("EjQ=")
* //_result:
2022-09-09 03:37:38 -04:00
*/
2022-11-27 21:50:34 -05:00
export function decodeBase64(value: string): Uint8Array {
return getBytesCopy(Buffer.from(value, "base64"));
2022-09-05 16:14:43 -04:00
};
2022-09-09 03:37:38 -04:00
/**
2022-11-27 21:50:34 -05:00
* Encodes %%data%% as a base-64 encoded string.
2023-02-12 21:21:11 -05:00
*
* @example:
* // Encoding binary data as a hexstring
* encodeBase64("0x1234")
* //_result:
*
* // Encoding binary data as a Uint8Array
* encodeBase64(new Uint8Array([ 0x12, 0x34 ]))
* //_result:
*
* // The input MUST be data...
* encodeBase64("Hello World!!")
* //_error:
*
* // ...use toUtf8Bytes for this.
* encodeBase64(toUtf8Bytes("Hello World!!"))
* //_result:
2022-09-09 03:37:38 -04:00
*/
2022-09-05 16:14:43 -04:00
export function encodeBase64(data: BytesLike): string {
return Buffer.from(getBytes(data)).toString("base64");
2022-09-05 16:14:43 -04:00
}