├── .eslintignore ├── CODEOWNERS ├── .npmrc ├── .gitignore ├── .eslintrc ├── .npmignore ├── .editorconfig ├── src ├── param-bytes-for-alg.js ├── ecdsa-sig-formatter.d.ts └── ecdsa-sig-formatter.js ├── fuzz └── happy.js ├── .travis.yml ├── benchmarks ├── jose-to-der.js └── der-to-jose.js ├── package.json ├── spec ├── jose-to-der.js ├── inverse.js └── der-to-jose.js ├── README.md └── LICENSE /.eslintignore: -------------------------------------------------------------------------------- 1 | .gitignore -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @omsmith 2 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | ignore-scripts=true 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | 3 | *.log 4 | *.swo 5 | *.swp 6 | 7 | coverage 8 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "brightspace/node-config", 3 | "env": { 4 | "es6": false 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .gitignore 2 | .npmignore 3 | 4 | .editorconfig 5 | .eslintignore 6 | .eslintrc 7 | 8 | spec 9 | benchmarks 10 | fuzz 11 | coverage 12 | .travis.yml 13 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # top-most EditorConfig file 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | end_of_line = lf 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | indent_style = tab 10 | indent_size = 4 11 | 12 | [*{.json,.yml}] 13 | indent_style = space 14 | indent_size = 2 15 | -------------------------------------------------------------------------------- /src/param-bytes-for-alg.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | function getParamSize(keySize) { 4 | var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); 5 | return result; 6 | } 7 | 8 | var paramBytesForAlg = { 9 | ES256: getParamSize(256), 10 | ES384: getParamSize(384), 11 | ES512: getParamSize(521) 12 | }; 13 | 14 | function getParamBytesForAlg(alg) { 15 | var paramBytes = paramBytesForAlg[alg]; 16 | if (paramBytes) { 17 | return paramBytes; 18 | } 19 | 20 | throw new Error('Unknown algorithm "' + alg + '"'); 21 | } 22 | 23 | module.exports = getParamBytesForAlg; 24 | -------------------------------------------------------------------------------- /src/ecdsa-sig-formatter.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | declare module "ecdsa-sig-formatter" { 4 | /** 5 | * Convert the ASN.1/DER encoded signature to a JOSE-style concatenated signature. Returns a base64 url encoded String. 6 | * If signature is a String, it should be base64 encoded 7 | * alg must be one of ES256, ES384 or ES512 8 | */ 9 | export function derToJose(signature: Buffer | string, alg: string): string; 10 | 11 | /** 12 | * Convert the JOSE-style concatenated signature to an ASN.1/DER encoded signature. Returns a Buffer 13 | * If signature is a String, it should be base64 url encoded 14 | * alg must be one of ES256, ES384 or ES512 15 | */ 16 | export function joseToDer(signature: Buffer | string, alg: string): Buffer 17 | } 18 | -------------------------------------------------------------------------------- /fuzz/happy.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var assert = require('assert'), 4 | crypto = require('crypto'), 5 | jwkToPem = require('jwk-to-pem'), 6 | nCrypto = require('native-crypto'); 7 | 8 | var conv = require('../'); 9 | 10 | var sslalgs = { 11 | 'ES256': 'RSA-SHA256', 12 | 'ES384': 'RSA-SHA384', 13 | 'ES512': 'RSA-SHA512' 14 | }; 15 | 16 | var crvs = { 17 | ES256: 'P-256', 18 | ES384: 'P-384', 19 | ES512: 'P-521' 20 | }; 21 | 22 | ['ES256', 'ES384', 'ES512'].forEach(function(alg) { 23 | for (var i = 0; i < 10; ++i) { 24 | nCrypto 25 | .generate(crvs[alg]) 26 | .then(function(keypair) { 27 | return jwkToPem(keypair.privateKey, { private: true }); 28 | }) 29 | .then(function(pem) { 30 | for (var j = 0; j < 10000; ++j) { 31 | var der = crypto 32 | .createSign(sslalgs[alg]) 33 | .update(crypto.randomBytes((Math.random() * (256 - 1) | 0) + 1)) 34 | .sign(pem); 35 | 36 | assert(conv.joseToDer(conv.derToJose(der, alg), alg).equals(der)); 37 | } 38 | }); 39 | } 40 | }); 41 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: node_js 3 | node_js: 4 | - '0.12' 5 | - 4 6 | - 6 7 | - 8 8 | - 10 9 | after_success: npm run report-cov 10 | deploy: 11 | provider: npm 12 | email: d2ltravisdeploy@d2l.com 13 | api_key: 14 | # d2l-travis-deploy: 0655......8469 15 | secure: FawA6VEKDBIS4ow4f/vKzC+W8YlzQCgHA/CnAgEmtrkWBR73ADhuEk1Gl5YSYAbMccmKCsEEpmsQqgMC3ddALRIlifu6IzQE6+KQj9uXOwST9Y9f6+STznf0XHpTje2eBn5F9Wa92tzcSIQJbrLpuD5kq/32tiH0ZyhnmKuW4ZJwou/+wG4uuOnon6HBsqvy3u9nMCGnDPwdTkuAr7Hc5KWiMOVuayFoLpIZ5PKuIbne404iMmkIQVxeoDLgFRehqo5zxLP1YPbCic0Vdz9r++nz+7EaJbspGNK/K6K6tzR4bb+BfN9TVB8x97cf49vt+ZTnvhjqXnrkSii+PCTyyZ7O/0oMrLVMOzkJ1yjUoZDqFUtN4wJFl/kNKw+ICXWan8vFFpldAxsLsyvgTU5pLuL/20NJNMZK0AV9pfuNUPs3yDni7jH14xjIaYH5zzU/DDXOgy38sQNIDRvLlV2d6GFZpmC35bLopx8iH3SZ9u9LOVYRc4GjG8hLZY0Ca/nGcrGvvGjPPl6Xu4TjI0S/lmAv7XpqGsv/Lb2J0SjEZQwjhh/BpvIDPGGoPILqn13fhrg6bc/kfI1/hHG4fHCwKQsQVkfV8pK0d/ZcPbFL+McMz3b967adD+PIpJ5cHCsTkFzp3YmW62mIHKi1kwF6yC1q2GOvVzXlk8WaSkVyrrI= 16 | on: 17 | tags: true 18 | repo: Brightspace/node-ecdsa-sig-formatter 19 | node: 10 20 | -------------------------------------------------------------------------------- /benchmarks/jose-to-der.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var Buffer = require('safe-buffer').Buffer; 4 | 5 | var joseToDer = require('..').joseToDer; 6 | 7 | var sigs = [ 8 | ['yA4WNemRpUreSh9qgMh_ePGqhgn328ghJ_HG7WOBKQV98eFNm3FIvweoiSzHvl49Z6YTdV4Up7NDD7UcZ-52cw', 'ES256'], 9 | ['TsS1fXqgq5S2lpjO-Tz5w6ZAKqNFuQ6PufvXRN2NRY2DEsQ3iUXdEcAzcMXNqVehkZ-NwUxdIvDqwKTGLYQYVhjBxkdnwm1T5VKG2v1BYFeDQ91sgBlVhHFzvFty5wCI', 'ES384'], 10 | ['AFKapY_5gq60n8NZ_C2iOQFov7sXgcMyDzCrnGsbvE7OlSBKbgj95aZ7GtdSdbw6joK2jjWJio8IgKNB9o11GdMTADfLUsv9oAJvmIApsmsPBAIe1vH8oeHYiDMBEz9OQcwS5eL-r1iO2v7oxzl9zZb1rA5kzBqS93ARCPKbjgcr602r', 'ES512'] 11 | ]; 12 | 13 | var sigBuffers = sigs.map(function(sig) { 14 | return [Buffer.from(sig[0], 'base64'), sig[1]]; 15 | }); 16 | 17 | module.exports.compare = { 18 | fromBase64: function() { 19 | for (var i = 0, n = sigs.length; i < n; ++i) { 20 | joseToDer.apply(null, sigs[i]); 21 | } 22 | }, 23 | fromBuffer: function() { 24 | for (var i = 0, n = sigBuffers.length; i < n; ++i) { 25 | joseToDer.apply(null, sigBuffers[i]); 26 | } 27 | } 28 | }; 29 | 30 | module.exports.compareCount = 20; 31 | module.exports.countPerLap = sigs.length; 32 | 33 | require('bench').runMain(); 34 | -------------------------------------------------------------------------------- /benchmarks/der-to-jose.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var Buffer = require('safe-buffer').Buffer; 4 | 5 | var derToJose = require('..').derToJose; 6 | 7 | var sigs = [ 8 | ['MEUCIQD0nDQE4uBS6JuklnyACfPQRB/LMEh5Stq6sAfp38k6ewIgHvhX59iuruBiFpVkg3dQKJ3+Wk29lJmXfxp6ciRdj+Q=', 'ES256'], 9 | ['MGUCMADcY5icKo+sLF0YCh5eVzju55Elt3Dfu4geMMDnUlLNaEO8NiCFzCHeqMx7mW5GMwIxAI6sp8ihHjRJ0sn/WV6mZCxN6/5lEg1QZJ5eiUHYv2kBgmiJ/Yv1pnqqFY3gVDBp/g==', 'ES384'], 10 | ['MIGHAkFgiYpVsYxx6XiQp2OXscRW/PrbEcoime/FftP+B7x4QVa+M3KZzXlfP66zKqjo7O3nwK2s8GbTftW8H4HwojzimwJCAYQNsozTpCo5nwIkBgelcfIQ0y/U/60TbNH1+rlKpFDCFs6Q1ro7R1tjtXoAUb9aPIOVyXGiSQX/+fcmmWs1rkJU', 'ES512'] 11 | ]; 12 | 13 | var sigBuffers = sigs.map(function(sig) { 14 | return [Buffer.from(sig[0], 'base64'), sig[1]]; 15 | }); 16 | 17 | module.exports.compare = { 18 | fromBase64: function() { 19 | for (var i = 0, n = sigs.length; i < n; ++i) { 20 | derToJose.apply(null, sigs[i]); 21 | } 22 | }, 23 | fromBuffer: function() { 24 | for (var i = 0, n = sigBuffers.length; i < n; ++i) { 25 | derToJose.apply(null, sigBuffers[i]); 26 | } 27 | } 28 | }; 29 | 30 | module.exports.compareCount = 20; 31 | module.exports.countPerLap = sigs.length; 32 | 33 | require('bench').runMain(); 34 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ecdsa-sig-formatter", 3 | "version": "1.0.11", 4 | "description": "Translate ECDSA signatures between ASN.1/DER and JOSE-style concatenation", 5 | "main": "src/ecdsa-sig-formatter.js", 6 | "scripts": { 7 | "check-style": "eslint .", 8 | "pretest": "npm run check-style", 9 | "test": "istanbul cover --root src _mocha -- spec", 10 | "report-cov": "cat ./coverage/lcov.info | coveralls" 11 | }, 12 | "typings": "./src/ecdsa-sig-formatter.d.ts", 13 | "repository": { 14 | "type": "git", 15 | "url": "git+ssh://git@github.com/Brightspace/node-ecdsa-sig-formatter.git" 16 | }, 17 | "keywords": [ 18 | "ecdsa", 19 | "der", 20 | "asn.1", 21 | "jwt", 22 | "jwa", 23 | "jsonwebtoken", 24 | "jose" 25 | ], 26 | "author": "D2L Corporation", 27 | "license": "Apache-2.0", 28 | "bugs": { 29 | "url": "https://github.com/Brightspace/node-ecdsa-sig-formatter/issues" 30 | }, 31 | "homepage": "https://github.com/Brightspace/node-ecdsa-sig-formatter#readme", 32 | "dependencies": { 33 | "safe-buffer": "^5.0.1" 34 | }, 35 | "devDependencies": { 36 | "bench": "^0.3.6", 37 | "chai": "^4.1.2", 38 | "coveralls": "^3.0.0", 39 | "eslint": "^2.13.1", 40 | "eslint-config-brightspace": "^0.4.0", 41 | "istanbul": "^0.4.3", 42 | "jwk-to-pem": "^2.0.0", 43 | "mocha": "^3.5.3", 44 | "native-crypto": "^1.7.0" 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /spec/jose-to-der.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var expect = require('chai').expect, 4 | mocha = require('mocha'); 5 | 6 | var describe = mocha.describe, 7 | it = mocha.it; 8 | 9 | var format = require('..'); 10 | 11 | describe('#joseToDer', function() { 12 | describe('should throw for', function() { 13 | it('no signature', function() { 14 | function fn() { 15 | return format.joseToDer(); 16 | } 17 | 18 | expect(fn).to.throw(TypeError); 19 | }); 20 | 21 | it('non buffer or base64 signature', function() { 22 | function fn() { 23 | return format.joseToDer(123); 24 | } 25 | 26 | expect(fn).to.throw(TypeError); 27 | }); 28 | 29 | it('unknown algorithm', function() { 30 | function fn() { 31 | return format.joseToDer('Zm9vLmJhci5iYXo=', 'foozleberries'); 32 | } 33 | 34 | expect(fn).to.throw(/"foozleberries"/); 35 | }); 36 | 37 | it('incorrect signature length (ES256)', function() { 38 | function fn() { 39 | return format.joseToDer('Zm9vLmJhci5iYXo', 'ES256'); 40 | } 41 | 42 | expect(fn).to.throw(/"64"/); 43 | }); 44 | 45 | it('incorrect signature length (ES384)', function() { 46 | function fn() { 47 | return format.joseToDer('Zm9vLmJhci5iYXo', 'ES384'); 48 | } 49 | 50 | expect(fn).to.throw(/"96"/); 51 | }); 52 | 53 | it('incorrect signature length (ES512)', function() { 54 | function fn() { 55 | return format.joseToDer('Zm9vLmJhci5iYXo', 'ES512'); 56 | } 57 | 58 | expect(fn).to.throw(/"132"/); 59 | }); 60 | }); 61 | }); 62 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ecdsa-sig-formatter 2 | 3 | [![Build Status](https://travis-ci.org/Brightspace/node-ecdsa-sig-formatter.svg?branch=master)](https://travis-ci.org/Brightspace/node-ecdsa-sig-formatter) [![Coverage Status](https://coveralls.io/repos/Brightspace/node-ecdsa-sig-formatter/badge.svg)](https://coveralls.io/r/Brightspace/node-ecdsa-sig-formatter) 4 | 5 | Translate between JOSE and ASN.1/DER encodings for ECDSA signatures 6 | 7 | ## Install 8 | ```sh 9 | npm install ecdsa-sig-formatter --save 10 | ``` 11 | 12 | ## Usage 13 | ```js 14 | var format = require('ecdsa-sig-formatter'); 15 | 16 | var derSignature = '..'; // asn.1/DER encoded ecdsa signature 17 | 18 | var joseSignature = format.derToJose(derSignature); 19 | 20 | ``` 21 | 22 | ### API 23 | 24 | --- 25 | 26 | #### `.derToJose(Buffer|String signature, String alg)` -> `String` 27 | 28 | Convert the ASN.1/DER encoded signature to a JOSE-style concatenated signature. 29 | Returns a _base64 url_ encoded `String`. 30 | 31 | * If _signature_ is a `String`, it should be _base64_ encoded 32 | * _alg_ must be one of _ES256_, _ES384_ or _ES512_ 33 | 34 | --- 35 | 36 | #### `.joseToDer(Buffer|String signature, String alg)` -> `Buffer` 37 | 38 | Convert the JOSE-style concatenated signature to an ASN.1/DER encoded 39 | signature. Returns a `Buffer` 40 | 41 | * If _signature_ is a `String`, it should be _base64 url_ encoded 42 | * _alg_ must be one of _ES256_, _ES384_ or _ES512_ 43 | 44 | ## Contributing 45 | 46 | 1. **Fork** the repository. Committing directly against this repository is 47 | highly discouraged. 48 | 49 | 2. Make your modifications in a branch, updating and writing new unit tests 50 | as necessary in the `spec` directory. 51 | 52 | 3. Ensure that all tests pass with `npm test` 53 | 54 | 4. `rebase` your changes against master. *Do not merge*. 55 | 56 | 5. Submit a pull request to this repository. Wait for tests to run and someone 57 | to chime in. 58 | 59 | ### Code Style 60 | 61 | This repository is configured with [EditorConfig][EditorConfig] and 62 | [ESLint][ESLint] rules. 63 | 64 | [EditorConfig]: http://editorconfig.org/ 65 | [ESLint]: http://eslint.org 66 | -------------------------------------------------------------------------------- /spec/inverse.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var expect = require('chai').expect, 4 | mocha = require('mocha'); 5 | 6 | var describe = mocha.describe, 7 | it = mocha.it; 8 | 9 | var format = require('..'); 10 | 11 | describe('inverse', function() { 12 | describe('ES256', function() { 13 | it('should jose -> der -> jose', function() { 14 | // Made with WebCrypto 15 | var expected = 'yA4WNemRpUreSh9qgMh_ePGqhgn328ghJ_HG7WOBKQV98eFNm3FIvweoiSzHvl49Z6YTdV4Up7NDD7UcZ-52cw'; 16 | var der = format.joseToDer(expected, 'ES256'); 17 | var actual = format.derToJose(der, 'ES256'); 18 | 19 | expect(actual).to.equal(expected); 20 | }); 21 | 22 | it('should der -> jose -> der', function() { 23 | // Made with OpenSSL 24 | var expected = 'MEUCIQD0nDQE4uBS6JuklnyACfPQRB/LMEh5Stq6sAfp38k6ewIgHvhX59iuruBiFpVkg3dQKJ3+Wk29lJmXfxp6ciRdj+Q='; 25 | var jose = format.derToJose(expected, 'ES256'); 26 | var actual = format.joseToDer(jose, 'ES256'); 27 | 28 | expect(actual.toString('base64')).to.equal(expected); 29 | }); 30 | }); 31 | 32 | describe('ES384', function() { 33 | it('should jose -> der -> jose', function() { 34 | // Made with WebCrypto 35 | var expected = 'TsS1fXqgq5S2lpjO-Tz5w6ZAKqNFuQ6PufvXRN2NRY2DEsQ3iUXdEcAzcMXNqVehkZ-NwUxdIvDqwKTGLYQYVhjBxkdnwm1T5VKG2v1BYFeDQ91sgBlVhHFzvFty5wCI'; 36 | var der = format.joseToDer(expected, 'ES384'); 37 | var actual = format.derToJose(der, 'ES384'); 38 | 39 | expect(actual).to.equal(expected); 40 | }); 41 | 42 | it('should der -> jose -> der', function() { 43 | // Made with OpenSSL 44 | var expected = 'MGUCMADcY5icKo+sLF0YCh5eVzju55Elt3Dfu4geMMDnUlLNaEO8NiCFzCHeqMx7mW5GMwIxAI6sp8ihHjRJ0sn/WV6mZCxN6/5lEg1QZJ5eiUHYv2kBgmiJ/Yv1pnqqFY3gVDBp/g=='; 45 | var jose = format.derToJose(expected, 'ES384'); 46 | var actual = format.joseToDer(jose, 'ES384'); 47 | 48 | expect(actual.toString('base64')).to.equal(expected); 49 | }); 50 | }); 51 | 52 | describe('ES512', function() { 53 | it('should jose -> der -> jose', function() { 54 | // Made with WebCrypto 55 | var expected = 'AFKapY_5gq60n8NZ_C2iOQFov7sXgcMyDzCrnGsbvE7OlSBKbgj95aZ7GtdSdbw6joK2jjWJio8IgKNB9o11GdMTADfLUsv9oAJvmIApsmsPBAIe1vH8oeHYiDMBEz9OQcwS5eL-r1iO2v7oxzl9zZb1rA5kzBqS93ARCPKbjgcr602r'; 56 | var der = format.joseToDer(expected, 'ES512'); 57 | var actual = format.derToJose(der, 'ES512'); 58 | 59 | expect(actual).to.equal(expected); 60 | }); 61 | 62 | it('should der -> jose -> der', function() { 63 | // Made with OpenSSL 64 | var expected = 'MIGHAkFgiYpVsYxx6XiQp2OXscRW/PrbEcoime/FftP+B7x4QVa+M3KZzXlfP66zKqjo7O3nwK2s8GbTftW8H4HwojzimwJCAYQNsozTpCo5nwIkBgelcfIQ0y/U/60TbNH1+rlKpFDCFs6Q1ro7R1tjtXoAUb9aPIOVyXGiSQX/+fcmmWs1rkJU'; 65 | var jose = format.derToJose(expected, 'ES512'); 66 | var actual = format.joseToDer(jose, 'ES512'); 67 | 68 | expect(actual.toString('base64')).to.equal(expected); 69 | }); 70 | }); 71 | }); 72 | -------------------------------------------------------------------------------- /spec/der-to-jose.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var Buffer = require('safe-buffer').Buffer, 4 | expect = require('chai').expect, 5 | mocha = require('mocha'); 6 | 7 | var describe = mocha.describe, 8 | it = mocha.it; 9 | 10 | var format = require('..'); 11 | var getParamBytesForAlg = require('../src/param-bytes-for-alg'); 12 | 13 | var CLASS_UNIVERSAL = 0, 14 | PRIMITIVE_BIT = 0x20, 15 | TAG_SEQ = (0x10 | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), 16 | TAG_INT = 0x02 | (CLASS_UNIVERSAL << 6); 17 | 18 | describe('#derToJose', function() { 19 | ['ES256', 'ES384', 'ES512'].forEach(function(alg) { 20 | describe(alg, function() { 21 | describe('should throw for', function() { 22 | it('no signature', function() { 23 | function fn() { 24 | return format.derToJose(); 25 | } 26 | 27 | expect(fn).to.throw(TypeError); 28 | }); 29 | 30 | it('non buffer or base64 signature', function() { 31 | function fn() { 32 | return format.derToJose(123); 33 | } 34 | 35 | expect(fn).to.throw(TypeError); 36 | }); 37 | 38 | it('unknown algorithm', function() { 39 | function fn() { 40 | return format.derToJose('Zm9vLmJhci5iYXo=', 'foozleberries'); 41 | } 42 | 43 | expect(fn).to.throw(/"foozleberries"/); 44 | }); 45 | 46 | it('no seq', function() { 47 | var input = Buffer.alloc(10); 48 | input[0] = TAG_SEQ + 1; // not seq 49 | 50 | function fn() { 51 | format.derToJose(input, alg); 52 | } 53 | 54 | expect(fn).to.throw(Error, /expected "seq"/); 55 | }); 56 | 57 | it('seq length exceeding input', function() { 58 | var input = Buffer.alloc(10); 59 | input[0] = TAG_SEQ; 60 | input[1] = 10; 61 | 62 | function fn() { 63 | format.derToJose(input, alg); 64 | } 65 | 66 | expect(fn).to.throw(Error, /length/); 67 | }); 68 | 69 | it('r is not marked as int', function() { 70 | var input = Buffer.alloc(10); 71 | input[0] = TAG_SEQ; 72 | input[1] = 8; 73 | input[2] = TAG_INT + 1; // not int 74 | 75 | function fn() { 76 | format.derToJose(input, alg); 77 | } 78 | 79 | expect(fn).to.throw(Error, /expected "int".+"r"/); 80 | }); 81 | 82 | it('r length exceeds available input', function() { 83 | var input = Buffer.alloc(10); 84 | input[0] = TAG_SEQ; 85 | input[1] = 8; 86 | input[2] = TAG_INT; 87 | input[3] = 5; 88 | 89 | function fn() { 90 | format.derToJose(input, alg); 91 | } 92 | 93 | expect(fn).to.throw(Error, /"r".+length/); 94 | }); 95 | 96 | it('r length exceeds sensical param length', function() { 97 | var input = Buffer.alloc(getParamBytesForAlg(alg) + 2 + 6); 98 | input[0] = TAG_SEQ; 99 | input[1] = getParamBytesForAlg(alg) + 2 + 4; 100 | input[2] = TAG_INT; 101 | input[3] = getParamBytesForAlg(alg) + 2; 102 | 103 | function fn() { 104 | format.derToJose(input, alg); 105 | } 106 | 107 | expect(fn).to.throw(Error, /"r".+length.+acceptable/); 108 | }); 109 | 110 | it('s is not marked as int', function() { 111 | var input = Buffer.alloc(10); 112 | input[0] = TAG_SEQ; 113 | input[1] = 8; 114 | input[2] = TAG_INT; 115 | input[3] = 2; 116 | input[4] = 0; 117 | input[5] = 0; 118 | input[6] = TAG_INT + 1; // not int 119 | 120 | function fn() { 121 | format.derToJose(input, alg); 122 | } 123 | 124 | expect(fn).to.throw(Error, /expected "int".+"s"/); 125 | }); 126 | 127 | it('s length exceeds available input', function() { 128 | var input = Buffer.alloc(10); 129 | input[0] = TAG_SEQ; 130 | input[1] = 8; 131 | input[2] = TAG_INT; 132 | input[3] = 2; 133 | input[4] = 0; 134 | input[5] = 0; 135 | input[6] = TAG_INT; 136 | input[7] = 3; 137 | 138 | function fn() { 139 | format.derToJose(input, alg); 140 | } 141 | 142 | expect(fn).to.throw(Error, /"s".+length/); 143 | }); 144 | 145 | it('s length does not consume available input', function() { 146 | var input = Buffer.alloc(10); 147 | input[0] = TAG_SEQ; 148 | input[1] = 8; 149 | input[2] = TAG_INT; 150 | input[3] = 2; 151 | input[4] = 0; 152 | input[5] = 0; 153 | input[6] = TAG_INT; 154 | input[7] = 1; 155 | 156 | function fn() { 157 | format.derToJose(input, alg); 158 | } 159 | 160 | expect(fn).to.throw(Error, /"s".+length/); 161 | }); 162 | 163 | it('s length exceeds sensical param length', function() { 164 | var input = Buffer.alloc(getParamBytesForAlg(alg) + 2 + 8); 165 | input[0] = TAG_SEQ; 166 | input[1] = getParamBytesForAlg(alg) + 2 + 6; 167 | input[2] = TAG_INT; 168 | input[3] = 2; 169 | input[4] = 0; 170 | input[5] = 0; 171 | input[6] = TAG_INT; 172 | input[7] = getParamBytesForAlg(alg) + 2; 173 | 174 | function fn() { 175 | format.derToJose(input, alg); 176 | } 177 | 178 | expect(fn).to.throw(Error, /"s".+length.+acceptable/); 179 | }); 180 | }); 181 | }); 182 | }); 183 | }); 184 | -------------------------------------------------------------------------------- /src/ecdsa-sig-formatter.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var Buffer = require('safe-buffer').Buffer; 4 | 5 | var getParamBytesForAlg = require('./param-bytes-for-alg'); 6 | 7 | var MAX_OCTET = 0x80, 8 | CLASS_UNIVERSAL = 0, 9 | PRIMITIVE_BIT = 0x20, 10 | TAG_SEQ = 0x10, 11 | TAG_INT = 0x02, 12 | ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), 13 | ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6); 14 | 15 | function base64Url(base64) { 16 | return base64 17 | .replace(/=/g, '') 18 | .replace(/\+/g, '-') 19 | .replace(/\//g, '_'); 20 | } 21 | 22 | function signatureAsBuffer(signature) { 23 | if (Buffer.isBuffer(signature)) { 24 | return signature; 25 | } else if ('string' === typeof signature) { 26 | return Buffer.from(signature, 'base64'); 27 | } 28 | 29 | throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); 30 | } 31 | 32 | function derToJose(signature, alg) { 33 | signature = signatureAsBuffer(signature); 34 | var paramBytes = getParamBytesForAlg(alg); 35 | 36 | // the DER encoded param should at most be the param size, plus a padding 37 | // zero, since due to being a signed integer 38 | var maxEncodedParamLength = paramBytes + 1; 39 | 40 | var inputLength = signature.length; 41 | 42 | var offset = 0; 43 | if (signature[offset++] !== ENCODED_TAG_SEQ) { 44 | throw new Error('Could not find expected "seq"'); 45 | } 46 | 47 | var seqLength = signature[offset++]; 48 | if (seqLength === (MAX_OCTET | 1)) { 49 | seqLength = signature[offset++]; 50 | } 51 | 52 | if (inputLength - offset < seqLength) { 53 | throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); 54 | } 55 | 56 | if (signature[offset++] !== ENCODED_TAG_INT) { 57 | throw new Error('Could not find expected "int" for "r"'); 58 | } 59 | 60 | var rLength = signature[offset++]; 61 | 62 | if (inputLength - offset - 2 < rLength) { 63 | throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); 64 | } 65 | 66 | if (maxEncodedParamLength < rLength) { 67 | throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); 68 | } 69 | 70 | var rOffset = offset; 71 | offset += rLength; 72 | 73 | if (signature[offset++] !== ENCODED_TAG_INT) { 74 | throw new Error('Could not find expected "int" for "s"'); 75 | } 76 | 77 | var sLength = signature[offset++]; 78 | 79 | if (inputLength - offset !== sLength) { 80 | throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); 81 | } 82 | 83 | if (maxEncodedParamLength < sLength) { 84 | throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); 85 | } 86 | 87 | var sOffset = offset; 88 | offset += sLength; 89 | 90 | if (offset !== inputLength) { 91 | throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); 92 | } 93 | 94 | var rPadding = paramBytes - rLength, 95 | sPadding = paramBytes - sLength; 96 | 97 | var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); 98 | 99 | for (offset = 0; offset < rPadding; ++offset) { 100 | dst[offset] = 0; 101 | } 102 | signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); 103 | 104 | offset = paramBytes; 105 | 106 | for (var o = offset; offset < o + sPadding; ++offset) { 107 | dst[offset] = 0; 108 | } 109 | signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); 110 | 111 | dst = dst.toString('base64'); 112 | dst = base64Url(dst); 113 | 114 | return dst; 115 | } 116 | 117 | function countPadding(buf, start, stop) { 118 | var padding = 0; 119 | while (start + padding < stop && buf[start + padding] === 0) { 120 | ++padding; 121 | } 122 | 123 | var needsSign = buf[start + padding] >= MAX_OCTET; 124 | if (needsSign) { 125 | --padding; 126 | } 127 | 128 | return padding; 129 | } 130 | 131 | function joseToDer(signature, alg) { 132 | signature = signatureAsBuffer(signature); 133 | var paramBytes = getParamBytesForAlg(alg); 134 | 135 | var signatureBytes = signature.length; 136 | if (signatureBytes !== paramBytes * 2) { 137 | throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); 138 | } 139 | 140 | var rPadding = countPadding(signature, 0, paramBytes); 141 | var sPadding = countPadding(signature, paramBytes, signature.length); 142 | var rLength = paramBytes - rPadding; 143 | var sLength = paramBytes - sPadding; 144 | 145 | var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; 146 | 147 | var shortLength = rsBytes < MAX_OCTET; 148 | 149 | var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); 150 | 151 | var offset = 0; 152 | dst[offset++] = ENCODED_TAG_SEQ; 153 | if (shortLength) { 154 | // Bit 8 has value "0" 155 | // bits 7-1 give the length. 156 | dst[offset++] = rsBytes; 157 | } else { 158 | // Bit 8 of first octet has value "1" 159 | // bits 7-1 give the number of additional length octets. 160 | dst[offset++] = MAX_OCTET | 1; 161 | // length, base 256 162 | dst[offset++] = rsBytes & 0xff; 163 | } 164 | dst[offset++] = ENCODED_TAG_INT; 165 | dst[offset++] = rLength; 166 | if (rPadding < 0) { 167 | dst[offset++] = 0; 168 | offset += signature.copy(dst, offset, 0, paramBytes); 169 | } else { 170 | offset += signature.copy(dst, offset, rPadding, paramBytes); 171 | } 172 | dst[offset++] = ENCODED_TAG_INT; 173 | dst[offset++] = sLength; 174 | if (sPadding < 0) { 175 | dst[offset++] = 0; 176 | signature.copy(dst, offset, paramBytes); 177 | } else { 178 | signature.copy(dst, offset, paramBytes + sPadding); 179 | } 180 | 181 | return dst; 182 | } 183 | 184 | module.exports = { 185 | derToJose: derToJose, 186 | joseToDer: joseToDer 187 | }; 188 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2015 D2L Corporation 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------