diff --git a/src/lib/crypto.ts b/src/lib/crypto.ts index ac3956a..53473e7 100644 --- a/src/lib/crypto.ts +++ b/src/lib/crypto.ts @@ -39,3 +39,15 @@ export const createHash = async ( return hash; }; + +export const encodeToBase64 = (str: string): string => { + // Convert string to UTF-8 byte array + const utf8Bytes = new TextEncoder().encode(str); + + // Convert byte array to base64 string + let binaryString = ''; + for (let i = 0; i < utf8Bytes.length; i++) { + binaryString += String.fromCharCode(utf8Bytes[i]); + } + return btoa(binaryString); +}; diff --git a/src/tests/crypto.spec.ts b/src/tests/crypto.spec.ts index 1659f78..9494f67 100644 --- a/src/tests/crypto.spec.ts +++ b/src/tests/crypto.spec.ts @@ -1,7 +1,7 @@ import nodeCrypto from 'node:crypto'; import { beforeAll, describe, expect, it } from 'vitest'; import { Request } from '../interfaces/index.js'; -import { createHash } from '../lib/crypto.js'; +import { createHash, encodeToBase64 } from '../lib/crypto.js'; describe('crypto', () => { beforeAll(() => { @@ -34,4 +34,26 @@ describe('crypto', () => { expect(hash).toEqual(expectedResultForAboveValues); }); }); + + describe('encodeToBase64', () => { + it('should encode an ascii string to base64', () => { + const asciiString = 'Hello, World!'; + const expectedResult = 'SGVsbG8sIFdvcmxkIQ=='; + + const base64String = encodeToBase64(asciiString); + + expect(base64String).toBeTruthy(); + expect(base64String).toEqual(expectedResult); + }); + + it('should encode a utf-8 string to base64', () => { + const utf8String = '👋🌍'; + const expectedResult = '8J+Ri/CfjI0='; + + const base64String = encodeToBase64(utf8String); + + expect(base64String).toBeTruthy(); + expect(base64String).toEqual(expectedResult); + }); + }); });