Skip to content

Commit

Permalink
feat: add base64 encoding function
Browse files Browse the repository at this point in the history
  • Loading branch information
ehrdi committed Aug 5, 2024
1 parent 3d8bf43 commit a98b3d7
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
12 changes: 12 additions & 0 deletions src/lib/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
};
24 changes: 23 additions & 1 deletion src/tests/crypto.spec.ts
Original file line number Diff line number Diff line change
@@ -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(() => {
Expand Down Expand Up @@ -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);
});
});
});

0 comments on commit a98b3d7

Please sign in to comment.