Skip to content

Commit

Permalink
chore: custom crypto provider per singleton constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
ohager committed Jan 11, 2025
1 parent b347f7b commit a0a2b66
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 16 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,4 @@ dist
.idea
.turbo
coverage.json
.DS_Store
4 changes: 1 addition & 3 deletions packages/crypto/src/__tests__/crypto.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,11 @@ class TestCryptoProvider implements CryptoProvider {

describe('Crypto', () => {
test('should use custom crypto provider', () => {
const crypto = Crypto.getInstance();
crypto.setCustomProvider(new TestCryptoProvider());
const crypto = Crypto.getInstance(new TestCryptoProvider());
const testHash = crypto.provider.sha256(new Uint8Array([12, 23, 54, 46]));
expect(testHash).toEqual(new Uint8Array([11, 12, 13, 14, 15]));
});
test('should use custom crypto provider', () => {
Crypto.getInstance().setCustomProvider(new TestCryptoProvider());
const testHash = sha256AsBytes('foo', 'utf8');
expect(testHash).toEqual(new Uint8Array([11, 12, 13, 14, 15]));
});
Expand Down
18 changes: 5 additions & 13 deletions packages/crypto/src/crypto/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,8 @@ import {WebCryptoProvider} from './webCryptoProvider';
export class Crypto {

private static instance: Crypto;
private cryptoProvider: CryptoProvider;

private constructor() {
this.cryptoProvider = Crypto.isNode() ? new NodeJSCryptoProvider() : new WebCryptoProvider();
private constructor(private cryptoProvider: CryptoProvider) {
}

/**
Expand All @@ -32,10 +30,12 @@ export class Crypto {

/**
* Singleton instance accessor
* @param customProvider The implementation of a CryptoProvider for non-Web or NodeJS environments
*/
static getInstance(): Crypto {
static getInstance(customProvider?: CryptoProvider): Crypto {
if (!Crypto.instance) {
Crypto.instance = new Crypto();
const provider = !customProvider ? Crypto.isNode() ? new NodeJSCryptoProvider() : new WebCryptoProvider() : customProvider;
Crypto.instance = new Crypto(provider);
}
return Crypto.instance;
}
Expand All @@ -47,13 +47,5 @@ export class Crypto {
return typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
}

/**
* Allows to set a custom crypto provider.
* This may be useful/necessary when using non-NodeJs or non-Web environments, e.g. React Native
* @param customProvider The implementation of a CryptoProvider
*/
setCustomProvider(customProvider: CryptoProvider): void {
this.cryptoProvider = customProvider;
}
}

0 comments on commit a0a2b66

Please sign in to comment.