Skip to content

Commit

Permalink
feat(jwk): adds support for importing key from JSON Web Key
Browse files Browse the repository at this point in the history
  • Loading branch information
willgm committed May 29, 2020
1 parent 55f21a8 commit befcf93
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/web-crypto-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export type ImportAlgorithm =
/**
* Import Key Web Crypto Algorithms
*/
export type OriginalKeyFormat = 'raw' | 'pkcs8' | 'spki';
export type OriginalKeyFormat = 'raw' | 'pkcs8' | 'spki' | 'jwk';

/**
* Derive Key Algorithms at at Web Crypto API
Expand Down Expand Up @@ -96,15 +96,16 @@ export const PBKDF2_ITERATIONS_DEFAULT: number = 50000;
* @returns A promise with the base Crypto Key.
*/
export function generateBaseCryptoKey(
rawKey: string | TypedArray,
rawKey: string | TypedArray | JsonWebKey,
algorithm: ImportAlgorithm = 'PBKDF2',
keyUsages: KeyUsage[] = ['deriveKey'],
format: OriginalKeyFormat = 'raw',
): Promise<CryptoKey> {
const isJwkKey = !isTypedArray(rawKey) && typeof rawKey === 'object';
return Promise.resolve(
crypto.subtle.importKey(
format,
encode(rawKey),
isJwkKey ? 'jwk' : format,
typeof rawKey === 'string' ? encode(rawKey) : rawKey,
algorithm,
false, // the original value will not be extractable
keyUsages,
Expand Down
21 changes: 21 additions & 0 deletions test/web-crypto-tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,27 @@ describe('Web Crypto Tools', () => {
);
expect(subject.algorithm).toEqual({ name: 'AES-GCM', length: 128 } as any);
});

it('should accept JSON Web Key', async () => {
const jwkEcKey = {
crv: 'P-384',
d: 'wouCtU7Nw4E8_7n5C1-xBjB4xqSb_liZhYMsy8MGgxUny6Q8NCoH9xSiviwLFfK_',
ext: true,
key_ops: ['sign'],
kty: 'EC',
x: 'SzrRXmyI8VWFJg1dPUNbFcc9jZvjZEfH7ulKI1UkXAltd7RGWrcfFxqyGPcwu6AQ',
y: 'hHUag3OvDzEr0uUQND4PXHQTXP5IDGdYhJhL-WLKjnGjQAw0rNGy5V29-aV-yseW',
};
const subject = await generateBaseCryptoKey(
jwkEcKey,
{
name: 'ECDSA',
namedCurve: 'P-384',
},
['sign'],
);
expect(subject.algorithm).toEqual({ name: 'ECDSA', namedCurve: 'P-384' } as any);
});
});

describe('Key Derivation', () => {
Expand Down

0 comments on commit befcf93

Please sign in to comment.