Skip to content

Commit

Permalink
add some sanity check tests for generateRandomString and increase url…
Browse files Browse the repository at this point in the history
… safe dictionary
  • Loading branch information
dillonstreator committed Dec 22, 2024
1 parent b76c80d commit f955b1b
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
27 changes: 26 additions & 1 deletion packages/core/src/encryption.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { encrypt, decrypt } from './encryption';
import { encrypt, decrypt, generateRandomString, generateRandomBytes } from './encryption';

describe('encryption', () => {
const testData = 'Hello, World!';
Expand All @@ -18,3 +18,28 @@ describe('encryption', () => {
await expect(decrypt(encrypted, 'wrong-password')).rejects.toThrow();
});
});

describe('generateRandomString', () => {
it("shouldn't generate the same string twice", async () => {
const randomString1 = await generateRandomString(15);
const randomString2 = await generateRandomString(15);
expect(randomString1).not.toBe(randomString2);
});

it('should generate a random string of the specified length', async () => {
const lengths = await generateRandomBytes(50);
for (const length of Array.from(new Set(lengths))) {
const randomString = await generateRandomString(length);
expect(randomString.length).toBe(length);
}
});

it('should generate all possible characters over time', async () => {
const dictionary =
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+-=[]{}|;:,.<>?';
const sample = await generateRandomString(10_000, dictionary);
for (const char of dictionary) {
expect(sample).toContain(char);
}
});
});
6 changes: 4 additions & 2 deletions packages/core/src/encryption.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,14 @@ export async function generateRandomHexString(length: number): Promise<string> {
.join('');
}

const DEFAULT_DICTIONARY = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
// https://stackoverflow.com/questions/695438/what-are-the-safe-characters-for-making-urls
export const URL_SAFE_DICTIONARY = `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_~`;

// The following implementation guarantees uniformly distributed cryptographically random
// string generation for any dictionary input length as described by https://arxiv.org/pdf/1304.1916
export async function generateRandomString(
length: number,
dictionary: string = DEFAULT_DICTIONARY,
dictionary: string = URL_SAFE_DICTIONARY,
): Promise<string> {
const dictionaryLength = dictionary.length;
const maxValid = Math.floor(256 / dictionaryLength) * dictionaryLength - 1;
Expand Down

0 comments on commit f955b1b

Please sign in to comment.