diff --git a/src/algorithms/ECDSA.js b/src/algorithms/ECDSA.js new file mode 100644 index 0000000..fc8175a --- /dev/null +++ b/src/algorithms/ECDSA.js @@ -0,0 +1,129 @@ +'use strict' + +/** + * Dependencies + * @ignore + */ +const base64url = require('base64url') +const crypto = require('isomorphic-webcrypto') +const TextEncoder = require('../text-encoder') + +/** + * ECDSA with SHA-2 Functions and P Curves + */ +class ECDSA { + + /** + * Constructor + * + * @param {string} bitlength + */ + constructor (params) { + this.params = params + } + + /** + * Sign + * + * @description + * Generate a hash-based message authentication code for a + * given input and key. Enforce the key length is equal to + * or greater than the bitlength. + * + * @param {CryptoKey} key + * @param {string} data + * + * @returns {string} + */ + sign (key, data) { + let algorithm = this.params + + // TODO: validate key length + + data = new TextEncoder().encode(data) + + return crypto.subtle + .sign(algorithm, key, data) + .then(signature => base64url(Buffer.from(signature))) + } + + /** + * Verify + * + * @description + * Verify a digital signature for a given input and private key. + * + * @param {CryptoKey} key + * @param {string} signature + * @param {string} data + * + * @returns {Boolean} + */ + verify (key, signature, data) { + let algorithm = this.params + + if (typeof signature === 'string') { + signature = Uint8Array.from(base64url.toBuffer(signature)) + } + + if (typeof data === 'string') { + data = new TextEncoder().encode(data) + } + + return crypto.subtle.verify(algorithm, key, signature, data) + } + + /** + * Assert Sufficient Key Length + * + * @description Assert that the key length is sufficient + * @param {string} key + */ + assertSufficientKeyLength (key) { + if (key.length < this.bitlength) { + throw new Error('The key is too short.') + } + } + + /** + * importKey + * copied from ./RSASSA-PKCS1-v1_5.js, and it works! + * + * @param {JWK} key + * @returns {Promise} + */ + async importKey (key) { + let jwk = Object.assign({}, key) + let algorithm = this.params + let usages = key['key_ops'] || [] + + if (key.use === 'sig') { + usages.push('verify') + } + + if (key.use === 'enc') { + // TODO: handle encryption keys + return Promise.resolve(key) + } + + if (key.key_ops) { + usages = key.key_ops + } + + return crypto.subtle + .importKey('jwk', jwk, algorithm, true, usages) + .then(cryptoKey => { + Object.defineProperty(jwk, 'cryptoKey', { + enumerable: false, + value: cryptoKey + }) + + return jwk + }) + } +} + +/** + * Export + */ +module.exports = ECDSA diff --git a/src/algorithms/index.js b/src/algorithms/index.js index 10d629c..5dff01b 100644 --- a/src/algorithms/index.js +++ b/src/algorithms/index.js @@ -4,6 +4,7 @@ const None = require('./NONE') const HMAC = require('./HMAC') const RSASSA_PKCS1_v1_5 = require('./RSASSA-PKCS1-v1_5') +const ECDSA = require('./ECDSA') const SupportedAlgorithms = require('./SupportedAlgorithms') /** @@ -55,7 +56,14 @@ supportedAlgorithms.define('RS512', 'sign', new RSASSA_PKCS1_v1_5({ name: 'SHA-512' } })) -//supportedAlgorithms.define('ES256', 'sign', {}) + +supportedAlgorithms.define('ES256', 'sign', new ECDSA({ + name: 'ECDSA', + hash: { + name: 'SHA-256' + }, + namedCurve: 'P-256' +})) //supportedAlgorithms.define('ES384', 'sign', {}) //supportedAlgorithms.define('ES512', 'sign', {}) //supportedAlgorithms.define('PS256', 'sign', {}) @@ -110,7 +118,14 @@ supportedAlgorithms.define('RS512', 'verify', new RSASSA_PKCS1_v1_5({ name: 'SHA-512' } })) -//supportedAlgorithms.define('ES256', 'verify', {}) + +supportedAlgorithms.define('ES256', 'verify', new ECDSA({ + name: 'ECDSA', + hash: { + name: 'SHA-256' + }, + namedCurve: 'P-256' +})) //supportedAlgorithms.define('ES384', 'verify', {}) //supportedAlgorithms.define('ES512', 'verify', {}) //supportedAlgorithms.define('PS256', 'verify', {}) @@ -142,6 +157,14 @@ supportedAlgorithms.define('RS512', 'importKey', new RSASSA_PKCS1_v1_5({ } })) +supportedAlgorithms.define('ES256', 'importKey', new ECDSA({ + name: 'ECDSA', + hash: { + name: 'SHA-256' + }, + namedCurve: 'P-256' +})) + /** * Export */ diff --git a/test/algorithms/ECDSASpec.js b/test/algorithms/ECDSASpec.js new file mode 100644 index 0000000..b01d837 --- /dev/null +++ b/test/algorithms/ECDSASpec.js @@ -0,0 +1,139 @@ +'use strict' + +/** + * Test dependencies + */ +const chai = require('chai') + +/** + * Assertions + */ +chai.should() +let expect = chai.expect + +/** + * Code under test + */ +const ECDSA = require('../../src/algorithms/ECDSA') +const {TextEncoder} = require('@sinonjs/text-encoding') +const crypto = require('isomorphic-webcrypto') +const base64url = require('base64url') +const { getPublicKey, getPrivateKey } = require('../keys/ES256') +const { should } = require('chai') + +/** + * Reused test constants + */ +const alg = { name: 'ECDSA', hash: { name: 'SHA-256' }, namedCurve: "P-256" } + +const data = 'signed with Chrome generated webcrypto key' + +/** + * Tests + */ +describe('ECDSA', () => { + + /** + * constructor + */ + describe('constructor', () => { + it('should set params', () => { + let alg = { name: 'ECDSA' } + let ecdsa = new ECDSA(alg) + ecdsa.params.should.equal(alg) + }) + }) + + /** + * sign + */ + describe('sign', () => { + let importedEcdsaPrivateKey, importedEcdsaPublicKey + + before(async () => { + importedEcdsaPrivateKey = await getPrivateKey() + importedEcdsaPublicKey = await getPublicKey() + }) + + it('should return a promise', () => { + let ecdsa = new ECDSA(alg) + return ecdsa.sign(importedEcdsaPrivateKey, data).should.be.instanceof(Promise) + }) + + it('should reject an insufficient key length') + + it('should resolve a base64url encoded value and verification should pass', async () => { + const ecdsa = new ECDSA(alg) + const signature = await ecdsa.sign(importedEcdsaPrivateKey, data) + + // this will fail if signature is anything but base64 string + expect(base64url(base64url.toBuffer(signature))).to.equal(signature) + + // ECDSA is non-deterministic. Therefore we test that the generated signature gets verified with crypto library + const verified = await crypto.subtle.verify( + { + name: 'ECDSA', + hash: { name: 'SHA-256' }, + namedCurve: "P-256" + }, + importedEcdsaPublicKey, + base64url.toBuffer(signature), + new TextEncoder().encode(data) + ) + + verified.should.eql(true) + }) + }) + + /** + * verify + */ + describe('verify', () => { + let importedEcdsaPublicKey, signature + + before(async () => { + /** + * This signature was produced in Chromium + * deails can be found in comments of ../keys/ES256.js + */ + signature = 'AUNkOnr//z999flIoTMebaf5EQC56WVQizK3GXW/u4EOQBvs9CtvfgWi0pQ3bi0k8p357ajtNvN/dJ1Vr8gbYg==' + + importedEcdsaPublicKey = await getPublicKey() + }) + + it('should return a promise', () => { + let ecdsa = new ECDSA(alg) + ecdsa.verify(importedEcdsaPublicKey, signature, data).should.be.instanceof(Promise) + }) + + it('should resolve to true', async () => { + const ecdsa = new ECDSA(alg) + const verified = await ecdsa.verify(importedEcdsaPublicKey, signature, data) + expect(verified).to.equal(true) + }) + }) + + /** + * importKey + */ + describe('importKey', () => { + let exampleJwkPublicKey + + before(() => { + exampleJwkPublicKey = { + crv: 'P-256', + kty: 'EC', + x: '-c0_z0ly3xRDR0XQuvIirfgal59hq7BzF9ObdUXrgmI', + y: '_7QdnDYKrkrkYaCqZko0ebDQ1L1RpHLtzg8YwdT79n8', + alg: 'ES256' + } + }) + + it('should successfully import public jwk key', async () => { + const ecdsa = new ECDSA(alg) + const key = await ecdsa.importKey(exampleJwkPublicKey) + key.cryptoKey.constructor.name.should.equal('CryptoKey') + }) + }) +}) + diff --git a/test/keys/ES256.js b/test/keys/ES256.js new file mode 100644 index 0000000..a95fba2 --- /dev/null +++ b/test/keys/ES256.js @@ -0,0 +1,80 @@ +const crypto = require('isomorphic-webcrypto') + +const alg = { name: 'ECDSA', hash: { name: 'SHA-256' }, namedCurve: "P-256" } + +const EcdsaPublicJwk = { + "crv": "P-256", + "ext": true, + "key_ops": [ + "verify" + ], + "kty": "EC", + "x": "uOn1dXfOejFDxl82ou1BqcWJj817HIs2BJbwkIdf0v4", + "y": "tA_wAZevVIITzb0UdivivtcOWEkiK6I3GxHsA_b8e70" +} + +const EcdsaPrivateJwk = { + "crv": "P-256", + "d": "HDlY69G2D9u_mmu3SbnLQqJW57opS84s2OWkE5uq9io", + "ext": true, + "key_ops": [ + "sign" + ], + "kty": "EC", + "x": "uOn1dXfOejFDxl82ou1BqcWJj817HIs2BJbwkIdf0v4", + "y": "tA_wAZevVIITzb0UdivivtcOWEkiK6I3GxHsA_b8e70" +} + +async function getPublicKey () { + return await crypto.subtle.importKey('jwk', EcdsaPublicJwk, alg, true, ['verify']) +} + +async function getPrivateKey () { + return await crypto.subtle.importKey('jwk', EcdsaPrivateJwk, alg, true, ['sign']) +} + +/** + * Export + */ +module.exports = { + EcdsaPrivateJwk, + EcdsaPublicJwk, + getPublicKey, + getPrivateKey, +} + +/** + * We produced the testing keys and signatures for ECDSASpec.js + * in Chromium Version 103.0.5060.134 (Official Build) Arch Linux (64-bit) + * with the following functions + * with typescript types stripped off: + * (may contain mistakes) + * +// algorithm +const alg: EcKeyGenParams = { name: 'ECDSA', namedCurve: 'P-256', hash: { name: 'SHA-256' }} + +// generate keys +const generateKeyPair = async (alg: EcKeyGenParams): Promise => await crypto.subtle.generateKey(alg, true, ['sign', 'verify']) + +// export keys as jwk +const exportPublicKey = async (keyPair: CryptoKey): Promise => await crypto.subtle.exportKey('jwk', keyPair.publicKey) + +const exportPrivateKey = async (keyPair: CryptoKey): Promise => await crypto.subtle.exportKey('jwk', keyPair.privateKey) + +// import jwk keys +const importPublicKey = async (publicKey: JsonWebKey, alg: EcKeyImportParams): Promise => await crypto.subtle.importKey('jwk', publicKey, alg, true, ['verify']) + +const importPrivateKey = async (privateKey: JsonWebKey, alg: EcKeyImportParams): Promise => await crypto.subtle.importKey('jwk', privateKey, alg, true, ['sign']) + +// sign text data +const sign = async (alg: EcKeyParams, privateKey: CryptoKey, data: string): Promise => { + const rawData = new TextEncoder().encode(data) + const rawSignature = await crypto.subtle.sign(alg, privateKey, rawData) + return rawSignature +} + +// produce string signature +const getStringSignature = (signature: ArrayBuffer): string => btoa(String.fromCharCode(...new Uint8Array(signature))) + +const getUint8ArraySignature = (signature: ArrayBuffer): Uint8Array => new Uint8Array(signature) + */