mirror of
https://github.com/fluencelabs/js-libp2p-crypto
synced 2025-07-23 00:22:12 +00:00
Compare commits
73 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
2d15e717e4 | ||
|
6775dbf670 | ||
|
4b09aae8ca | ||
|
764d8bff3e | ||
|
26b6217041 | ||
|
5500ac4a6e | ||
|
d675670ed9 | ||
|
ad7107233e | ||
|
5cd0e8cc1a | ||
|
0ffe31821a | ||
|
7b3625888c | ||
|
b7bce77ad5 | ||
|
c1f867bd9c | ||
|
e3f02eb6f1 | ||
|
a0874389a9 | ||
|
567d68c855 | ||
|
af782c5906 | ||
|
f0593c9e6d | ||
|
8d8294dc3f | ||
|
df23d634c5 | ||
|
88e1bcf75f | ||
|
c54ea206f0 | ||
|
857d2bd902 | ||
|
200110cb9d | ||
|
9e5778694c | ||
|
87e8f1c86f | ||
|
df75980a88 | ||
|
934390acd3 | ||
|
8b80b46667 | ||
|
e8efad546f | ||
|
e8cbf13d85 | ||
|
c7e0409c1c | ||
|
f4c00893ad | ||
|
b05e77f375 | ||
|
ad478454d8 | ||
|
8c69ffb20f | ||
|
e689a402a3 | ||
|
4bd032a6ae | ||
|
50c61ba46e | ||
|
3a90f70350 | ||
|
743c69524c | ||
|
1a347fa04c | ||
|
71339e08e7 | ||
|
0ab2c2d2d6 | ||
|
cdcca5f828 | ||
|
2c0dc706b7 | ||
|
21d4c8b74e | ||
|
285b6ca392 | ||
|
7d96dd3243 | ||
|
b3421284f9 | ||
|
f3cb8ced36 | ||
|
0a6f63dce5 | ||
|
0ce5f34a08 | ||
|
a826968e71 | ||
|
7608fdd858 | ||
|
bf9b532067 | ||
|
5296f8a42f | ||
|
3a91ae2ed8 | ||
|
e7c11a8e01 | ||
|
9bb96dc2bf | ||
|
957fdd37e9 | ||
|
83257bc4bd | ||
|
cb7fae7fcc | ||
|
7669847c17 | ||
|
dc2793f138 | ||
|
e0b916ace9 | ||
|
0a71af7b89 | ||
|
46adafb207 | ||
|
9e977c7d44 | ||
|
f20267b962 | ||
|
1b6a070fa8 | ||
|
1471e07bf9 | ||
|
bc554d1407 |
1
.eslintignore
Normal file
1
.eslintignore
Normal file
@@ -0,0 +1 @@
|
|||||||
|
src/keys/keys.proto.js
|
13
.gitignore
vendored
13
.gitignore
vendored
@@ -1,6 +1,11 @@
|
|||||||
|
docs
|
||||||
|
package-lock.json
|
||||||
|
yarn.lock
|
||||||
|
|
||||||
**/node_modules/
|
**/node_modules/
|
||||||
**/*.log
|
**/*.log
|
||||||
test/repo-tests*
|
test/repo-tests*
|
||||||
|
**/bundle.js
|
||||||
|
|
||||||
# Logs
|
# Logs
|
||||||
logs
|
logs
|
||||||
@@ -31,4 +36,12 @@ build
|
|||||||
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git
|
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git
|
||||||
node_modules
|
node_modules
|
||||||
|
|
||||||
|
lib
|
||||||
dist
|
dist
|
||||||
|
test/test-data/go-ipfs-repo/LOCK
|
||||||
|
test/test-data/go-ipfs-repo/LOG
|
||||||
|
test/test-data/go-ipfs-repo/LOG.old
|
||||||
|
|
||||||
|
# while testing npm5
|
||||||
|
package-lock.json
|
||||||
|
yarn.lock
|
||||||
|
34
.npmignore
34
.npmignore
@@ -1,34 +0,0 @@
|
|||||||
**/node_modules/
|
|
||||||
**/*.log
|
|
||||||
test/repo-tests*
|
|
||||||
|
|
||||||
# Logs
|
|
||||||
logs
|
|
||||||
*.log
|
|
||||||
|
|
||||||
coverage
|
|
||||||
|
|
||||||
# Runtime data
|
|
||||||
pids
|
|
||||||
*.pid
|
|
||||||
*.seed
|
|
||||||
|
|
||||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
|
||||||
lib-cov
|
|
||||||
|
|
||||||
# Coverage directory used by tools like istanbul
|
|
||||||
coverage
|
|
||||||
|
|
||||||
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
|
|
||||||
.grunt
|
|
||||||
|
|
||||||
# node-waf configuration
|
|
||||||
.lock-wscript
|
|
||||||
|
|
||||||
build
|
|
||||||
|
|
||||||
# Dependency directory
|
|
||||||
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git
|
|
||||||
node_modules
|
|
||||||
|
|
||||||
test
|
|
68
.travis.yml
68
.travis.yml
@@ -1,35 +1,45 @@
|
|||||||
sudo: false
|
|
||||||
language: node_js
|
language: node_js
|
||||||
|
|
||||||
matrix:
|
cache: npm
|
||||||
|
|
||||||
|
stages:
|
||||||
|
- check
|
||||||
|
- test
|
||||||
|
- cov
|
||||||
|
|
||||||
|
node_js:
|
||||||
|
- '10'
|
||||||
|
- '12'
|
||||||
|
|
||||||
|
os:
|
||||||
|
- linux
|
||||||
|
- osx
|
||||||
|
- windows
|
||||||
|
|
||||||
|
script: npx nyc -s npm run test:node -- --bail
|
||||||
|
after_success: npx nyc report --reporter=text-lcov > coverage.lcov && npx codecov
|
||||||
|
|
||||||
|
jobs:
|
||||||
include:
|
include:
|
||||||
- node_js: 4
|
- stage: check
|
||||||
env: CXX=g++-4.8
|
script:
|
||||||
- node_js: 6
|
- npx aegir commitlint --travis
|
||||||
env: CXX=g++-4.8
|
- npx aegir dep-check
|
||||||
- node_js: stable
|
- npm run lint
|
||||||
env: CXX=g++-4.8
|
|
||||||
|
|
||||||
# Make sure we have new NPM.
|
- stage: test
|
||||||
before_install:
|
name: chrome
|
||||||
- npm install -g npm@4
|
addons:
|
||||||
|
chrome: stable
|
||||||
|
script:
|
||||||
|
- npx aegir test -t browser
|
||||||
|
|
||||||
script:
|
- stage: test
|
||||||
- npm run lint
|
name: firefox
|
||||||
- npm test
|
addons:
|
||||||
- npm run coverage
|
firefox: latest
|
||||||
|
script:
|
||||||
|
- npx aegir test -t browser -- --browsers FirefoxHeadless
|
||||||
|
|
||||||
before_script:
|
notifications:
|
||||||
- export DISPLAY=:99.0
|
email: false
|
||||||
- sh -e /etc/init.d/xvfb start
|
|
||||||
|
|
||||||
after_success:
|
|
||||||
- npm run coverage-publish
|
|
||||||
|
|
||||||
addons:
|
|
||||||
firefox: 'latest'
|
|
||||||
apt:
|
|
||||||
sources:
|
|
||||||
- ubuntu-toolchain-r-test
|
|
||||||
packages:
|
|
||||||
- g++-4.8
|
|
||||||
|
184
CHANGELOG.md
184
CHANGELOG.md
@@ -1,3 +1,187 @@
|
|||||||
|
<a name="0.17.0"></a>
|
||||||
|
# [0.17.0](https://github.com/libp2p/js-libp2p-crypto/compare/v0.16.1...v0.17.0) (2019-07-11)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **deps:** update to ursa-optiona@0.10 ([26b6217](https://github.com/libp2p/js-libp2p-crypto/commit/26b6217))
|
||||||
|
* fix links in README ([#148](https://github.com/libp2p/js-libp2p-crypto/issues/148)) ([5cd0e8c](https://github.com/libp2p/js-libp2p-crypto/commit/5cd0e8c))
|
||||||
|
* put optional args last for key export ([#154](https://github.com/libp2p/js-libp2p-crypto/issues/154)) ([d675670](https://github.com/libp2p/js-libp2p-crypto/commit/d675670))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* refactor to use async/await ([#131](https://github.com/libp2p/js-libp2p-crypto/issues/131)) ([ad71072](https://github.com/libp2p/js-libp2p-crypto/commit/ad71072))
|
||||||
|
|
||||||
|
|
||||||
|
### BREAKING CHANGES
|
||||||
|
|
||||||
|
* key export arguments are now swapped so that the optional format is last
|
||||||
|
* API refactored to use async/await
|
||||||
|
|
||||||
|
feat: WIP use async await
|
||||||
|
fix: passing tests
|
||||||
|
chore: update travis node.js versions
|
||||||
|
fix: skip ursa optional tests on windows
|
||||||
|
fix: benchmarks
|
||||||
|
docs: update docs
|
||||||
|
fix: remove broken and intested private key decrypt
|
||||||
|
chore: update deps
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<a name="0.16.1"></a>
|
||||||
|
## [0.16.1](https://github.com/libp2p/js-libp2p-crypto/compare/v0.16.0...v0.16.1) (2019-02-26)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<a name="0.16.0"></a>
|
||||||
|
# [0.16.0](https://github.com/libp2p/js-libp2p-crypto/compare/v0.15.0...v0.16.0) (2019-01-08)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* clean up, bundle size reduction ([8d8294d](https://github.com/libp2p/js-libp2p-crypto/commit/8d8294d))
|
||||||
|
|
||||||
|
|
||||||
|
### BREAKING CHANGES
|
||||||
|
|
||||||
|
* getRandomValues method exported from src/keys/rsa-browser.js and src/keys/rsa.js signature has changed from accepting an array to a number for random byte length
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<a name="0.15.0"></a>
|
||||||
|
# [0.15.0](https://github.com/libp2p/js-libp2p-crypto/compare/v0.14.1...v0.15.0) (2019-01-03)
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* nextTick instead of setImmediate, and fix sync in async ([#136](https://github.com/libp2p/js-libp2p-crypto/issues/136)) ([c54ea20](https://github.com/libp2p/js-libp2p-crypto/commit/c54ea20))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<a name="0.14.1"></a>
|
||||||
|
## [0.14.1](https://github.com/libp2p/js-libp2p-crypto/compare/v0.14.0...v0.14.1) (2018-11-05)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* dont setimmediate when its not needed ([9e57786](https://github.com/libp2p/js-libp2p-crypto/commit/9e57786))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<a name="0.14.0"></a>
|
||||||
|
# [0.14.0](https://github.com/libp2p/js-libp2p-crypto/compare/v0.13.0...v0.14.0) (2018-09-17)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* windows build ([c7e0409](https://github.com/libp2p/js-libp2p-crypto/commit/c7e0409))
|
||||||
|
* **lint:** use ~ for ursa-optional version ([e8cbf13](https://github.com/libp2p/js-libp2p-crypto/commit/e8cbf13))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* use ursa-optional for lightning fast key generation ([b05e77f](https://github.com/libp2p/js-libp2p-crypto/commit/b05e77f))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<a name="0.13.0"></a>
|
||||||
|
# [0.13.0](https://github.com/libp2p/js-libp2p-crypto/compare/v0.12.1...v0.13.0) (2018-04-05)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<a name="0.12.1"></a>
|
||||||
|
## [0.12.1](https://github.com/libp2p/js-libp2p-crypto/compare/v0.12.0...v0.12.1) (2018-02-12)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<a name="0.12.0"></a>
|
||||||
|
# [0.12.0](https://github.com/libp2p/js-libp2p-crypto/compare/v0.11.0...v0.12.0) (2018-01-27)
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* improve perf ([#117](https://github.com/libp2p/js-libp2p-crypto/issues/117)) ([cdcca5f](https://github.com/libp2p/js-libp2p-crypto/commit/cdcca5f))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<a name="0.11.0"></a>
|
||||||
|
# [0.11.0](https://github.com/libp2p/js-libp2p-crypto/compare/v0.10.4...v0.11.0) (2017-12-20)
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* key exchange with jsrsasign ([#115](https://github.com/libp2p/js-libp2p-crypto/issues/115)) ([b342128](https://github.com/libp2p/js-libp2p-crypto/commit/b342128))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<a name="0.10.4"></a>
|
||||||
|
## [0.10.4](https://github.com/libp2p/js-libp2p-crypto/compare/v0.10.3...v0.10.4) (2017-12-01)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* catch error when unmarshaling instead of crashing ([#113](https://github.com/libp2p/js-libp2p-crypto/issues/113)) ([7608fdd](https://github.com/libp2p/js-libp2p-crypto/commit/7608fdd))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<a name="0.10.3"></a>
|
||||||
|
## [0.10.3](https://github.com/libp2p/js-libp2p-crypto/compare/v0.10.2...v0.10.3) (2017-09-07)
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* switch protocol-buffers to protons ([#110](https://github.com/libp2p/js-libp2p-crypto/issues/110)) ([3a91ae2](https://github.com/libp2p/js-libp2p-crypto/commit/3a91ae2))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<a name="0.10.2"></a>
|
||||||
|
## [0.10.2](https://github.com/libp2p/js-libp2p-crypto/compare/v0.10.1...v0.10.2) (2017-09-06)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* use regular protocol-buffers until protobufjs is fixed ([#109](https://github.com/libp2p/js-libp2p-crypto/issues/109)) ([957fdd3](https://github.com/libp2p/js-libp2p-crypto/commit/957fdd3))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* **deps:** upgrade to aegir@12 and browserify-aes@1.0.8 ([83257bc](https://github.com/libp2p/js-libp2p-crypto/commit/83257bc))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<a name="0.10.1"></a>
|
||||||
|
## [0.10.1](https://github.com/libp2p/js-libp2p-crypto/compare/v0.10.0...v0.10.1) (2017-09-05)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* switch to protobufjs ([#107](https://github.com/libp2p/js-libp2p-crypto/issues/107)) ([dc2793f](https://github.com/libp2p/js-libp2p-crypto/commit/dc2793f))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<a name="0.10.0"></a>
|
||||||
|
# [0.10.0](https://github.com/libp2p/js-libp2p-crypto/compare/v0.9.4...v0.10.0) (2017-09-03)
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* p2p addrs situation ([#106](https://github.com/libp2p/js-libp2p-crypto/issues/106)) ([9e977c7](https://github.com/libp2p/js-libp2p-crypto/commit/9e977c7))
|
||||||
|
* skip nextTick in nodeify ([#103](https://github.com/libp2p/js-libp2p-crypto/issues/103)) ([f20267b](https://github.com/libp2p/js-libp2p-crypto/commit/f20267b))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<a name="0.9.4"></a>
|
||||||
|
## [0.9.4](https://github.com/libp2p/js-libp2p-crypto/compare/v0.9.3...v0.9.4) (2017-07-22)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* circular circular dep -> DI ([bc554d1](https://github.com/libp2p/js-libp2p-crypto/commit/bc554d1))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<a name="0.9.3"></a>
|
<a name="0.9.3"></a>
|
||||||
## [0.9.3](https://github.com/libp2p/js-libp2p-crypto/compare/v0.9.2...v0.9.3) (2017-07-22)
|
## [0.9.3](https://github.com/libp2p/js-libp2p-crypto/compare/v0.9.2...v0.9.3) (2017-07-22)
|
||||||
|
|
||||||
|
199
README.md
199
README.md
@@ -1,43 +1,49 @@
|
|||||||
# js-libp2p-crypto
|
# js-libp2p-crypto
|
||||||
|
|
||||||
[](http://ipn.io)
|
[](http://protocol.ai)
|
||||||
[](http://ipfs.io/)
|
[](http://libp2p.io/)
|
||||||
[](http://webchat.freenode.net/?channels=%23ipfs)
|
[](http://webchat.freenode.net/?channels=%23libp2p)
|
||||||
[](https://github.com/RichardLitt/standard-readme)
|
[](https://discuss.libp2p.io)
|
||||||
[](https://coveralls.io/github/libp2p/js-libp2p-crypto?branch=master)
|
[](https://codecov.io/gh/libp2p/js-libp2p-crypto)
|
||||||
[](https://travis-ci.org/libp2p/js-libp2p-crypto)
|
[](https://travis-ci.com/libp2p/js-libp2p-crypto)
|
||||||
[](https://circleci.com/gh/libp2p/js-libp2p-crypto)
|
|
||||||
[](https://david-dm.org/libp2p/js-libp2p-crypto)
|
[](https://david-dm.org/libp2p/js-libp2p-crypto)
|
||||||
[](https://github.com/feross/standard)
|
[](https://github.com/feross/standard)
|
||||||

|
|
||||||

|
|
||||||
|
|
||||||
> Crypto primitives for libp2p in JavaScript
|
> Crypto primitives for libp2p in JavaScript
|
||||||
|
|
||||||
This repo contains the JavaScript implementation of the crypto primitives needed for libp2p. This is based on this [go implementation](https://github.com/libp2p/go-libp2p-crypto).
|
This repo contains the JavaScript implementation of the crypto primitives needed for libp2p. This is based on this [go implementation](https://github.com/libp2p/go-libp2p-crypto).
|
||||||
|
|
||||||
|
## Lead Maintainer
|
||||||
|
|
||||||
|
[Friedel Ziegelmayer](https://github.com/dignifiedquire/)
|
||||||
|
|
||||||
## Table of Contents
|
## Table of Contents
|
||||||
|
|
||||||
- [Install](#install)
|
- [js-libp2p-crypto](#js-libp2p-crypto)
|
||||||
- [API](#api)
|
- [Lead Maintainer](#Lead-Maintainer)
|
||||||
- [`crypto.hmac`](#hmac)
|
- [Table of Contents](#Table-of-Contents)
|
||||||
- [`create(hash, secret, callback)`](#createhash-secret-callback)
|
- [Install](#Install)
|
||||||
- [`digest(data, callback)`](#digestdata-callback)
|
- [API](#API)
|
||||||
- [`crypto.aes`](#aes)
|
- [`crypto.aes`](#cryptoaes)
|
||||||
- [`create(key, iv, callback)`](#createkey-iv-callback)
|
- [`crypto.aes.create(key, iv)`](#cryptoaescreatekey-iv)
|
||||||
- [`encrypt(data, callback)`](#encryptdata-callback)
|
- [`decrypt(data)`](#decryptdata)
|
||||||
- [`decrypt(data, callback)`](#decryptdata-callback)
|
- [`encrypt(data)`](#encryptdata)
|
||||||
- [`keys`](#keys)
|
- [`crypto.hmac`](#cryptohmac)
|
||||||
- [`generateKeyPair(type, bits, callback)`](#generatekeypairtype-bits-callback)
|
- [`crypto.hmac.create(hash, secret)`](#cryptohmaccreatehash-secret)
|
||||||
- [`generateEphemeralKeyPair(curve, callback)`](#generateephemeralkeypaircurve-callback)
|
- [`digest(data)`](#digestdata)
|
||||||
- [`keyStretcher(cipherType, hashType, secret, callback)`](#keystretcherciphertype-hashtype-secret-callback)
|
- [`crypto.keys`](#cryptokeys)
|
||||||
- [`marshalPublicKey(key[, type], callback)`](#marshalpublickeykey-type-callback)
|
- [`crypto.keys.generateKeyPair(type, bits)`](#cryptokeysgenerateKeyPairtype-bits)
|
||||||
- [`unmarshalPublicKey(buf)`](#unmarshalpublickeybuf)
|
- [`crypto.keys.generateEphemeralKeyPair(curve)`](#cryptokeysgenerateEphemeralKeyPaircurve)
|
||||||
- [`marshalPrivateKey(key[, type])`](#marshalprivatekeykey-type)
|
- [`crypto.keys.keyStretcher(cipherType, hashType, secret)`](#cryptokeyskeyStretchercipherType-hashType-secret)
|
||||||
- [`unmarshalPrivateKey(buf, callback)`](#unmarshalprivatekeybuf-callback)
|
- [`crypto.keys.marshalPublicKey(key, [type])`](#cryptokeysmarshalPublicKeykey-type)
|
||||||
- [`webcrypto`](#webcrypto)
|
- [`crypto.keys.unmarshalPublicKey(buf)`](#cryptokeysunmarshalPublicKeybuf)
|
||||||
- [Contribute](#contribute)
|
- [`crypto.keys.marshalPrivateKey(key, [type])`](#cryptokeysmarshalPrivateKeykey-type)
|
||||||
- [License](#license)
|
- [`crypto.keys.unmarshalPrivateKey(buf)`](#cryptokeysunmarshalPrivateKeybuf)
|
||||||
|
- [`crypto.keys.import(pem, password)`](#cryptokeysimportpem-password)
|
||||||
|
- [`crypto.randomBytes(number)`](#cryptorandomBytesnumber)
|
||||||
|
- [`crypto.pbkdf2(password, salt, iterations, keySize, hash)`](#cryptopbkdf2password-salt-iterations-keySize-hash)
|
||||||
|
- [Contribute](#Contribute)
|
||||||
|
- [License](#License)
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|
||||||
@@ -53,75 +59,121 @@ Expoes an interface to AES encryption (formerly Rijndael), as defined in U.S. Fe
|
|||||||
|
|
||||||
This uses `CTR` mode.
|
This uses `CTR` mode.
|
||||||
|
|
||||||
#### `crypto.aes.create(key, iv, callback)`
|
#### `crypto.aes.create(key, iv)`
|
||||||
|
|
||||||
- `key: Buffer` The key, if length `16` then `AES 128` is used. For length `32`, `AES 256` is used.
|
- `key: Buffer` The key, if length `16` then `AES 128` is used. For length `32`, `AES 256` is used.
|
||||||
- `iv: Buffer` Must have length `16`.
|
- `iv: Buffer` Must have length `16`.
|
||||||
- `callback: Function`
|
|
||||||
|
|
||||||
##### `decrypt(data, callback)`
|
Returns `Promise<{decrypt<Function>, encrypt<Function>}>`
|
||||||
|
|
||||||
|
##### `decrypt(data)`
|
||||||
|
|
||||||
- `data: Buffer`
|
- `data: Buffer`
|
||||||
- `callback: Function`
|
|
||||||
|
|
||||||
##### `encrypt(data, callback)`
|
Returns `Promise<Buffer>`
|
||||||
|
|
||||||
|
##### `encrypt(data)`
|
||||||
|
|
||||||
- `data: Buffer`
|
- `data: Buffer`
|
||||||
- `callback: Function`
|
|
||||||
|
|
||||||
```
|
Returns `Promise<Buffer>`
|
||||||
TODO: Example of using aes
|
|
||||||
|
```js
|
||||||
|
const crypto = require('libp2p-crypto')
|
||||||
|
|
||||||
|
// Setting up Key and IV
|
||||||
|
|
||||||
|
// A 16 bytes array, 128 Bits, AES-128 is chosen
|
||||||
|
const key128 = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
|
||||||
|
|
||||||
|
// A 16 bytes array, 128 Bits,
|
||||||
|
const IV = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
|
||||||
|
|
||||||
|
async function main () {
|
||||||
|
const decryptedMessage = 'Hello, world!'
|
||||||
|
|
||||||
|
// Encrypting
|
||||||
|
const cipher = await crypto.aes.create(key128, IV)
|
||||||
|
const encryptedBuffer = await cipher.encrypt(Buffer.from(decryptedMessage))
|
||||||
|
console.log(encryptedBuffer)
|
||||||
|
// prints: <Buffer 42 f1 67 d9 2e 42 d0 32 9e b1 f8 3c>
|
||||||
|
|
||||||
|
// Decrypting
|
||||||
|
const decipher = await crypto.aes.create(key128, IV)
|
||||||
|
const decryptedBuffer = await cipher.decrypt(encryptedBuffer)
|
||||||
|
|
||||||
|
console.log(decryptedBuffer)
|
||||||
|
// prints: <Buffer 42 f1 67 d9 2e 42 d0 32 9e b1 f8 3c>
|
||||||
|
|
||||||
|
console.log(decryptedBuffer.toString('utf-8'))
|
||||||
|
// prints: Hello, world!
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
```
|
```
|
||||||
|
|
||||||
### `crypto.hmac`
|
### `crypto.hmac`
|
||||||
|
|
||||||
Exposes an interface to the Keyed-Hash Message Authentication Code (HMAC) as defined in U.S. Federal Information Processing Standards Publication 198. An HMAC is a cryptographic hash that uses a key to sign a message. The receiver verifies the hash by recomputing it using the same key.
|
Exposes an interface to the Keyed-Hash Message Authentication Code (HMAC) as defined in U.S. Federal Information Processing Standards Publication 198. An HMAC is a cryptographic hash that uses a key to sign a message. The receiver verifies the hash by recomputing it using the same key.
|
||||||
|
|
||||||
#### `crypto.hmac.create(hash, secret, callback)`
|
#### `crypto.hmac.create(hash, secret)`
|
||||||
|
|
||||||
- `hash: String`
|
- `hash: String`
|
||||||
- `secret: Buffer`
|
- `secret: Buffer`
|
||||||
- `callback: Function`
|
|
||||||
|
|
||||||
##### `digest(data, callback)`
|
Returns `Promise<{digest<Function>}>`
|
||||||
|
|
||||||
|
##### `digest(data)`
|
||||||
|
|
||||||
- `data: Buffer`
|
- `data: Buffer`
|
||||||
- `callback: Function`
|
|
||||||
|
Returns `Promise<Buffer>`
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
|
|
||||||
```
|
```js
|
||||||
TODO: Example of using hmac
|
const crypto = require('libp2p-crypto')
|
||||||
|
|
||||||
|
async function main () {
|
||||||
|
const hash = 'SHA1' // 'SHA256' || 'SHA512'
|
||||||
|
const hmac = await crypto.hmac.create(hash, Buffer.from('secret'))
|
||||||
|
const sig = await hmac.digest(Buffer.from('hello world'))
|
||||||
|
console.log(sig)
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
```
|
```
|
||||||
|
|
||||||
### `crypto.keys`
|
### `crypto.keys`
|
||||||
|
|
||||||
**Supported Key Types**
|
**Supported Key Types**
|
||||||
|
|
||||||
The [`generateKeyPair`](#generatekeypairtype-bits-callback), [`marshalPublicKey`](#marshalpublickeykey-type-callback), and [`marshalPrivateKey`](#marshalprivatekeykey-type) functions accept a string `type` argument.
|
The [`generateKeyPair`](#generatekeypairtype-bits), [`marshalPublicKey`](#marshalpublickeykey-type), and [`marshalPrivateKey`](#marshalprivatekeykey-type) functions accept a string `type` argument.
|
||||||
|
|
||||||
Currently the `'RSA'` and `'ed25519'` types are supported, although ed25519 keys support only signing and verification of messages. For encryption / decryption support, RSA keys should be used.
|
Currently the `'RSA'` and `'ed25519'` types are supported, although ed25519 keys support only signing and verification of messages. For encryption / decryption support, RSA keys should be used.
|
||||||
|
|
||||||
Installing the [libp2p-crypto-secp256k1](https://github.com/libp2p/js-libp2p-crypto-secp256k1) module adds support for the `'secp256k1'` type, which supports ECDSA signatures using the secp256k1 elliptic curve popularized by Bitcoin. This module is not installed by default, and should be explicitly depended on if your project requires secp256k1 support.
|
Installing the [libp2p-crypto-secp256k1](https://github.com/libp2p/js-libp2p-crypto-secp256k1) module adds support for the `'secp256k1'` type, which supports ECDSA signatures using the secp256k1 elliptic curve popularized by Bitcoin. This module is not installed by default, and should be explicitly depended on if your project requires secp256k1 support.
|
||||||
|
|
||||||
### `crypto.keys.generateKeyPair(type, bits, callback)`
|
### `crypto.keys.generateKeyPair(type, bits)`
|
||||||
|
|
||||||
- `type: String`, see [Supported Key Types](#supported-key-types) above.
|
- `type: String`, see [Supported Key Types](#supported-key-types) above.
|
||||||
- `bits: Number` Minimum of 1024
|
- `bits: Number` Minimum of 1024
|
||||||
- `callback: Function`
|
|
||||||
|
Returns `Promise<{privateKey<Buffer>, publicKey<Buffer>}>`
|
||||||
|
|
||||||
Generates a keypair of the given type and bitsize.
|
Generates a keypair of the given type and bitsize.
|
||||||
|
|
||||||
### `crypto.keys.generateEphemeralKeyPair(curve, callback)`
|
### `crypto.keys.generateEphemeralKeyPair(curve)`
|
||||||
|
|
||||||
- `curve: String`, one of `'P-256'`, `'P-384'`, `'P-521'` is currently supported
|
- `curve: String`, one of `'P-256'`, `'P-384'`, `'P-521'` is currently supported
|
||||||
- `callback: Function`
|
|
||||||
|
Returns `Promise`
|
||||||
|
|
||||||
Generates an ephemeral public key and returns a function that will compute the shared secret key.
|
Generates an ephemeral public key and returns a function that will compute the shared secret key.
|
||||||
|
|
||||||
Focuses only on ECDH now, but can be made more general in the future.
|
Focuses only on ECDH now, but can be made more general in the future.
|
||||||
|
|
||||||
Calls back with an object of the form
|
Resolves to an object of the form:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
{
|
{
|
||||||
@@ -130,16 +182,17 @@ Calls back with an object of the form
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### `crypto.keys.keyStretcher(cipherType, hashType, secret, callback)`
|
### `crypto.keys.keyStretcher(cipherType, hashType, secret)`
|
||||||
|
|
||||||
- `cipherType: String`, one of `'AES-128'`, `'AES-256'`, `'Blowfish'`
|
- `cipherType: String`, one of `'AES-128'`, `'AES-256'`, `'Blowfish'`
|
||||||
- `hashType: String`, one of `'SHA1'`, `SHA256`, `SHA512`
|
- `hashType: String`, one of `'SHA1'`, `SHA256`, `SHA512`
|
||||||
- `secret: Buffer`
|
- `secret: Buffer`
|
||||||
- `callback: Function`
|
|
||||||
|
Returns `Promise`
|
||||||
|
|
||||||
Generates a set of keys for each party by stretching the shared key.
|
Generates a set of keys for each party by stretching the shared key.
|
||||||
|
|
||||||
Calls back with an object of the form:
|
Resolves to an object of the form:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
{
|
{
|
||||||
@@ -156,10 +209,12 @@ Calls back with an object of the form:
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### `crypto.keys.marshalPublicKey(key[, type], callback)`
|
### `crypto.keys.marshalPublicKey(key, [type])`
|
||||||
|
|
||||||
- `key: keys.rsa.RsaPublicKey | keys.ed25519.Ed25519PublicKey | require('libp2p-crypto-secp256k1').Secp256k1PublicKey`
|
- `key: keys.rsa.RsaPublicKey | keys.ed25519.Ed25519PublicKey | require('libp2p-crypto-secp256k1').Secp256k1PublicKey`
|
||||||
- `type: String`, see [Supported Key Types](#supported-key-types) above.
|
- `type: String`, see [Supported Key Types](#supported-key-types) above. Defaults to 'rsa'.
|
||||||
|
|
||||||
|
Returns `Buffer`
|
||||||
|
|
||||||
Converts a public key object into a protobuf serialized public key.
|
Converts a public key object into a protobuf serialized public key.
|
||||||
|
|
||||||
@@ -167,28 +222,54 @@ Converts a public key object into a protobuf serialized public key.
|
|||||||
|
|
||||||
- `buf: Buffer`
|
- `buf: Buffer`
|
||||||
|
|
||||||
Converts a protobuf serialized public key into its representative object.
|
Returns `RsaPublicKey|Ed25519PublicKey|Secp256k1PublicKey`
|
||||||
|
|
||||||
### `crypto.keys.marshalPrivateKey(key[, type])`
|
Converts a protobuf serialized public key into its representative object.
|
||||||
|
|
||||||
|
### `crypto.keys.marshalPrivateKey(key, [type])`
|
||||||
|
|
||||||
- `key: keys.rsa.RsaPrivateKey | keys.ed25519.Ed25519PrivateKey | require('libp2p-crypto-secp256k1').Secp256k1PrivateKey`
|
- `key: keys.rsa.RsaPrivateKey | keys.ed25519.Ed25519PrivateKey | require('libp2p-crypto-secp256k1').Secp256k1PrivateKey`
|
||||||
- `type: String`, see [Supported Key Types](#supported-key-types) above.
|
- `type: String`, see [Supported Key Types](#supported-key-types) above.
|
||||||
|
|
||||||
|
Returns `Buffer`
|
||||||
|
|
||||||
Converts a private key object into a protobuf serialized private key.
|
Converts a private key object into a protobuf serialized private key.
|
||||||
|
|
||||||
### `crypto.keys.unmarshalPrivateKey(buf, callback)`
|
### `crypto.keys.unmarshalPrivateKey(buf)`
|
||||||
|
|
||||||
- `buf: Buffer`
|
- `buf: Buffer`
|
||||||
- `callback: Function`
|
|
||||||
|
Returns `Promise<RsaPrivateKey|Ed25519PrivateKey|Secp256k1PrivateKey>`
|
||||||
|
|
||||||
Converts a protobuf serialized private key into its representative object.
|
Converts a protobuf serialized private key into its representative object.
|
||||||
|
|
||||||
|
### `crypto.keys.import(pem, password)`
|
||||||
|
|
||||||
|
- `pem: string`
|
||||||
|
- `password: string`
|
||||||
|
|
||||||
|
Returns `Promise<RsaPrivateKey>`
|
||||||
|
|
||||||
|
Converts a PEM password protected private key into its representative object.
|
||||||
|
|
||||||
### `crypto.randomBytes(number)`
|
### `crypto.randomBytes(number)`
|
||||||
|
|
||||||
- `number: Number`
|
- `number: Number`
|
||||||
|
|
||||||
|
Returns `Buffer`
|
||||||
|
|
||||||
Generates a Buffer with length `number` populated by random bytes.
|
Generates a Buffer with length `number` populated by random bytes.
|
||||||
|
|
||||||
|
### `crypto.pbkdf2(password, salt, iterations, keySize, hash)`
|
||||||
|
|
||||||
|
- `password: String`
|
||||||
|
- `salt: String`
|
||||||
|
- `iterations: Number`
|
||||||
|
- `keySize: Number` in bytes
|
||||||
|
- `hash: String` the hashing algorithm ('sha1', 'sha2-512', ...)
|
||||||
|
|
||||||
|
Computes the Password Based Key Derivation Function 2; returning a new password.
|
||||||
|
|
||||||
## Contribute
|
## Contribute
|
||||||
|
|
||||||
Feel free to join in. All welcome. Open an [issue](https://github.com/libp2p/js-libp2p-crypto/issues)!
|
Feel free to join in. All welcome. Open an [issue](https://github.com/libp2p/js-libp2p-crypto/issues)!
|
||||||
@@ -199,4 +280,4 @@ This repository falls under the IPFS [Code of Conduct](https://github.com/ipfs/c
|
|||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
[MIT](LICENSE)
|
[MIT](./LICENSE)
|
||||||
|
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const Benchmark = require('benchmark')
|
const Benchmark = require('benchmark')
|
||||||
@@ -9,18 +10,14 @@ const secrets = []
|
|||||||
const curves = ['P-256', 'P-384', 'P-521']
|
const curves = ['P-256', 'P-384', 'P-521']
|
||||||
|
|
||||||
curves.forEach((curve) => {
|
curves.forEach((curve) => {
|
||||||
suite.add(`ephemeral key with secrect ${curve}`, (d) => {
|
suite.add(`ephemeral key with secrect ${curve}`, async (d) => {
|
||||||
crypto.keys.generateEphemeralKeyPair('P-256', (err, res) => {
|
const res = await crypto.keys.generateEphemeralKeyPair('P-256')
|
||||||
if (err) { throw err }
|
const secret = await res.genSharedKey(res.key)
|
||||||
res.genSharedKey(res.key, (err, secret) => {
|
secrets.push(secret)
|
||||||
if (err) { throw err }
|
d.resolve()
|
||||||
secrets.push(secret)
|
|
||||||
|
|
||||||
d.resolve()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}, { defer: true })
|
}, { defer: true })
|
||||||
})
|
})
|
||||||
|
|
||||||
suite.on('cycle', (event) => console.log(String(event.target)))
|
suite
|
||||||
.run({async: true})
|
.on('cycle', (event) => console.log(String(event.target)))
|
||||||
|
.run({ async: true })
|
||||||
|
@@ -1,7 +1,7 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const Benchmark = require('benchmark')
|
const Benchmark = require('benchmark')
|
||||||
const async = require('async')
|
|
||||||
|
|
||||||
const crypto = require('../src')
|
const crypto = require('../src')
|
||||||
|
|
||||||
@@ -12,27 +12,23 @@ const keys = []
|
|||||||
const ciphers = ['AES-128', 'AES-256', 'Blowfish']
|
const ciphers = ['AES-128', 'AES-256', 'Blowfish']
|
||||||
const hashes = ['SHA1', 'SHA256', 'SHA512']
|
const hashes = ['SHA1', 'SHA256', 'SHA512']
|
||||||
|
|
||||||
async.waterfall([
|
;(async () => {
|
||||||
(cb) => crypto.keys.generateEphemeralKeyPair('P-256', cb),
|
const res = await crypto.keys.generateEphemeralKeyPair('P-256')
|
||||||
(res, cb) => res.genSharedKey(res.key, cb)
|
const secret = await res.genSharedKey(res.key)
|
||||||
], (err, secret) => {
|
|
||||||
if (err) { throw err }
|
|
||||||
|
|
||||||
ciphers.forEach((cipher) => hashes.forEach((hash) => {
|
ciphers.forEach((cipher) => hashes.forEach((hash) => {
|
||||||
setup(cipher, hash, secret)
|
setup(cipher, hash, secret)
|
||||||
}))
|
}))
|
||||||
|
|
||||||
suite.on('cycle', (event) => console.log(String(event.target)))
|
suite
|
||||||
.run({async: true})
|
.on('cycle', (event) => console.log(String(event.target)))
|
||||||
})
|
.run({ async: true })
|
||||||
|
})()
|
||||||
|
|
||||||
function setup (cipher, hash, secret) {
|
function setup (cipher, hash, secret) {
|
||||||
suite.add(`keyStretcher ${cipher} ${hash}`, (d) => {
|
suite.add(`keyStretcher ${cipher} ${hash}`, async (d) => {
|
||||||
crypto.keys.keyStretcher(cipher, hash, secret, (err, k) => {
|
const k = await crypto.keys.keyStretcher(cipher, hash, secret)
|
||||||
if (err) { throw err }
|
keys.push(k)
|
||||||
|
d.resolve()
|
||||||
keys.push(k)
|
|
||||||
d.resolve()
|
|
||||||
})
|
|
||||||
}, { defer: true })
|
}, { defer: true })
|
||||||
}
|
}
|
||||||
|
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const Benchmark = require('benchmark')
|
const Benchmark = require('benchmark')
|
||||||
@@ -9,33 +10,28 @@ const keys = []
|
|||||||
const bits = [1024, 2048, 4096]
|
const bits = [1024, 2048, 4096]
|
||||||
|
|
||||||
bits.forEach((bit) => {
|
bits.forEach((bit) => {
|
||||||
suite.add(`generateKeyPair ${bit}bits`, (d) => {
|
suite.add(`generateKeyPair ${bit}bits`, async (d) => {
|
||||||
crypto.keys.generateKeyPair('RSA', bit, (err, key) => {
|
const key = await crypto.keys.generateKeyPair('RSA', bit)
|
||||||
if (err) { throw err }
|
keys.push(key)
|
||||||
keys.push(key)
|
d.resolve()
|
||||||
d.resolve()
|
|
||||||
})
|
|
||||||
}, {
|
}, {
|
||||||
defer: true
|
defer: true
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
suite.add('sign and verify', (d) => {
|
suite.add('sign and verify', async (d) => {
|
||||||
const key = keys[0]
|
const key = keys[0]
|
||||||
const text = key.genSecret()
|
const text = key.genSecret()
|
||||||
|
|
||||||
key.sign(text, (err, sig) => {
|
const sig = await key.sign(text)
|
||||||
if (err) { throw err }
|
const res = await key.public.verify(text, sig)
|
||||||
|
|
||||||
key.public.verify(text, sig, (err, res) => {
|
if (res !== true) { throw new Error('failed to verify') }
|
||||||
if (err) { throw err }
|
d.resolve()
|
||||||
if (res !== true) { throw new Error('failed to verify') }
|
|
||||||
d.resolve()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}, {
|
}, {
|
||||||
defer: true
|
defer: true
|
||||||
})
|
})
|
||||||
|
|
||||||
suite.on('cycle', (event) => console.log(String(event.target)))
|
suite
|
||||||
.run({async: true})
|
.on('cycle', (event) => console.log(String(event.target)))
|
||||||
|
.run({ async: true })
|
||||||
|
14
circle.yml
14
circle.yml
@@ -1,14 +0,0 @@
|
|||||||
machine:
|
|
||||||
node:
|
|
||||||
version: stable
|
|
||||||
|
|
||||||
dependencies:
|
|
||||||
pre:
|
|
||||||
- google-chrome --version
|
|
||||||
- curl -L -o google-chrome.deb https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
|
|
||||||
- sudo dpkg -i google-chrome.deb || true
|
|
||||||
- sudo apt-get update
|
|
||||||
- sudo apt-get install -f
|
|
||||||
- sudo apt-get install --only-upgrade lsb-base
|
|
||||||
- sudo dpkg -i google-chrome.deb
|
|
||||||
- google-chrome --version
|
|
83
package.json
83
package.json
@@ -1,25 +1,31 @@
|
|||||||
{
|
{
|
||||||
"name": "libp2p-crypto",
|
"name": "libp2p-crypto",
|
||||||
"version": "0.9.3",
|
"version": "0.17.0",
|
||||||
"description": "Crypto primitives for libp2p",
|
"description": "Crypto primitives for libp2p",
|
||||||
"main": "src/index.js",
|
"main": "src/index.js",
|
||||||
|
"leadMaintainer": "Friedel Ziegelmayer <dignifiedquire@gmail.com>",
|
||||||
"browser": {
|
"browser": {
|
||||||
"./src/hmac/index.js": "./src/hmac/index-browser.js",
|
"./src/hmac/index.js": "./src/hmac/index-browser.js",
|
||||||
"./src/keys/ecdh.js": "./src/keys/ecdh-browser.js",
|
"./src/keys/ecdh.js": "./src/keys/ecdh-browser.js",
|
||||||
"./src/aes/ciphers.js": "./src/aes/ciphers-browser.js",
|
"./src/aes/ciphers.js": "./src/aes/ciphers-browser.js",
|
||||||
"./src/keys/rsa.js": "./src/keys/rsa-browser.js"
|
"./src/keys/rsa.js": "./src/keys/rsa-browser.js"
|
||||||
},
|
},
|
||||||
|
"files": [
|
||||||
|
"src",
|
||||||
|
"dist"
|
||||||
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"lint": "aegir-lint",
|
"lint": "aegir lint",
|
||||||
"build": "aegir-build",
|
"build": "aegir build",
|
||||||
"test": "aegir-test",
|
"build-proto": "pbjs --wrap commonjs --target static-module src/keys/keys.proto > src/keys/keys.proto.js",
|
||||||
"test:node": "aegir-test --env node",
|
"test": "aegir test",
|
||||||
"test:browser": "aegir-test --env browser",
|
"test:node": "aegir test -t node",
|
||||||
"release": "aegir-release",
|
"test:browser": "aegir test -t browser -t webworker",
|
||||||
"release-minor": "aegir-release --type minor",
|
"release": "aegir release",
|
||||||
"release-major": "aegir-release --type major",
|
"release-minor": "aegir release --type minor",
|
||||||
"coverage": "aegir-coverage",
|
"release-major": "aegir release --type major",
|
||||||
"coverage-publish": "aegir-coverage publish"
|
"coverage": "aegir coverage --ignore src/keys/keys.proto.js",
|
||||||
|
"size": "bundlesize -f dist/index.min.js -s 139kB"
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"IPFS",
|
"IPFS",
|
||||||
@@ -27,37 +33,36 @@
|
|||||||
"crypto",
|
"crypto",
|
||||||
"rsa"
|
"rsa"
|
||||||
],
|
],
|
||||||
"author": "Friedel Ziegelmayer <dignifiedquire@gmail.com>",
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"asn1.js": "^4.9.1",
|
"asmcrypto.js": "^2.3.2",
|
||||||
"async": "^2.5.0",
|
"asn1.js": "^5.0.1",
|
||||||
"browserify-aes": "^1.0.6",
|
"bn.js": "^5.0.0",
|
||||||
|
"browserify-aes": "^1.2.0",
|
||||||
|
"bs58": "^4.0.1",
|
||||||
|
"iso-random-stream": "^1.1.0",
|
||||||
"keypair": "^1.0.1",
|
"keypair": "^1.0.1",
|
||||||
"libp2p-crypto-secp256k1": "~0.2.1",
|
"libp2p-crypto-secp256k1": "~0.4.0",
|
||||||
"nodeify": "^1.0.1",
|
"multihashing-async": "~0.7.0",
|
||||||
"pem-jwk": "^1.5.1",
|
"node-forge": "~0.8.5",
|
||||||
"protocol-buffers": "^3.2.1",
|
"pem-jwk": "^2.0.0",
|
||||||
|
"protons": "^1.0.1",
|
||||||
"rsa-pem-to-jwk": "^1.1.3",
|
"rsa-pem-to-jwk": "^1.1.3",
|
||||||
"safe-buffer": "^5.1.1",
|
"tweetnacl": "^1.0.1",
|
||||||
"tweetnacl": "^1.0.0",
|
"ursa-optional": "~0.10.0"
|
||||||
"webcrypto-shim": "github:dignifiedquire/webcrypto-shim#master",
|
|
||||||
"multihashing-async": "~0.4.6"
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"aegir": "^11.0.2",
|
"aegir": "^19.0.5",
|
||||||
"benchmark": "^2.1.4",
|
"benchmark": "^2.1.4",
|
||||||
"chai": "^4.1.0",
|
"bundlesize": "~0.18.0",
|
||||||
|
"chai": "^4.2.0",
|
||||||
|
"chai-string": "^1.5.0",
|
||||||
"dirty-chai": "^2.0.1",
|
"dirty-chai": "^2.0.1",
|
||||||
"pre-commit": "^1.2.2"
|
"sinon": "^7.3.2"
|
||||||
},
|
},
|
||||||
"pre-commit": [
|
|
||||||
"lint",
|
|
||||||
"test"
|
|
||||||
],
|
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=4.0.0",
|
"node": ">=10.0.0",
|
||||||
"npm": ">=3.0.0"
|
"npm": ">=6.0.0"
|
||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@@ -68,15 +73,27 @@
|
|||||||
},
|
},
|
||||||
"homepage": "https://github.com/libp2p/js-libp2p-crypto",
|
"homepage": "https://github.com/libp2p/js-libp2p-crypto",
|
||||||
"contributors": [
|
"contributors": [
|
||||||
|
"Alan Shaw <alan.shaw@protocol.ai>",
|
||||||
|
"Alberto Elias <hi@albertoelias.me>",
|
||||||
|
"Arve Knudsen <arve.knudsen@gmail.com>",
|
||||||
"David Dias <daviddias.p@gmail.com>",
|
"David Dias <daviddias.p@gmail.com>",
|
||||||
"Dmitriy Ryajov <dryajov@gmail.com>",
|
"Dmitriy Ryajov <dryajov@gmail.com>",
|
||||||
"Friedel Ziegelmayer <dignifiedquire@gmail.com>",
|
"Friedel Ziegelmayer <dignifiedquire@gmail.com>",
|
||||||
"Greenkeeper <support@greenkeeper.io>",
|
"Greenkeeper <support@greenkeeper.io>",
|
||||||
|
"Hugo Dias <hugomrdias@gmail.com>",
|
||||||
"Jack Kleeman <jackkleeman@gmail.com>",
|
"Jack Kleeman <jackkleeman@gmail.com>",
|
||||||
|
"Jacob Heun <jacobheun@gmail.com>",
|
||||||
|
"Joao Santos <jrmsantos15@gmail.com>",
|
||||||
|
"Maciej Krüger <mkg20001@gmail.com>",
|
||||||
"Richard Littauer <richard.littauer@gmail.com>",
|
"Richard Littauer <richard.littauer@gmail.com>",
|
||||||
|
"Richard Schneider <makaretu@gmail.com>",
|
||||||
"Tom Swindell <t.swindell@rubyx.co.uk>",
|
"Tom Swindell <t.swindell@rubyx.co.uk>",
|
||||||
|
"Vasco Santos <vasco.santos@ua.pt>",
|
||||||
|
"Victor Bjelkholm <victorbjelkholm@gmail.com>",
|
||||||
"Yusef Napora <yusef@napora.org>",
|
"Yusef Napora <yusef@napora.org>",
|
||||||
|
"dignifiedquire <dignifiedquire@users.noreply.github.com>",
|
||||||
|
"dirkmc <dirkmdev@gmail.com>",
|
||||||
"greenkeeper[bot] <greenkeeper[bot]@users.noreply.github.com>",
|
"greenkeeper[bot] <greenkeeper[bot]@users.noreply.github.com>",
|
||||||
"nikuda <nikuda@gmail.com>"
|
"nikuda <nikuda@gmail.com>"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
34
src/aes/index-browser.js
Normal file
34
src/aes/index-browser.js
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
'use strict'
|
||||||
|
|
||||||
|
const asm = require('asmcrypto.js')
|
||||||
|
|
||||||
|
exports.create = async function (key, iv) { // eslint-disable-line require-await
|
||||||
|
if (key.length !== 16 && key.length !== 32) {
|
||||||
|
throw new Error('Invalid key length')
|
||||||
|
}
|
||||||
|
|
||||||
|
const enc = new asm.AES_CTR.Encrypt({
|
||||||
|
key: key,
|
||||||
|
nonce: iv
|
||||||
|
})
|
||||||
|
const dec = new asm.AES_CTR.Decrypt({
|
||||||
|
key: key,
|
||||||
|
nonce: iv
|
||||||
|
})
|
||||||
|
|
||||||
|
const res = {
|
||||||
|
async encrypt (data) { // eslint-disable-line require-await
|
||||||
|
return Buffer.from(
|
||||||
|
enc.process(data).result
|
||||||
|
)
|
||||||
|
},
|
||||||
|
|
||||||
|
async decrypt (data) { // eslint-disable-line require-await
|
||||||
|
return Buffer.from(
|
||||||
|
dec.process(data).result
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return res
|
||||||
|
}
|
@@ -7,24 +7,24 @@ const CIPHER_MODES = {
|
|||||||
32: 'aes-256-ctr'
|
32: 'aes-256-ctr'
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.create = function (key, iv, callback) {
|
exports.create = async function (key, iv) { // eslint-disable-line require-await
|
||||||
const mode = CIPHER_MODES[key.length]
|
const mode = CIPHER_MODES[key.length]
|
||||||
if (!mode) {
|
if (!mode) {
|
||||||
return callback(new Error('Invalid key length'))
|
throw new Error('Invalid key length')
|
||||||
}
|
}
|
||||||
|
|
||||||
const cipher = ciphers.createCipheriv(mode, key, iv)
|
const cipher = ciphers.createCipheriv(mode, key, iv)
|
||||||
const decipher = ciphers.createDecipheriv(mode, key, iv)
|
const decipher = ciphers.createDecipheriv(mode, key, iv)
|
||||||
|
|
||||||
const res = {
|
const res = {
|
||||||
encrypt (data, cb) {
|
async encrypt (data) { // eslint-disable-line require-await
|
||||||
cb(null, cipher.update(data))
|
return cipher.update(data)
|
||||||
},
|
},
|
||||||
|
|
||||||
decrypt (data, cb) {
|
async decrypt (data) { // eslint-disable-line require-await
|
||||||
cb(null, decipher.update(data))
|
return decipher.update(data)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
callback(null, res)
|
return res
|
||||||
}
|
}
|
||||||
|
@@ -1,9 +1,6 @@
|
|||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const nodeify = require('nodeify')
|
const webcrypto = require('../webcrypto.js')
|
||||||
const Buffer = require('safe-buffer').Buffer
|
|
||||||
|
|
||||||
const crypto = require('../webcrypto.js')()
|
|
||||||
const lengths = require('./lengths')
|
const lengths = require('./lengths')
|
||||||
|
|
||||||
const hashTypes = {
|
const hashTypes = {
|
||||||
@@ -12,25 +9,28 @@ const hashTypes = {
|
|||||||
SHA512: 'SHA-512'
|
SHA512: 'SHA-512'
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.create = function (hashType, secret, callback) {
|
const sign = async (key, data) => {
|
||||||
|
return Buffer.from(await webcrypto.subtle.sign({ name: 'HMAC' }, key, data))
|
||||||
|
}
|
||||||
|
|
||||||
|
exports.create = async function (hashType, secret) {
|
||||||
const hash = hashTypes[hashType]
|
const hash = hashTypes[hashType]
|
||||||
|
|
||||||
nodeify(crypto.subtle.importKey(
|
const key = await webcrypto.subtle.importKey(
|
||||||
'raw',
|
'raw',
|
||||||
secret,
|
secret,
|
||||||
{
|
{
|
||||||
name: 'HMAC',
|
name: 'HMAC',
|
||||||
hash: {name: hash}
|
hash: { name: hash }
|
||||||
},
|
},
|
||||||
false,
|
false,
|
||||||
['sign']
|
['sign']
|
||||||
).then((key) => {
|
)
|
||||||
return {
|
|
||||||
digest (data, cb) {
|
return {
|
||||||
nodeify(crypto.subtle.sign({name: 'HMAC'}, key, data)
|
async digest (data) { // eslint-disable-line require-await
|
||||||
.then((raw) => Buffer.from(raw)), cb)
|
return sign(key, data)
|
||||||
},
|
},
|
||||||
length: lengths[hashType]
|
length: lengths[hashType]
|
||||||
}
|
}
|
||||||
}), callback)
|
|
||||||
}
|
}
|
||||||
|
@@ -3,19 +3,15 @@
|
|||||||
const crypto = require('crypto')
|
const crypto = require('crypto')
|
||||||
const lengths = require('./lengths')
|
const lengths = require('./lengths')
|
||||||
|
|
||||||
exports.create = function (hash, secret, callback) {
|
exports.create = async function (hash, secret) { // eslint-disable-line require-await
|
||||||
const res = {
|
const res = {
|
||||||
digest (data, cb) {
|
async digest (data) { // eslint-disable-line require-await
|
||||||
const hmac = crypto.createHmac(hash.toLowerCase(), secret)
|
const hmac = crypto.createHmac(hash.toLowerCase(), secret)
|
||||||
|
|
||||||
hmac.update(data)
|
hmac.update(data)
|
||||||
|
return hmac.digest()
|
||||||
setImmediate(() => {
|
|
||||||
cb(null, hmac.digest())
|
|
||||||
})
|
|
||||||
},
|
},
|
||||||
length: lengths[hash]
|
length: lengths[hash]
|
||||||
}
|
}
|
||||||
|
|
||||||
callback(null, res)
|
return res
|
||||||
}
|
}
|
||||||
|
13
src/index.js
13
src/index.js
@@ -3,18 +3,9 @@
|
|||||||
const hmac = require('./hmac')
|
const hmac = require('./hmac')
|
||||||
const aes = require('./aes')
|
const aes = require('./aes')
|
||||||
const keys = require('./keys')
|
const keys = require('./keys')
|
||||||
const rsa = require('./keys/rsa')
|
|
||||||
|
|
||||||
exports = module.exports
|
|
||||||
|
|
||||||
exports.aes = aes
|
exports.aes = aes
|
||||||
exports.hmac = hmac
|
exports.hmac = hmac
|
||||||
exports.keys = keys
|
exports.keys = keys
|
||||||
|
exports.randomBytes = require('./random-bytes')
|
||||||
exports.randomBytes = (number) => {
|
exports.pbkdf2 = require('./pbkdf2')
|
||||||
if (!number || typeof number !== 'number') {
|
|
||||||
throw new Error('first argument must be a Number bigger than 0')
|
|
||||||
}
|
|
||||||
|
|
||||||
return rsa.getRandomValues(new Uint8Array(number))
|
|
||||||
}
|
|
||||||
|
@@ -1,13 +1,8 @@
|
|||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const webcrypto = require('../webcrypto.js')()
|
const webcrypto = require('../webcrypto.js')
|
||||||
const nodeify = require('nodeify')
|
|
||||||
const BN = require('asn1.js').bignum
|
const BN = require('asn1.js').bignum
|
||||||
const Buffer = require('safe-buffer').Buffer
|
const { toBase64, toBn } = require('../util')
|
||||||
|
|
||||||
const util = require('../util')
|
|
||||||
const toBase64 = util.toBase64
|
|
||||||
const toBn = util.toBn
|
|
||||||
|
|
||||||
const bits = {
|
const bits = {
|
||||||
'P-256': 256,
|
'P-256': 256,
|
||||||
@@ -15,72 +10,66 @@ const bits = {
|
|||||||
'P-521': 521
|
'P-521': 521
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.generateEphmeralKeyPair = function (curve, callback) {
|
exports.generateEphmeralKeyPair = async function (curve) {
|
||||||
nodeify(webcrypto.subtle.generateKey(
|
const pair = await webcrypto.subtle.generateKey(
|
||||||
{
|
{
|
||||||
name: 'ECDH',
|
name: 'ECDH',
|
||||||
namedCurve: curve
|
namedCurve: curve
|
||||||
},
|
},
|
||||||
true,
|
true,
|
||||||
['deriveBits']
|
['deriveBits']
|
||||||
).then((pair) => {
|
)
|
||||||
// forcePrivate is used for testing only
|
|
||||||
const genSharedKey = (theirPub, forcePrivate, cb) => {
|
|
||||||
if (typeof forcePrivate === 'function') {
|
|
||||||
cb = forcePrivate
|
|
||||||
forcePrivate = undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
let privateKey
|
// forcePrivate is used for testing only
|
||||||
|
const genSharedKey = async (theirPub, forcePrivate) => {
|
||||||
|
let privateKey
|
||||||
|
|
||||||
if (forcePrivate) {
|
if (forcePrivate) {
|
||||||
privateKey = webcrypto.subtle.importKey(
|
privateKey = await webcrypto.subtle.importKey(
|
||||||
'jwk',
|
'jwk',
|
||||||
unmarshalPrivateKey(curve, forcePrivate),
|
unmarshalPrivateKey(curve, forcePrivate),
|
||||||
{
|
|
||||||
name: 'ECDH',
|
|
||||||
namedCurve: curve
|
|
||||||
},
|
|
||||||
false,
|
|
||||||
['deriveBits']
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
privateKey = Promise.resolve(pair.privateKey)
|
|
||||||
}
|
|
||||||
|
|
||||||
const keys = Promise.all([
|
|
||||||
webcrypto.subtle.importKey(
|
|
||||||
'jwk',
|
|
||||||
unmarshalPublicKey(curve, theirPub),
|
|
||||||
{
|
|
||||||
name: 'ECDH',
|
|
||||||
namedCurve: curve
|
|
||||||
},
|
|
||||||
false,
|
|
||||||
[]
|
|
||||||
),
|
|
||||||
privateKey
|
|
||||||
])
|
|
||||||
|
|
||||||
nodeify(keys.then((keys) => webcrypto.subtle.deriveBits(
|
|
||||||
{
|
{
|
||||||
name: 'ECDH',
|
name: 'ECDH',
|
||||||
namedCurve: curve,
|
namedCurve: curve
|
||||||
public: keys[0]
|
|
||||||
},
|
},
|
||||||
keys[1],
|
false,
|
||||||
bits[curve]
|
['deriveBits']
|
||||||
)).then((bits) => Buffer.from(bits)), cb)
|
)
|
||||||
|
} else {
|
||||||
|
privateKey = pair.privateKey
|
||||||
}
|
}
|
||||||
|
|
||||||
return webcrypto.subtle.exportKey('jwk', pair.publicKey)
|
const keys = [
|
||||||
.then((publicKey) => {
|
await webcrypto.subtle.importKey(
|
||||||
return {
|
'jwk',
|
||||||
key: marshalPublicKey(publicKey),
|
unmarshalPublicKey(curve, theirPub),
|
||||||
genSharedKey
|
{
|
||||||
}
|
name: 'ECDH',
|
||||||
})
|
namedCurve: curve
|
||||||
}), callback)
|
},
|
||||||
|
false,
|
||||||
|
[]
|
||||||
|
),
|
||||||
|
privateKey
|
||||||
|
]
|
||||||
|
|
||||||
|
return Buffer.from(await webcrypto.subtle.deriveBits(
|
||||||
|
{
|
||||||
|
name: 'ECDH',
|
||||||
|
namedCurve: curve,
|
||||||
|
public: keys[0]
|
||||||
|
},
|
||||||
|
keys[1],
|
||||||
|
bits[curve]
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
const publicKey = await webcrypto.subtle.exportKey('jwk', pair.publicKey)
|
||||||
|
|
||||||
|
return {
|
||||||
|
key: marshalPublicKey(publicKey),
|
||||||
|
genSharedKey
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const curveLengths = {
|
const curveLengths = {
|
||||||
|
@@ -1,7 +1,6 @@
|
|||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const crypto = require('crypto')
|
const crypto = require('crypto')
|
||||||
const setImmediate = require('async/setImmediate')
|
|
||||||
|
|
||||||
const curves = {
|
const curves = {
|
||||||
'P-256': 'prime256v1',
|
'P-256': 'prime256v1',
|
||||||
@@ -9,33 +8,21 @@ const curves = {
|
|||||||
'P-521': 'secp521r1'
|
'P-521': 'secp521r1'
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.generateEphmeralKeyPair = function (curve, callback) {
|
exports.generateEphmeralKeyPair = async function (curve) { // eslint-disable-line require-await
|
||||||
if (!curves[curve]) {
|
if (!curves[curve]) {
|
||||||
return callback(new Error(`Unkown curve: ${curve}`))
|
throw new Error(`Unkown curve: ${curve}`)
|
||||||
}
|
}
|
||||||
const ecdh = crypto.createECDH(curves[curve])
|
const ecdh = crypto.createECDH(curves[curve])
|
||||||
ecdh.generateKeys()
|
ecdh.generateKeys()
|
||||||
|
|
||||||
setImmediate(() => callback(null, {
|
return {
|
||||||
key: ecdh.getPublicKey(),
|
key: ecdh.getPublicKey(),
|
||||||
genSharedKey (theirPub, forcePrivate, cb) {
|
async genSharedKey (theirPub, forcePrivate) { // eslint-disable-line require-await
|
||||||
if (typeof forcePrivate === 'function') {
|
|
||||||
cb = forcePrivate
|
|
||||||
forcePrivate = null
|
|
||||||
}
|
|
||||||
|
|
||||||
if (forcePrivate) {
|
if (forcePrivate) {
|
||||||
ecdh.setPrivateKey(forcePrivate.private)
|
ecdh.setPrivateKey(forcePrivate.private)
|
||||||
}
|
}
|
||||||
|
|
||||||
let secret
|
return ecdh.computeSecret(theirPub)
|
||||||
try {
|
|
||||||
secret = ecdh.computeSecret(theirPub)
|
|
||||||
} catch (err) {
|
|
||||||
return cb(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
setImmediate(() => cb(null, secret))
|
|
||||||
}
|
}
|
||||||
}))
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,8 +1,8 @@
|
|||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const multihashing = require('multihashing-async')
|
const multihashing = require('multihashing-async')
|
||||||
const protobuf = require('protocol-buffers')
|
const protobuf = require('protons')
|
||||||
const Buffer = require('safe-buffer').Buffer
|
const bs58 = require('bs58')
|
||||||
|
|
||||||
const crypto = require('./ed25519')
|
const crypto = require('./ed25519')
|
||||||
const pbm = protobuf(require('./keys.proto'))
|
const pbm = protobuf(require('./keys.proto'))
|
||||||
@@ -12,9 +12,8 @@ class Ed25519PublicKey {
|
|||||||
this._key = ensureKey(key, crypto.publicKeyLength)
|
this._key = ensureKey(key, crypto.publicKeyLength)
|
||||||
}
|
}
|
||||||
|
|
||||||
verify (data, sig, callback) {
|
async verify (data, sig) { // eslint-disable-line require-await
|
||||||
ensure(callback)
|
return crypto.hashAndVerify(this._key, sig, data)
|
||||||
crypto.hashAndVerify(this._key, sig, data, callback)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
marshal () {
|
marshal () {
|
||||||
@@ -32,9 +31,8 @@ class Ed25519PublicKey {
|
|||||||
return this.bytes.equals(key.bytes)
|
return this.bytes.equals(key.bytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
hash (callback) {
|
async hash () { // eslint-disable-line require-await
|
||||||
ensure(callback)
|
return multihashing(this.bytes, 'sha2-256')
|
||||||
multihashing(this.bytes, 'sha2-256', callback)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,9 +44,8 @@ class Ed25519PrivateKey {
|
|||||||
this._publicKey = ensureKey(publicKey, crypto.publicKeyLength)
|
this._publicKey = ensureKey(publicKey, crypto.publicKeyLength)
|
||||||
}
|
}
|
||||||
|
|
||||||
sign (message, callback) {
|
async sign (message) { // eslint-disable-line require-await
|
||||||
ensure(callback)
|
return crypto.hashAndSign(this._key, message)
|
||||||
crypto.hashAndSign(this._key, message, callback)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
get public () {
|
get public () {
|
||||||
@@ -74,21 +71,30 @@ class Ed25519PrivateKey {
|
|||||||
return this.bytes.equals(key.bytes)
|
return this.bytes.equals(key.bytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
hash (callback) {
|
async hash () { // eslint-disable-line require-await
|
||||||
ensure(callback)
|
return multihashing(this.bytes, 'sha2-256')
|
||||||
multihashing(this.bytes, 'sha2-256', callback)
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the ID of the key.
|
||||||
|
*
|
||||||
|
* The key id is the base58 encoding of the SHA-256 multihash of its public key.
|
||||||
|
* The public key is a protobuf encoding containing a type and the DER encoding
|
||||||
|
* of the PKCS SubjectPublicKeyInfo.
|
||||||
|
*
|
||||||
|
* @returns {Promise<String>}
|
||||||
|
*/
|
||||||
|
async id () {
|
||||||
|
const hash = await this.public.hash()
|
||||||
|
return bs58.encode(hash)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function unmarshalEd25519PrivateKey (bytes, callback) {
|
function unmarshalEd25519PrivateKey (bytes) {
|
||||||
try {
|
bytes = ensureKey(bytes, crypto.privateKeyLength + crypto.publicKeyLength)
|
||||||
bytes = ensureKey(bytes, crypto.privateKeyLength + crypto.publicKeyLength)
|
|
||||||
} catch (err) {
|
|
||||||
return callback(err)
|
|
||||||
}
|
|
||||||
const privateKeyBytes = bytes.slice(0, crypto.privateKeyLength)
|
const privateKeyBytes = bytes.slice(0, crypto.privateKeyLength)
|
||||||
const publicKeyBytes = bytes.slice(crypto.privateKeyLength, bytes.length)
|
const publicKeyBytes = bytes.slice(crypto.privateKeyLength, bytes.length)
|
||||||
callback(null, new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes))
|
return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
function unmarshalEd25519PublicKey (bytes) {
|
function unmarshalEd25519PublicKey (bytes) {
|
||||||
@@ -96,52 +102,14 @@ function unmarshalEd25519PublicKey (bytes) {
|
|||||||
return new Ed25519PublicKey(bytes)
|
return new Ed25519PublicKey(bytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
function generateKeyPair (_bits, cb) {
|
async function generateKeyPair () {
|
||||||
if (cb === undefined && typeof _bits === 'function') {
|
const { secretKey, publicKey } = await crypto.generateKey()
|
||||||
cb = _bits
|
return new Ed25519PrivateKey(secretKey, publicKey)
|
||||||
}
|
|
||||||
|
|
||||||
crypto.generateKey((err, keys) => {
|
|
||||||
if (err) {
|
|
||||||
return cb(err)
|
|
||||||
}
|
|
||||||
let privkey
|
|
||||||
try {
|
|
||||||
privkey = new Ed25519PrivateKey(keys.secretKey, keys.publicKey)
|
|
||||||
} catch (err) {
|
|
||||||
cb(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
cb(null, privkey)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function generateKeyPairFromSeed (seed, _bits, cb) {
|
async function generateKeyPairFromSeed (seed) {
|
||||||
if (cb === undefined && typeof _bits === 'function') {
|
const { secretKey, publicKey } = await crypto.generateKeyFromSeed(seed)
|
||||||
cb = _bits
|
return new Ed25519PrivateKey(secretKey, publicKey)
|
||||||
}
|
|
||||||
|
|
||||||
crypto.generateKeyFromSeed(seed, (err, keys) => {
|
|
||||||
if (err) {
|
|
||||||
return cb(err)
|
|
||||||
}
|
|
||||||
let privkey
|
|
||||||
try {
|
|
||||||
privkey = new Ed25519PrivateKey(keys.secretKey, keys.publicKey)
|
|
||||||
} catch (err) {
|
|
||||||
cb(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
cb(null, privkey)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
function ensure (cb) {
|
|
||||||
if (typeof cb !== 'function') {
|
|
||||||
throw new Error('callback is required')
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function ensureKey (key, length) {
|
function ensureKey (key, length) {
|
||||||
|
@@ -1,47 +1,23 @@
|
|||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const nacl = require('tweetnacl')
|
const nacl = require('tweetnacl')
|
||||||
const setImmediate = require('async/setImmediate')
|
|
||||||
const Buffer = require('safe-buffer').Buffer
|
|
||||||
|
|
||||||
exports.publicKeyLength = nacl.sign.publicKeyLength
|
exports.publicKeyLength = nacl.sign.publicKeyLength
|
||||||
exports.privateKeyLength = nacl.sign.secretKeyLength
|
exports.privateKeyLength = nacl.sign.secretKeyLength
|
||||||
|
|
||||||
exports.generateKey = function (callback) {
|
exports.generateKey = async function () { // eslint-disable-line require-await
|
||||||
const done = (err, res) => setImmediate(() => {
|
return nacl.sign.keyPair()
|
||||||
callback(err, res)
|
|
||||||
})
|
|
||||||
|
|
||||||
let keys
|
|
||||||
try {
|
|
||||||
keys = nacl.sign.keyPair()
|
|
||||||
} catch (err) {
|
|
||||||
return done(err)
|
|
||||||
}
|
|
||||||
done(null, keys)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// seed should be a 32 byte uint8array
|
// seed should be a 32 byte uint8array
|
||||||
exports.generateKeyFromSeed = function (seed, callback) {
|
exports.generateKeyFromSeed = async function (seed) { // eslint-disable-line require-await
|
||||||
const done = (err, res) => setImmediate(() => callback(err, res))
|
return nacl.sign.keyPair.fromSeed(seed)
|
||||||
|
|
||||||
let keys
|
|
||||||
try {
|
|
||||||
keys = nacl.sign.keyPair.fromSeed(seed)
|
|
||||||
} catch (err) {
|
|
||||||
return done(err)
|
|
||||||
}
|
|
||||||
done(null, keys)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.hashAndSign = function (key, msg, callback) {
|
exports.hashAndSign = async function (key, msg) { // eslint-disable-line require-await
|
||||||
setImmediate(() => {
|
return Buffer.from(nacl.sign.detached(msg, key))
|
||||||
callback(null, Buffer.from(nacl.sign.detached(msg, key)))
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.hashAndVerify = function (key, sig, msg, callback) {
|
exports.hashAndVerify = async function (key, sig, msg) { // eslint-disable-line require-await
|
||||||
setImmediate(() => {
|
return nacl.sign.detached.verify(msg, sig, key)
|
||||||
callback(null, nacl.sign.detached.verify(msg, sig, key))
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
@@ -6,6 +6,4 @@ const ecdh = require('./ecdh')
|
|||||||
// the shared secret key.
|
// the shared secret key.
|
||||||
//
|
//
|
||||||
// Focuses only on ECDH now, but can be made more general in the future.
|
// Focuses only on ECDH now, but can be made more general in the future.
|
||||||
module.exports = (curve, callback) => {
|
module.exports = async (curve) => ecdh.generateEphmeralKeyPair(curve) // eslint-disable-line require-await
|
||||||
ecdh.generateEphmeralKeyPair(curve, callback)
|
|
||||||
}
|
|
||||||
|
@@ -1,16 +1,25 @@
|
|||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const protobuf = require('protocol-buffers')
|
const protobuf = require('protons')
|
||||||
const pbm = protobuf(require('./keys.proto'))
|
const keysPBM = protobuf(require('./keys.proto'))
|
||||||
|
require('node-forge/lib/asn1')
|
||||||
const keys = exports.keys = require('./keys')
|
require('node-forge/lib/rsa')
|
||||||
|
require('node-forge/lib/pbe')
|
||||||
|
const forge = require('node-forge/lib/forge')
|
||||||
|
|
||||||
exports = module.exports
|
exports = module.exports
|
||||||
|
|
||||||
exports.pbm = pbm
|
const supportedKeys = {
|
||||||
|
rsa: require('./rsa-class'),
|
||||||
|
ed25519: require('./ed25519-class'),
|
||||||
|
secp256k1: require('libp2p-crypto-secp256k1')(keysPBM, require('../random-bytes'))
|
||||||
|
}
|
||||||
|
|
||||||
|
exports.supportedKeys = supportedKeys
|
||||||
|
exports.keysPBM = keysPBM
|
||||||
|
|
||||||
function isValidKeyType (keyType) {
|
function isValidKeyType (keyType) {
|
||||||
const key = keys[keyType.toLowerCase()]
|
const key = supportedKeys[keyType.toLowerCase()]
|
||||||
return key !== undefined
|
return key !== undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -18,42 +27,43 @@ exports.keyStretcher = require('./key-stretcher')
|
|||||||
exports.generateEphemeralKeyPair = require('./ephemeral-keys')
|
exports.generateEphemeralKeyPair = require('./ephemeral-keys')
|
||||||
|
|
||||||
// Generates a keypair of the given type and bitsize
|
// Generates a keypair of the given type and bitsize
|
||||||
exports.generateKeyPair = (type, bits, cb) => {
|
exports.generateKeyPair = async (type, bits) => { // eslint-disable-line require-await
|
||||||
let key = keys[type.toLowerCase()]
|
let key = supportedKeys[type.toLowerCase()]
|
||||||
|
|
||||||
if (!key) {
|
if (!key) {
|
||||||
return cb(new Error('invalid or unsupported key type'))
|
throw new Error('invalid or unsupported key type')
|
||||||
}
|
}
|
||||||
|
|
||||||
key.generateKeyPair(bits, cb)
|
return key.generateKeyPair(bits)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generates a keypair of the given type and bitsize
|
// Generates a keypair of the given type and bitsize
|
||||||
// seed is a 32 byte uint8array
|
// seed is a 32 byte uint8array
|
||||||
exports.generateKeyPairFromSeed = (type, seed, bits, cb) => {
|
exports.generateKeyPairFromSeed = async (type, seed, bits) => { // eslint-disable-line require-await
|
||||||
let key = keys[type.toLowerCase()]
|
let key = supportedKeys[type.toLowerCase()]
|
||||||
if (!key) {
|
if (!key) {
|
||||||
return cb(new Error('invalid or unsupported key type'))
|
throw new Error('invalid or unsupported key type')
|
||||||
}
|
}
|
||||||
if (type.toLowerCase() !== 'ed25519') {
|
if (type.toLowerCase() !== 'ed25519') {
|
||||||
return cb(new Error('Seed key derivation is unimplemented for RSA or secp256k1'))
|
throw new Error('Seed key derivation is unimplemented for RSA or secp256k1')
|
||||||
}
|
}
|
||||||
key.generateKeyPairFromSeed(seed, bits, cb)
|
return key.generateKeyPairFromSeed(seed, bits)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Converts a protobuf serialized public key into its
|
// Converts a protobuf serialized public key into its
|
||||||
// representative object
|
// representative object
|
||||||
exports.unmarshalPublicKey = (buf) => {
|
exports.unmarshalPublicKey = (buf) => {
|
||||||
const decoded = pbm.PublicKey.decode(buf)
|
const decoded = keysPBM.PublicKey.decode(buf)
|
||||||
|
const data = decoded.Data
|
||||||
|
|
||||||
switch (decoded.Type) {
|
switch (decoded.Type) {
|
||||||
case pbm.KeyType.RSA:
|
case keysPBM.KeyType.RSA:
|
||||||
return keys.rsa.unmarshalRsaPublicKey(decoded.Data)
|
return supportedKeys.rsa.unmarshalRsaPublicKey(data)
|
||||||
case pbm.KeyType.Ed25519:
|
case keysPBM.KeyType.Ed25519:
|
||||||
return keys.ed25519.unmarshalEd25519PublicKey(decoded.Data)
|
return supportedKeys.ed25519.unmarshalEd25519PublicKey(data)
|
||||||
case pbm.KeyType.Secp256k1:
|
case keysPBM.KeyType.Secp256k1:
|
||||||
if (keys.secp256k1) {
|
if (supportedKeys.secp256k1) {
|
||||||
return keys.secp256k1.unmarshalSecp256k1PublicKey(decoded.Data)
|
return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data)
|
||||||
} else {
|
} else {
|
||||||
throw new Error('secp256k1 support requires libp2p-crypto-secp256k1 package')
|
throw new Error('secp256k1 support requires libp2p-crypto-secp256k1 package')
|
||||||
}
|
}
|
||||||
@@ -74,22 +84,23 @@ exports.marshalPublicKey = (key, type) => {
|
|||||||
|
|
||||||
// Converts a protobuf serialized private key into its
|
// Converts a protobuf serialized private key into its
|
||||||
// representative object
|
// representative object
|
||||||
exports.unmarshalPrivateKey = (buf, callback) => {
|
exports.unmarshalPrivateKey = async (buf) => { // eslint-disable-line require-await
|
||||||
const decoded = pbm.PrivateKey.decode(buf)
|
const decoded = keysPBM.PrivateKey.decode(buf)
|
||||||
|
const data = decoded.Data
|
||||||
|
|
||||||
switch (decoded.Type) {
|
switch (decoded.Type) {
|
||||||
case pbm.KeyType.RSA:
|
case keysPBM.KeyType.RSA:
|
||||||
return keys.rsa.unmarshalRsaPrivateKey(decoded.Data, callback)
|
return supportedKeys.rsa.unmarshalRsaPrivateKey(data)
|
||||||
case pbm.KeyType.Ed25519:
|
case keysPBM.KeyType.Ed25519:
|
||||||
return keys.ed25519.unmarshalEd25519PrivateKey(decoded.Data, callback)
|
return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data)
|
||||||
case pbm.KeyType.Secp256k1:
|
case keysPBM.KeyType.Secp256k1:
|
||||||
if (keys.secp256k1) {
|
if (supportedKeys.secp256k1) {
|
||||||
return keys.secp256k1.unmarshalSecp256k1PrivateKey(decoded.Data, callback)
|
return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data)
|
||||||
} else {
|
} else {
|
||||||
return callback(new Error('secp256k1 support requires libp2p-crypto-secp256k1 package'))
|
throw new Error('secp256k1 support requires libp2p-crypto-secp256k1 package')
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
callback(new Error('invalid or unsupported key type'))
|
throw new Error('invalid or unsupported key type')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,3 +113,13 @@ exports.marshalPrivateKey = (key, type) => {
|
|||||||
|
|
||||||
return key.bytes
|
return key.bytes
|
||||||
}
|
}
|
||||||
|
|
||||||
|
exports.import = async (pem, password) => { // eslint-disable-line require-await
|
||||||
|
const key = forge.pki.decryptRsaPrivateKey(pem, password)
|
||||||
|
if (key === null) {
|
||||||
|
throw new Error('Cannot read the key, most likely the password is wrong or not a RSA key')
|
||||||
|
}
|
||||||
|
let der = forge.asn1.toDer(forge.pki.privateKeyToAsn1(key))
|
||||||
|
der = Buffer.from(der.getBytes(), 'binary')
|
||||||
|
return supportedKeys.rsa.unmarshalRsaPrivateKey(der)
|
||||||
|
}
|
||||||
|
@@ -1,7 +1,5 @@
|
|||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const whilst = require('async/whilst')
|
|
||||||
const Buffer = require('safe-buffer').Buffer
|
|
||||||
const hmac = require('../hmac')
|
const hmac = require('../hmac')
|
||||||
|
|
||||||
const cipherMap = {
|
const cipherMap = {
|
||||||
@@ -21,15 +19,15 @@ const cipherMap = {
|
|||||||
|
|
||||||
// Generates a set of keys for each party by stretching the shared key.
|
// Generates a set of keys for each party by stretching the shared key.
|
||||||
// (myIV, theirIV, myCipherKey, theirCipherKey, myMACKey, theirMACKey)
|
// (myIV, theirIV, myCipherKey, theirCipherKey, myMACKey, theirMACKey)
|
||||||
module.exports = (cipherType, hash, secret, callback) => {
|
module.exports = async (cipherType, hash, secret) => {
|
||||||
const cipher = cipherMap[cipherType]
|
const cipher = cipherMap[cipherType]
|
||||||
|
|
||||||
if (!cipher) {
|
if (!cipher) {
|
||||||
return callback(new Error('unkown cipherType passed'))
|
throw new Error('unkown cipherType passed')
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!hash) {
|
if (!hash) {
|
||||||
return callback(new Error('unkown hashType passed'))
|
throw new Error('unkown hashType passed')
|
||||||
}
|
}
|
||||||
|
|
||||||
const cipherKeySize = cipher.keySize
|
const cipherKeySize = cipher.keySize
|
||||||
@@ -38,72 +36,38 @@ module.exports = (cipherType, hash, secret, callback) => {
|
|||||||
const seed = Buffer.from('key expansion')
|
const seed = Buffer.from('key expansion')
|
||||||
const resultLength = 2 * (ivSize + cipherKeySize + hmacKeySize)
|
const resultLength = 2 * (ivSize + cipherKeySize + hmacKeySize)
|
||||||
|
|
||||||
hmac.create(hash, secret, (err, m) => {
|
const m = await hmac.create(hash, secret)
|
||||||
if (err) {
|
let a = await m.digest(seed)
|
||||||
return callback(err)
|
|
||||||
|
let result = []
|
||||||
|
let j = 0
|
||||||
|
|
||||||
|
while (j < resultLength) {
|
||||||
|
const b = await m.digest(Buffer.concat([a, seed]))
|
||||||
|
let todo = b.length
|
||||||
|
|
||||||
|
if (j + todo > resultLength) {
|
||||||
|
todo = resultLength - j
|
||||||
}
|
}
|
||||||
|
|
||||||
m.digest(seed, (err, a) => {
|
result.push(b)
|
||||||
if (err) {
|
j += todo
|
||||||
return callback(err)
|
a = await m.digest(a)
|
||||||
}
|
}
|
||||||
|
|
||||||
let result = []
|
const half = resultLength / 2
|
||||||
let j = 0
|
const resultBuffer = Buffer.concat(result)
|
||||||
|
const r1 = resultBuffer.slice(0, half)
|
||||||
|
const r2 = resultBuffer.slice(half, resultLength)
|
||||||
|
|
||||||
whilst(
|
const createKey = (res) => ({
|
||||||
() => j < resultLength,
|
iv: res.slice(0, ivSize),
|
||||||
stretch,
|
cipherKey: res.slice(ivSize, ivSize + cipherKeySize),
|
||||||
finish
|
macKey: res.slice(ivSize + cipherKeySize)
|
||||||
)
|
|
||||||
|
|
||||||
function stretch (cb) {
|
|
||||||
m.digest(Buffer.concat([a, seed]), (err, b) => {
|
|
||||||
if (err) {
|
|
||||||
return cb(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
let todo = b.length
|
|
||||||
|
|
||||||
if (j + todo > resultLength) {
|
|
||||||
todo = resultLength - j
|
|
||||||
}
|
|
||||||
|
|
||||||
result.push(b)
|
|
||||||
|
|
||||||
j += todo
|
|
||||||
|
|
||||||
m.digest(a, (err, _a) => {
|
|
||||||
if (err) {
|
|
||||||
return cb(err)
|
|
||||||
}
|
|
||||||
a = _a
|
|
||||||
cb()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
function finish (err) {
|
|
||||||
if (err) {
|
|
||||||
return callback(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
const half = resultLength / 2
|
|
||||||
const resultBuffer = Buffer.concat(result)
|
|
||||||
const r1 = resultBuffer.slice(0, half)
|
|
||||||
const r2 = resultBuffer.slice(half, resultLength)
|
|
||||||
|
|
||||||
const createKey = (res) => ({
|
|
||||||
iv: res.slice(0, ivSize),
|
|
||||||
cipherKey: res.slice(ivSize, ivSize + cipherKeySize),
|
|
||||||
macKey: res.slice(ivSize + cipherKeySize)
|
|
||||||
})
|
|
||||||
|
|
||||||
callback(null, {
|
|
||||||
k1: createKey(r1),
|
|
||||||
k2: createKey(r2)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
k1: createKey(r1),
|
||||||
|
k2: createKey(r2)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,7 +0,0 @@
|
|||||||
'use strict'
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
rsa: require('./rsa-class'),
|
|
||||||
ed25519: require('./ed25519-class'),
|
|
||||||
secp256k1: require('libp2p-crypto-secp256k1')
|
|
||||||
}
|
|
@@ -5,12 +5,10 @@ module.exports = `enum KeyType {
|
|||||||
Ed25519 = 1;
|
Ed25519 = 1;
|
||||||
Secp256k1 = 2;
|
Secp256k1 = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
message PublicKey {
|
message PublicKey {
|
||||||
required KeyType Type = 1;
|
required KeyType Type = 1;
|
||||||
required bytes Data = 2;
|
required bytes Data = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
message PrivateKey {
|
message PrivateKey {
|
||||||
required KeyType Type = 1;
|
required KeyType Type = 1;
|
||||||
required bytes Data = 2;
|
required bytes Data = 2;
|
||||||
|
@@ -1,96 +1,100 @@
|
|||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const nodeify = require('nodeify')
|
const webcrypto = require('../webcrypto.js')
|
||||||
const Buffer = require('safe-buffer').Buffer
|
const randomBytes = require('../random-bytes')
|
||||||
|
|
||||||
const webcrypto = require('../webcrypto.js')()
|
|
||||||
|
|
||||||
exports.utils = require('./rsa-utils')
|
exports.utils = require('./rsa-utils')
|
||||||
|
|
||||||
exports.generateKey = function (bits, callback) {
|
exports.generateKey = async function (bits) {
|
||||||
nodeify(webcrypto.subtle.generateKey(
|
const pair = await webcrypto.subtle.generateKey(
|
||||||
{
|
{
|
||||||
name: 'RSASSA-PKCS1-v1_5',
|
name: 'RSASSA-PKCS1-v1_5',
|
||||||
modulusLength: bits,
|
modulusLength: bits,
|
||||||
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
|
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
|
||||||
hash: {name: 'SHA-256'}
|
hash: { name: 'SHA-256' }
|
||||||
},
|
},
|
||||||
true,
|
true,
|
||||||
['sign', 'verify']
|
['sign', 'verify']
|
||||||
)
|
)
|
||||||
.then(exportKey)
|
|
||||||
.then((keys) => ({
|
const keys = await exportKey(pair)
|
||||||
|
|
||||||
|
return {
|
||||||
privateKey: keys[0],
|
privateKey: keys[0],
|
||||||
publicKey: keys[1]
|
publicKey: keys[1]
|
||||||
})), callback)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Takes a jwk key
|
// Takes a jwk key
|
||||||
exports.unmarshalPrivateKey = function (key, callback) {
|
exports.unmarshalPrivateKey = async function (key) {
|
||||||
const privateKey = webcrypto.subtle.importKey(
|
const privateKey = await webcrypto.subtle.importKey(
|
||||||
'jwk',
|
'jwk',
|
||||||
key,
|
key,
|
||||||
{
|
{
|
||||||
name: 'RSASSA-PKCS1-v1_5',
|
name: 'RSASSA-PKCS1-v1_5',
|
||||||
hash: {name: 'SHA-256'}
|
hash: { name: 'SHA-256' }
|
||||||
},
|
},
|
||||||
true,
|
true,
|
||||||
['sign']
|
['sign']
|
||||||
)
|
)
|
||||||
|
|
||||||
nodeify(Promise.all([
|
const pair = [
|
||||||
privateKey,
|
privateKey,
|
||||||
derivePublicFromPrivate(key)
|
await derivePublicFromPrivate(key)
|
||||||
]).then((keys) => exportKey({
|
]
|
||||||
|
|
||||||
|
const keys = await exportKey({
|
||||||
|
privateKey: pair[0],
|
||||||
|
publicKey: pair[1]
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
privateKey: keys[0],
|
privateKey: keys[0],
|
||||||
publicKey: keys[1]
|
publicKey: keys[1]
|
||||||
})).then((keys) => ({
|
}
|
||||||
privateKey: keys[0],
|
|
||||||
publicKey: keys[1]
|
|
||||||
})), callback)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.getRandomValues = function (arr) {
|
exports.getRandomValues = randomBytes
|
||||||
return Buffer.from(webcrypto.getRandomValues(arr))
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.hashAndSign = function (key, msg, callback) {
|
exports.hashAndSign = async function (key, msg) {
|
||||||
nodeify(webcrypto.subtle.importKey(
|
const privateKey = await webcrypto.subtle.importKey(
|
||||||
'jwk',
|
'jwk',
|
||||||
key,
|
key,
|
||||||
{
|
{
|
||||||
name: 'RSASSA-PKCS1-v1_5',
|
name: 'RSASSA-PKCS1-v1_5',
|
||||||
hash: {name: 'SHA-256'}
|
hash: { name: 'SHA-256' }
|
||||||
},
|
},
|
||||||
false,
|
false,
|
||||||
['sign']
|
['sign']
|
||||||
).then((privateKey) => {
|
)
|
||||||
return webcrypto.subtle.sign(
|
|
||||||
{name: 'RSASSA-PKCS1-v1_5'},
|
const sig = await webcrypto.subtle.sign(
|
||||||
privateKey,
|
{ name: 'RSASSA-PKCS1-v1_5' },
|
||||||
Uint8Array.from(msg)
|
privateKey,
|
||||||
)
|
Uint8Array.from(msg)
|
||||||
}).then((sig) => Buffer.from(sig)), callback)
|
)
|
||||||
|
|
||||||
|
return Buffer.from(sig)
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.hashAndVerify = function (key, sig, msg, callback) {
|
exports.hashAndVerify = async function (key, sig, msg) {
|
||||||
nodeify(webcrypto.subtle.importKey(
|
const publicKey = await webcrypto.subtle.importKey(
|
||||||
'jwk',
|
'jwk',
|
||||||
key,
|
key,
|
||||||
{
|
{
|
||||||
name: 'RSASSA-PKCS1-v1_5',
|
name: 'RSASSA-PKCS1-v1_5',
|
||||||
hash: {name: 'SHA-256'}
|
hash: { name: 'SHA-256' }
|
||||||
},
|
},
|
||||||
false,
|
false,
|
||||||
['verify']
|
['verify']
|
||||||
).then((publicKey) => {
|
)
|
||||||
return webcrypto.subtle.verify(
|
|
||||||
{name: 'RSASSA-PKCS1-v1_5'},
|
return webcrypto.subtle.verify(
|
||||||
publicKey,
|
{ name: 'RSASSA-PKCS1-v1_5' },
|
||||||
sig,
|
publicKey,
|
||||||
msg
|
sig,
|
||||||
)
|
msg
|
||||||
}), callback)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function exportKey (pair) {
|
function exportKey (pair) {
|
||||||
@@ -106,13 +110,11 @@ function derivePublicFromPrivate (jwKey) {
|
|||||||
{
|
{
|
||||||
kty: jwKey.kty,
|
kty: jwKey.kty,
|
||||||
n: jwKey.n,
|
n: jwKey.n,
|
||||||
e: jwKey.e,
|
e: jwKey.e
|
||||||
alg: jwKey.alg,
|
|
||||||
kid: jwKey.kid
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'RSASSA-PKCS1-v1_5',
|
name: 'RSASSA-PKCS1-v1_5',
|
||||||
hash: {name: 'SHA-256'}
|
hash: { name: 'SHA-256' }
|
||||||
},
|
},
|
||||||
true,
|
true,
|
||||||
['verify']
|
['verify']
|
||||||
|
@@ -1,19 +1,22 @@
|
|||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const multihashing = require('multihashing-async')
|
const multihashing = require('multihashing-async')
|
||||||
const protobuf = require('protocol-buffers')
|
const protobuf = require('protons')
|
||||||
|
const bs58 = require('bs58')
|
||||||
|
|
||||||
const crypto = require('./rsa')
|
const crypto = require('./rsa')
|
||||||
const pbm = protobuf(require('./keys.proto'))
|
const pbm = protobuf(require('./keys.proto'))
|
||||||
|
require('node-forge/lib/sha512')
|
||||||
|
require('node-forge/lib/pbe')
|
||||||
|
const forge = require('node-forge/lib/forge')
|
||||||
|
|
||||||
class RsaPublicKey {
|
class RsaPublicKey {
|
||||||
constructor (key) {
|
constructor (key) {
|
||||||
this._key = key
|
this._key = key
|
||||||
}
|
}
|
||||||
|
|
||||||
verify (data, sig, callback) {
|
async verify (data, sig) { // eslint-disable-line require-await
|
||||||
ensure(callback)
|
return crypto.hashAndVerify(this._key, sig, data)
|
||||||
crypto.hashAndVerify(this._key, sig, data, callback)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
marshal () {
|
marshal () {
|
||||||
@@ -35,9 +38,8 @@ class RsaPublicKey {
|
|||||||
return this.bytes.equals(key.bytes)
|
return this.bytes.equals(key.bytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
hash (callback) {
|
async hash () { // eslint-disable-line require-await
|
||||||
ensure(callback)
|
return multihashing(this.bytes, 'sha2-256')
|
||||||
multihashing(this.bytes, 'sha2-256', callback)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,12 +52,11 @@ class RsaPrivateKey {
|
|||||||
}
|
}
|
||||||
|
|
||||||
genSecret () {
|
genSecret () {
|
||||||
return crypto.getRandomValues(new Uint8Array(16))
|
return crypto.getRandomValues(16)
|
||||||
}
|
}
|
||||||
|
|
||||||
sign (message, callback) {
|
async sign (message) { // eslint-disable-line require-await
|
||||||
ensure(callback)
|
return crypto.hashAndSign(this._key, message)
|
||||||
crypto.hashAndSign(this._key, message, callback)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
get public () {
|
get public () {
|
||||||
@@ -66,10 +67,6 @@ class RsaPrivateKey {
|
|||||||
return new RsaPublicKey(this._publicKey)
|
return new RsaPublicKey(this._publicKey)
|
||||||
}
|
}
|
||||||
|
|
||||||
decrypt (msg, callback) {
|
|
||||||
crypto.decrypt(this._key, msg, callback)
|
|
||||||
}
|
|
||||||
|
|
||||||
marshal () {
|
marshal () {
|
||||||
return crypto.utils.jwkToPkcs1(this._key)
|
return crypto.utils.jwkToPkcs1(this._key)
|
||||||
}
|
}
|
||||||
@@ -85,43 +82,73 @@ class RsaPrivateKey {
|
|||||||
return this.bytes.equals(key.bytes)
|
return this.bytes.equals(key.bytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
hash (callback) {
|
async hash () { // eslint-disable-line require-await
|
||||||
ensure(callback)
|
return multihashing(this.bytes, 'sha2-256')
|
||||||
multihashing(this.bytes, 'sha2-256', callback)
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the ID of the key.
|
||||||
|
*
|
||||||
|
* The key id is the base58 encoding of the SHA-256 multihash of its public key.
|
||||||
|
* The public key is a protobuf encoding containing a type and the DER encoding
|
||||||
|
* of the PKCS SubjectPublicKeyInfo.
|
||||||
|
*
|
||||||
|
* @returns {Promise<String>}
|
||||||
|
*/
|
||||||
|
async id () {
|
||||||
|
const hash = await this.public.hash()
|
||||||
|
return bs58.encode(hash)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exports the key into a password protected PEM format
|
||||||
|
*
|
||||||
|
* @param {string} password - The password to read the encrypted PEM
|
||||||
|
* @param {string} [format] - Defaults to 'pkcs-8'.
|
||||||
|
* @returns {KeyInfo}
|
||||||
|
*/
|
||||||
|
async export (password, format = 'pkcs-8') { // eslint-disable-line require-await
|
||||||
|
let pem = null
|
||||||
|
|
||||||
|
const buffer = new forge.util.ByteBuffer(this.marshal())
|
||||||
|
const asn1 = forge.asn1.fromDer(buffer)
|
||||||
|
const privateKey = forge.pki.privateKeyFromAsn1(asn1)
|
||||||
|
|
||||||
|
if (format === 'pkcs-8') {
|
||||||
|
const options = {
|
||||||
|
algorithm: 'aes256',
|
||||||
|
count: 10000,
|
||||||
|
saltSize: 128 / 8,
|
||||||
|
prfAlgorithm: 'sha512'
|
||||||
|
}
|
||||||
|
pem = forge.pki.encryptRsaPrivateKey(privateKey, password, options)
|
||||||
|
} else {
|
||||||
|
throw new Error(`Unknown export format '${format}'`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return pem
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function unmarshalRsaPrivateKey (bytes, callback) {
|
async function unmarshalRsaPrivateKey (bytes) {
|
||||||
const jwk = crypto.utils.pkcs1ToJwk(bytes)
|
const jwk = crypto.utils.pkcs1ToJwk(bytes)
|
||||||
crypto.unmarshalPrivateKey(jwk, (err, keys) => {
|
const keys = await crypto.unmarshalPrivateKey(jwk)
|
||||||
if (err) {
|
return new RsaPrivateKey(keys.privateKey, keys.publicKey)
|
||||||
return callback(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
callback(null, new RsaPrivateKey(keys.privateKey, keys.publicKey))
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function unmarshalRsaPublicKey (bytes) {
|
function unmarshalRsaPublicKey (bytes) {
|
||||||
const jwk = crypto.utils.pkixToJwk(bytes)
|
const jwk = crypto.utils.pkixToJwk(bytes)
|
||||||
|
|
||||||
return new RsaPublicKey(jwk)
|
return new RsaPublicKey(jwk)
|
||||||
}
|
}
|
||||||
|
|
||||||
function generateKeyPair (bits, cb) {
|
async function fromJwk (jwk) {
|
||||||
crypto.generateKey(bits, (err, keys) => {
|
const keys = await crypto.unmarshalPrivateKey(jwk)
|
||||||
if (err) {
|
return new RsaPrivateKey(keys.privateKey, keys.publicKey)
|
||||||
return cb(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
cb(null, new RsaPrivateKey(keys.privateKey, keys.publicKey))
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function ensure (cb) {
|
async function generateKeyPair (bits) {
|
||||||
if (typeof cb !== 'function') {
|
const keys = await crypto.generateKey(bits)
|
||||||
throw new Error('callback is required')
|
return new RsaPrivateKey(keys.privateKey, keys.publicKey)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
@@ -129,5 +156,6 @@ module.exports = {
|
|||||||
RsaPrivateKey,
|
RsaPrivateKey,
|
||||||
unmarshalRsaPublicKey,
|
unmarshalRsaPublicKey,
|
||||||
unmarshalRsaPrivateKey,
|
unmarshalRsaPrivateKey,
|
||||||
generateKeyPair
|
generateKeyPair,
|
||||||
|
fromJwk
|
||||||
}
|
}
|
||||||
|
@@ -1,56 +1,69 @@
|
|||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const crypto = require('crypto')
|
const crypto = require('crypto')
|
||||||
const keypair = require('keypair')
|
const randomBytes = require('../random-bytes')
|
||||||
const setImmediate = require('async/setImmediate')
|
|
||||||
|
let keypair
|
||||||
|
try {
|
||||||
|
if (process.env.LP2P_FORCE_CRYPTO_LIB === 'keypair') {
|
||||||
|
throw new Error('Force keypair usage')
|
||||||
|
}
|
||||||
|
|
||||||
|
const ursa = require('ursa-optional') // throws if not compiled
|
||||||
|
keypair = ({ bits }) => {
|
||||||
|
const key = ursa.generatePrivateKey(bits)
|
||||||
|
return {
|
||||||
|
private: key.toPrivatePem(),
|
||||||
|
public: key.toPublicPem()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (process.env.LP2P_FORCE_CRYPTO_LIB === 'ursa') {
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
|
||||||
|
keypair = require('keypair')
|
||||||
|
}
|
||||||
const pemToJwk = require('pem-jwk').pem2jwk
|
const pemToJwk = require('pem-jwk').pem2jwk
|
||||||
const jwkToPem = require('pem-jwk').jwk2pem
|
const jwkToPem = require('pem-jwk').jwk2pem
|
||||||
|
|
||||||
exports.utils = require('./rsa-utils')
|
exports.utils = require('./rsa-utils')
|
||||||
|
|
||||||
exports.generateKey = function (bits, callback) {
|
exports.generateKey = async function (bits) { // eslint-disable-line require-await
|
||||||
const done = (err, res) => setImmediate(() => callback(err, res))
|
const key = keypair({ bits })
|
||||||
|
return {
|
||||||
let key
|
|
||||||
try {
|
|
||||||
key = keypair({ bits: bits })
|
|
||||||
} catch (err) {
|
|
||||||
return done(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
done(null, {
|
|
||||||
privateKey: pemToJwk(key.private),
|
privateKey: pemToJwk(key.private),
|
||||||
publicKey: pemToJwk(key.public)
|
publicKey: pemToJwk(key.public)
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Takes a jwk key
|
// Takes a jwk key
|
||||||
exports.unmarshalPrivateKey = function (key, callback) {
|
exports.unmarshalPrivateKey = async function (key) { // eslint-disable-line require-await
|
||||||
callback(null, {
|
if (!key) {
|
||||||
|
throw new Error('Key is invalid')
|
||||||
|
}
|
||||||
|
return {
|
||||||
privateKey: key,
|
privateKey: key,
|
||||||
publicKey: {
|
publicKey: {
|
||||||
kty: key.kty,
|
kty: key.kty,
|
||||||
n: key.n,
|
n: key.n,
|
||||||
e: key.e
|
e: key.e
|
||||||
}
|
}
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.getRandomValues = function (arr) {
|
exports.getRandomValues = randomBytes
|
||||||
return crypto.randomBytes(arr.length)
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.hashAndSign = function (key, msg, callback) {
|
exports.hashAndSign = async function (key, msg) { // eslint-disable-line require-await
|
||||||
const sign = crypto.createSign('RSA-SHA256')
|
const sign = crypto.createSign('RSA-SHA256')
|
||||||
|
|
||||||
sign.update(msg)
|
sign.update(msg)
|
||||||
setImmediate(() => callback(null, sign.sign(jwkToPem(key))))
|
const pem = jwkToPem(key)
|
||||||
|
return sign.sign(pem)
|
||||||
}
|
}
|
||||||
|
|
||||||
exports.hashAndVerify = function (key, sig, msg, callback) {
|
exports.hashAndVerify = async function (key, sig, msg) { // eslint-disable-line require-await
|
||||||
const verify = crypto.createVerify('RSA-SHA256')
|
const verify = crypto.createVerify('RSA-SHA256')
|
||||||
|
|
||||||
verify.update(msg)
|
verify.update(msg)
|
||||||
|
const pem = jwkToPem(key)
|
||||||
setImmediate(() => callback(null, verify.verify(jwkToPem(key), sig)))
|
return verify.verify(pem, sig)
|
||||||
}
|
}
|
||||||
|
43
src/pbkdf2.js
Normal file
43
src/pbkdf2.js
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
'use strict'
|
||||||
|
|
||||||
|
const forgePbkdf2 = require('node-forge/lib/pbkdf2')
|
||||||
|
const forgeUtil = require('node-forge/lib/util')
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Maps an IPFS hash name to its node-forge equivalent.
|
||||||
|
*
|
||||||
|
* See https://github.com/multiformats/multihash/blob/master/hashtable.csv
|
||||||
|
*
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
const hashName = {
|
||||||
|
sha1: 'sha1',
|
||||||
|
'sha2-256': 'sha256',
|
||||||
|
'sha2-512': 'sha512'
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Computes the Password-Based Key Derivation Function 2.
|
||||||
|
*
|
||||||
|
* @param {string} password
|
||||||
|
* @param {string} salt
|
||||||
|
* @param {number} iterations
|
||||||
|
* @param {number} keySize (in bytes)
|
||||||
|
* @param {string} hash - The hash name ('sha1', 'sha2-512, ...)
|
||||||
|
* @returns {string} - A new password
|
||||||
|
*/
|
||||||
|
function pbkdf2 (password, salt, iterations, keySize, hash) {
|
||||||
|
const hasher = hashName[hash]
|
||||||
|
if (!hasher) {
|
||||||
|
throw new Error(`Hash '${hash}' is unknown or not supported`)
|
||||||
|
}
|
||||||
|
const dek = forgePbkdf2(
|
||||||
|
password,
|
||||||
|
salt,
|
||||||
|
iterations,
|
||||||
|
keySize,
|
||||||
|
hasher)
|
||||||
|
return forgeUtil.encode64(dek)
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = pbkdf2
|
9
src/random-bytes.js
Normal file
9
src/random-bytes.js
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
'use strict'
|
||||||
|
const randomBytes = require('iso-random-stream/src/random')
|
||||||
|
|
||||||
|
module.exports = function (number) {
|
||||||
|
if (!number || typeof number !== 'number') {
|
||||||
|
throw new Error('first argument must be a Number bigger than 0')
|
||||||
|
}
|
||||||
|
return randomBytes(number)
|
||||||
|
}
|
@@ -1,7 +1,6 @@
|
|||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const BN = require('asn1.js').bignum
|
const BN = require('asn1.js').bignum
|
||||||
const Buffer = require('safe-buffer').Buffer
|
|
||||||
|
|
||||||
// Convert a BN.js instance to a base64 encoded string without padding
|
// Convert a BN.js instance to a base64 encoded string without padding
|
||||||
// Adapted from https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#appendix-C
|
// Adapted from https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#appendix-C
|
||||||
@@ -11,8 +10,8 @@ exports.toBase64 = function toBase64 (bn, len) {
|
|||||||
|
|
||||||
return s
|
return s
|
||||||
.replace(/(=*)$/, '') // Remove any trailing '='s
|
.replace(/(=*)$/, '') // Remove any trailing '='s
|
||||||
.replace(/\+/g, '-') // 62nd char of encoding
|
.replace(/\+/g, '-') // 62nd char of encoding
|
||||||
.replace(/\//g, '_') // 63rd char of encoding
|
.replace(/\//g, '_') // 63rd char of encoding
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert a base64 encoded string to a BN.js instance
|
// Convert a base64 encoded string to a BN.js instance
|
||||||
|
@@ -2,15 +2,4 @@
|
|||||||
|
|
||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
module.exports = () => {
|
module.exports = self.crypto || self.msCrypto
|
||||||
// This is only a shim for interfaces, not for functionality
|
|
||||||
if (typeof self !== 'undefined') {
|
|
||||||
require('webcrypto-shim')(self)
|
|
||||||
|
|
||||||
if (self.crypto) {
|
|
||||||
return self.crypto
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error('Please use an environment with crypto support')
|
|
||||||
}
|
|
||||||
|
@@ -6,8 +6,6 @@ const chai = require('chai')
|
|||||||
const dirtyChai = require('dirty-chai')
|
const dirtyChai = require('dirty-chai')
|
||||||
const expect = chai.expect
|
const expect = chai.expect
|
||||||
chai.use(dirtyChai)
|
chai.use(dirtyChai)
|
||||||
const series = require('async/series')
|
|
||||||
const Buffer = require('safe-buffer').Buffer
|
|
||||||
|
|
||||||
const crypto = require('../../src')
|
const crypto = require('../../src')
|
||||||
const fixtures = require('./../fixtures/aes')
|
const fixtures = require('./../fixtures/aes')
|
||||||
@@ -20,53 +18,43 @@ const bytes = {
|
|||||||
|
|
||||||
describe('AES-CTR', () => {
|
describe('AES-CTR', () => {
|
||||||
Object.keys(bytes).forEach((byte) => {
|
Object.keys(bytes).forEach((byte) => {
|
||||||
it(`${bytes[byte]} - encrypt and decrypt`, (done) => {
|
it(`${bytes[byte]} - encrypt and decrypt`, async () => {
|
||||||
const key = Buffer.alloc(parseInt(byte, 10))
|
const key = Buffer.alloc(parseInt(byte, 10))
|
||||||
key.fill(5)
|
key.fill(5)
|
||||||
|
|
||||||
const iv = Buffer.alloc(16)
|
const iv = Buffer.alloc(16)
|
||||||
iv.fill(1)
|
iv.fill(1)
|
||||||
|
|
||||||
crypto.aes.create(key, iv, (err, cipher) => {
|
const cipher = await crypto.aes.create(key, iv)
|
||||||
expect(err).to.not.exist()
|
|
||||||
|
|
||||||
series([
|
await encryptAndDecrypt(cipher)
|
||||||
encryptAndDecrypt(cipher),
|
await encryptAndDecrypt(cipher)
|
||||||
encryptAndDecrypt(cipher),
|
await encryptAndDecrypt(cipher)
|
||||||
encryptAndDecrypt(cipher),
|
await encryptAndDecrypt(cipher)
|
||||||
encryptAndDecrypt(cipher),
|
await encryptAndDecrypt(cipher)
|
||||||
encryptAndDecrypt(cipher)
|
|
||||||
], done)
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
Object.keys(bytes).forEach((byte) => {
|
Object.keys(bytes).forEach((byte) => {
|
||||||
it(`${bytes[byte]} - fixed - encrypt and decrypt`, (done) => {
|
it(`${bytes[byte]} - fixed - encrypt and decrypt`, async () => {
|
||||||
const key = Buffer.alloc(parseInt(byte, 10))
|
const key = Buffer.alloc(parseInt(byte, 10))
|
||||||
key.fill(5)
|
key.fill(5)
|
||||||
|
|
||||||
const iv = Buffer.alloc(16)
|
const iv = Buffer.alloc(16)
|
||||||
iv.fill(1)
|
iv.fill(1)
|
||||||
|
|
||||||
crypto.aes.create(key, iv, (err, cipher) => {
|
const cipher = await crypto.aes.create(key, iv)
|
||||||
expect(err).to.not.exist()
|
|
||||||
|
|
||||||
series(fixtures[byte].inputs.map((rawIn, i) => (cb) => {
|
for (let i = 0; i < fixtures[byte].inputs.length; i++) {
|
||||||
const input = Buffer.from(rawIn)
|
const rawIn = fixtures[byte].inputs[i]
|
||||||
const output = Buffer.from(fixtures[byte].outputs[i])
|
const input = Buffer.from(rawIn)
|
||||||
cipher.encrypt(input, (err, res) => {
|
const output = Buffer.from(fixtures[byte].outputs[i])
|
||||||
expect(err).to.not.exist()
|
const encrypted = await cipher.encrypt(input)
|
||||||
expect(res).to.have.length(output.length)
|
expect(encrypted).to.have.length(output.length)
|
||||||
expect(res).to.eql(output)
|
expect(encrypted).to.eql(output)
|
||||||
cipher.decrypt(res, (err, res) => {
|
const decrypted = await cipher.decrypt(encrypted)
|
||||||
expect(err).to.not.exist()
|
expect(decrypted).to.eql(input)
|
||||||
expect(res).to.eql(input)
|
}
|
||||||
cb()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}), done)
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -75,46 +63,35 @@ describe('AES-CTR', () => {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
it(`${bytes[byte]} - go interop - encrypt and decrypt`, (done) => {
|
it(`${bytes[byte]} - go interop - encrypt and decrypt`, async () => {
|
||||||
const key = Buffer.alloc(parseInt(byte, 10))
|
const key = Buffer.alloc(parseInt(byte, 10))
|
||||||
key.fill(5)
|
key.fill(5)
|
||||||
|
|
||||||
const iv = Buffer.alloc(16)
|
const iv = Buffer.alloc(16)
|
||||||
iv.fill(1)
|
iv.fill(1)
|
||||||
|
|
||||||
crypto.aes.create(key, iv, (err, cipher) => {
|
const cipher = await crypto.aes.create(key, iv)
|
||||||
expect(err).to.not.exist()
|
|
||||||
|
|
||||||
series(goFixtures[byte].inputs.map((rawIn, i) => (cb) => {
|
for (let i = 0; i < goFixtures[byte].inputs.length; i++) {
|
||||||
const input = Buffer.from(rawIn)
|
const rawIn = goFixtures[byte].inputs[i]
|
||||||
const output = Buffer.from(goFixtures[byte].outputs[i])
|
const input = Buffer.from(rawIn)
|
||||||
cipher.encrypt(input, (err, res) => {
|
const output = Buffer.from(goFixtures[byte].outputs[i])
|
||||||
expect(err).to.not.exist()
|
const encrypted = await cipher.encrypt(input)
|
||||||
expect(res).to.have.length(output.length)
|
expect(encrypted).to.have.length(output.length)
|
||||||
expect(res).to.be.eql(output)
|
expect(encrypted).to.eql(output)
|
||||||
cipher.decrypt(res, (err, res) => {
|
const decrypted = await cipher.decrypt(encrypted)
|
||||||
expect(err).to.not.exist()
|
expect(decrypted).to.eql(input)
|
||||||
expect(res).to.be.eql(input)
|
}
|
||||||
cb()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}), done)
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
function encryptAndDecrypt (cipher) {
|
async function encryptAndDecrypt (cipher) {
|
||||||
const data = Buffer.alloc(100)
|
const data = Buffer.alloc(100)
|
||||||
data.fill(Math.ceil(Math.random() * 100))
|
data.fill(Math.ceil(Math.random() * 100))
|
||||||
return (cb) => {
|
|
||||||
cipher.encrypt(data, (err, res) => {
|
const encrypted = await cipher.encrypt(data)
|
||||||
expect(err).to.not.exist()
|
const decrypted = await cipher.decrypt(encrypted)
|
||||||
cipher.decrypt(res, (err, res) => {
|
|
||||||
expect(err).to.not.exist()
|
expect(decrypted).to.be.eql(data)
|
||||||
expect(res).to.be.eql(data)
|
|
||||||
cb()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@@ -9,16 +9,11 @@ chai.use(dirtyChai)
|
|||||||
const crypto = require('../src')
|
const crypto = require('../src')
|
||||||
const fixtures = require('./fixtures/go-key-rsa')
|
const fixtures = require('./fixtures/go-key-rsa')
|
||||||
|
|
||||||
describe('libp2p-crypto', () => {
|
describe('libp2p-crypto', function () {
|
||||||
|
this.timeout(20 * 1000)
|
||||||
let key
|
let key
|
||||||
before((done) => {
|
before(async () => {
|
||||||
crypto.keys.generateKeyPair('RSA', 2048, (err, _key) => {
|
key = await crypto.keys.generateKeyPair('RSA', 512)
|
||||||
if (err) {
|
|
||||||
return done(err)
|
|
||||||
}
|
|
||||||
key = _key
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('marshalPublicKey and unmarshalPublicKey', () => {
|
it('marshalPublicKey and unmarshalPublicKey', () => {
|
||||||
@@ -32,71 +27,41 @@ describe('libp2p-crypto', () => {
|
|||||||
}).to.throw()
|
}).to.throw()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('marshalPrivateKey and unmarshalPrivateKey', (done) => {
|
it('marshalPrivateKey and unmarshalPrivateKey', async () => {
|
||||||
expect(() => {
|
expect(() => {
|
||||||
crypto.keys.marshalPrivateKey(key, 'invalid-key-type')
|
crypto.keys.marshalPrivateKey(key, 'invalid-key-type')
|
||||||
}).to.throw()
|
}).to.throw()
|
||||||
|
|
||||||
crypto.keys.unmarshalPrivateKey(crypto.keys.marshalPrivateKey(key), (err, key2) => {
|
const key2 = await crypto.keys.unmarshalPrivateKey(crypto.keys.marshalPrivateKey(key))
|
||||||
if (err) {
|
|
||||||
return done(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(key2.equals(key)).to.be.eql(true)
|
expect(key2.equals(key)).to.be.eql(true)
|
||||||
expect(key2.public.equals(key.public)).to.be.eql(true)
|
expect(key2.public.equals(key.public)).to.be.eql(true)
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
// marshalled keys seem to be slightly different
|
// marshalled keys seem to be slightly different
|
||||||
// unsure as to if this is just a difference in encoding
|
// unsure as to if this is just a difference in encoding
|
||||||
// or a bug
|
// or a bug
|
||||||
describe('go interop', () => {
|
describe('go interop', () => {
|
||||||
it('unmarshals private key', (done) => {
|
it('unmarshals private key', async () => {
|
||||||
crypto.keys.unmarshalPrivateKey(fixtures.private.key, (err, key) => {
|
const key = await crypto.keys.unmarshalPrivateKey(fixtures.private.key)
|
||||||
if (err) {
|
const hash = fixtures.private.hash
|
||||||
return done(err)
|
expect(fixtures.private.key).to.eql(key.bytes)
|
||||||
}
|
const digest = await key.hash()
|
||||||
const hash = fixtures.private.hash
|
expect(digest).to.eql(hash)
|
||||||
expect(fixtures.private.key).to.eql(key.bytes)
|
|
||||||
|
|
||||||
key.hash((err, digest) => {
|
|
||||||
if (err) {
|
|
||||||
return done(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(digest).to.eql(hash)
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('unmarshals public key', (done) => {
|
it('unmarshals public key', async () => {
|
||||||
const key = crypto.keys.unmarshalPublicKey(fixtures.public.key)
|
const key = crypto.keys.unmarshalPublicKey(fixtures.public.key)
|
||||||
const hash = fixtures.public.hash
|
const hash = fixtures.public.hash
|
||||||
|
|
||||||
expect(crypto.keys.marshalPublicKey(key)).to.eql(fixtures.public.key)
|
expect(crypto.keys.marshalPublicKey(key)).to.eql(fixtures.public.key)
|
||||||
|
const digest = await key.hash()
|
||||||
key.hash((err, digest) => {
|
expect(digest).to.eql(hash)
|
||||||
if (err) {
|
|
||||||
return done(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(digest).to.eql(hash)
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('unmarshal -> marshal, private key', (done) => {
|
it('unmarshal -> marshal, private key', async () => {
|
||||||
crypto.keys.unmarshalPrivateKey(fixtures.private.key, (err, key) => {
|
const key = await crypto.keys.unmarshalPrivateKey(fixtures.private.key)
|
||||||
if (err) {
|
const marshalled = crypto.keys.marshalPrivateKey(key)
|
||||||
return done(err)
|
expect(marshalled).to.eql(fixtures.private.key)
|
||||||
}
|
|
||||||
|
|
||||||
const marshalled = crypto.keys.marshalPrivateKey(key)
|
|
||||||
expect(marshalled).to.eql(fixtures.private.key)
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('unmarshal -> marshal, public key', () => {
|
it('unmarshal -> marshal, public key', () => {
|
||||||
@@ -106,6 +71,32 @@ describe('libp2p-crypto', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('pbkdf2', () => {
|
||||||
|
it('generates a derived password using sha1', () => {
|
||||||
|
const p1 = crypto.pbkdf2('password', 'at least 16 character salt', 500, 512 / 8, 'sha1')
|
||||||
|
expect(p1).to.exist()
|
||||||
|
expect(p1).to.be.a('string')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('generates a derived password using sha2-512', () => {
|
||||||
|
const p1 = crypto.pbkdf2('password', 'at least 16 character salt', 500, 512 / 8, 'sha2-512')
|
||||||
|
expect(p1).to.exist()
|
||||||
|
expect(p1).to.be.a('string')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('generates the same derived password with the same options', () => {
|
||||||
|
const p1 = crypto.pbkdf2('password', 'at least 16 character salt', 10, 512 / 8, 'sha1')
|
||||||
|
const p2 = crypto.pbkdf2('password', 'at least 16 character salt', 10, 512 / 8, 'sha1')
|
||||||
|
const p3 = crypto.pbkdf2('password', 'at least 16 character salt', 11, 512 / 8, 'sha1')
|
||||||
|
expect(p2).to.equal(p1)
|
||||||
|
expect(p3).to.not.equal(p2)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('throws on invalid hash name', () => {
|
||||||
|
expect(() => crypto.pbkdf2('password', 'at least 16 character salt', 500, 512 / 8, 'shaX-xxx')).to.throw()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
describe('randomBytes', () => {
|
describe('randomBytes', () => {
|
||||||
it('throws with no number passed', () => {
|
it('throws with no number passed', () => {
|
||||||
expect(() => {
|
expect(() => {
|
||||||
|
2
test/fixtures/go-elliptic-key.js
vendored
2
test/fixtures/go-elliptic-key.js
vendored
@@ -1,7 +1,5 @@
|
|||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const Buffer = require('safe-buffer').Buffer
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
curve: 'P-256',
|
curve: 'P-256',
|
||||||
bob: {
|
bob: {
|
||||||
|
2
test/fixtures/go-key-ed25519.js
vendored
2
test/fixtures/go-key-ed25519.js
vendored
@@ -1,7 +1,5 @@
|
|||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const Buffer = require('safe-buffer').Buffer
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
// These were generated in a gore (https://github.com/motemen/gore) repl session:
|
// These were generated in a gore (https://github.com/motemen/gore) repl session:
|
||||||
//
|
//
|
||||||
|
2
test/fixtures/go-key-rsa.js
vendored
2
test/fixtures/go-key-rsa.js
vendored
@@ -1,7 +1,5 @@
|
|||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const Buffer = require('safe-buffer').Buffer
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
private: {
|
private: {
|
||||||
hash: Buffer.from([
|
hash: Buffer.from([
|
||||||
|
2
test/fixtures/go-stretch-key.js
vendored
2
test/fixtures/go-stretch-key.js
vendored
@@ -1,7 +1,5 @@
|
|||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const Buffer = require('safe-buffer').Buffer
|
|
||||||
|
|
||||||
module.exports = [{
|
module.exports = [{
|
||||||
cipher: 'AES-256',
|
cipher: 'AES-256',
|
||||||
hash: 'SHA256',
|
hash: 'SHA256',
|
||||||
|
3
test/fixtures/secp256k1.js
vendored
3
test/fixtures/secp256k1.js
vendored
@@ -1,9 +1,6 @@
|
|||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const Buffer = require('safe-buffer').Buffer
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
|
||||||
// protobuf marshaled key pair generated with libp2p-crypto-secp256k1
|
// protobuf marshaled key pair generated with libp2p-crypto-secp256k1
|
||||||
// and marshaled with libp2p-crypto.marshalPublicKey / marshalPrivateKey
|
// and marshaled with libp2p-crypto.marshalPublicKey / marshalPrivateKey
|
||||||
pbmPrivateKey: Buffer.from('08021220e0600103010000000100000000000000be1dc82c2e000000e8d6030301000000', 'hex'),
|
pbmPrivateKey: Buffer.from('08021220e0600103010000000100000000000000be1dc82c2e000000e8d6030301000000', 'hex'),
|
||||||
|
40
test/helpers/test-garbage-error-handling.js
Normal file
40
test/helpers/test-garbage-error-handling.js
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
/* eslint-env mocha */
|
||||||
|
'use strict'
|
||||||
|
|
||||||
|
const util = require('util')
|
||||||
|
const garbage = [Buffer.from('00010203040506070809', 'hex'), {}, null, false, undefined, true, 1, 0, Buffer.from(''), 'aGVsbG93b3JsZA==', 'helloworld', '']
|
||||||
|
|
||||||
|
function doTests (fncName, fnc, num, skipBuffersAndStrings) {
|
||||||
|
if (!num) {
|
||||||
|
num = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
garbage.forEach((garbage) => {
|
||||||
|
if (skipBuffersAndStrings && (Buffer.isBuffer(garbage) || (typeof garbage) === 'string')) {
|
||||||
|
// skip this garbage because it's a buffer or a string and we were told do do that
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let args = []
|
||||||
|
for (let i = 0; i < num; i++) {
|
||||||
|
args.push(garbage)
|
||||||
|
}
|
||||||
|
it(fncName + '(' + args.map(garbage => util.inspect(garbage)).join(', ') + ')', async () => {
|
||||||
|
try {
|
||||||
|
await fnc.apply(null, args)
|
||||||
|
} catch (err) {
|
||||||
|
return // expected
|
||||||
|
}
|
||||||
|
throw new Error('Expected error to be thrown')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = (obj, fncs, num) => {
|
||||||
|
describe('returns error via cb instead of crashing', () => {
|
||||||
|
fncs.forEach(fnc => {
|
||||||
|
doTests(fnc, obj[fnc], num)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports.doTests = doTests
|
@@ -2,7 +2,6 @@
|
|||||||
/* eslint-env mocha */
|
/* eslint-env mocha */
|
||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const Buffer = require('safe-buffer').Buffer
|
|
||||||
const chai = require('chai')
|
const chai = require('chai')
|
||||||
const dirtyChai = require('dirty-chai')
|
const dirtyChai = require('dirty-chai')
|
||||||
const expect = chai.expect
|
const expect = chai.expect
|
||||||
@@ -14,16 +13,10 @@ const hashes = ['SHA1', 'SHA256', 'SHA512']
|
|||||||
|
|
||||||
describe('HMAC', () => {
|
describe('HMAC', () => {
|
||||||
hashes.forEach((hash) => {
|
hashes.forEach((hash) => {
|
||||||
it(`${hash} - sign and verify`, (done) => {
|
it(`${hash} - sign and verify`, async () => {
|
||||||
crypto.hmac.create(hash, Buffer.from('secret'), (err, hmac) => {
|
const hmac = await crypto.hmac.create(hash, Buffer.from('secret'))
|
||||||
expect(err).to.not.exist()
|
const sig = await hmac.digest(Buffer.from('hello world'))
|
||||||
|
expect(sig).to.have.length(hmac.length)
|
||||||
hmac.digest(Buffer.from('hello world'), (err, sig) => {
|
|
||||||
expect(err).to.not.exist()
|
|
||||||
expect(sig).to.have.length(hmac.length)
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
@@ -5,114 +5,77 @@ const chai = require('chai')
|
|||||||
const dirtyChai = require('dirty-chai')
|
const dirtyChai = require('dirty-chai')
|
||||||
const expect = chai.expect
|
const expect = chai.expect
|
||||||
chai.use(dirtyChai)
|
chai.use(dirtyChai)
|
||||||
const Buffer = require('safe-buffer').Buffer
|
|
||||||
|
|
||||||
const crypto = require('../../src')
|
const crypto = require('../../src')
|
||||||
const ed25519 = crypto.keys.keys.ed25519
|
const ed25519 = crypto.keys.supportedKeys.ed25519
|
||||||
const fixtures = require('../fixtures/go-key-ed25519')
|
const fixtures = require('../fixtures/go-key-ed25519')
|
||||||
|
|
||||||
describe('ed25519', () => {
|
const testGarbage = require('../helpers/test-garbage-error-handling')
|
||||||
|
|
||||||
|
describe('ed25519', function () {
|
||||||
|
this.timeout(20 * 1000)
|
||||||
let key
|
let key
|
||||||
before((done) => {
|
before(async () => {
|
||||||
crypto.keys.generateKeyPair('Ed25519', 512, (err, _key) => {
|
key = await crypto.keys.generateKeyPair('Ed25519', 512)
|
||||||
if (err) return done(err)
|
|
||||||
key = _key
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('generates a valid key', (done) => {
|
it('generates a valid key', async () => {
|
||||||
expect(key).to.be.an.instanceof(ed25519.Ed25519PrivateKey)
|
expect(key).to.be.an.instanceof(ed25519.Ed25519PrivateKey)
|
||||||
|
const digest = await key.hash()
|
||||||
key.hash((err, digest) => {
|
expect(digest).to.have.length(34)
|
||||||
if (err) {
|
|
||||||
return done(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(digest).to.have.length(34)
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('generates a valid key from seed', (done) => {
|
it('generates a valid key from seed', async () => {
|
||||||
var seed = crypto.randomBytes(32)
|
var seed = crypto.randomBytes(32)
|
||||||
crypto.keys.generateKeyPairFromSeed('Ed25519', seed, 512, (err, seededkey) => {
|
const seededkey = await crypto.keys.generateKeyPairFromSeed('Ed25519', seed, 512)
|
||||||
if (err) return done(err)
|
expect(seededkey).to.be.an.instanceof(ed25519.Ed25519PrivateKey)
|
||||||
expect(seededkey).to.be.an.instanceof(ed25519.Ed25519PrivateKey)
|
const digest = await seededkey.hash()
|
||||||
|
expect(digest).to.have.length(34)
|
||||||
seededkey.hash((err, digest) => {
|
|
||||||
if (err) {
|
|
||||||
return done(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(digest).to.have.length(34)
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('generates the same key from the same seed', (done) => {
|
it('generates the same key from the same seed', async () => {
|
||||||
var seed = crypto.randomBytes(32)
|
const seed = crypto.randomBytes(32)
|
||||||
crypto.keys.generateKeyPairFromSeed('Ed25519', seed, 512, (err, seededkey1) => {
|
const seededkey1 = await crypto.keys.generateKeyPairFromSeed('Ed25519', seed, 512)
|
||||||
if (err) return done(err)
|
const seededkey2 = await crypto.keys.generateKeyPairFromSeed('Ed25519', seed, 512)
|
||||||
crypto.keys.generateKeyPairFromSeed('Ed25519', seed, 512, (err, seededkey2) => {
|
expect(seededkey1.equals(seededkey2)).to.eql(true)
|
||||||
if (err) return done(err)
|
expect(seededkey1.public.equals(seededkey2.public)).to.eql(true)
|
||||||
expect(seededkey1.equals(seededkey2)).to.eql(true)
|
|
||||||
expect(seededkey1.public.equals(seededkey2.public)).to.eql(true)
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('generates different keys for different seeds', (done) => {
|
it('generates different keys for different seeds', async () => {
|
||||||
const seed1 = crypto.randomBytes(32)
|
const seed1 = crypto.randomBytes(32)
|
||||||
crypto.keys.generateKeyPairFromSeed('Ed25519', seed1, 512, (err, seededkey1) => {
|
const seededkey1 = await crypto.keys.generateKeyPairFromSeed('Ed25519', seed1, 512)
|
||||||
expect(err).to.not.exist()
|
const seed2 = crypto.randomBytes(32)
|
||||||
|
const seededkey2 = await crypto.keys.generateKeyPairFromSeed('Ed25519', seed2, 512)
|
||||||
const seed2 = crypto.randomBytes(32)
|
expect(seededkey1.equals(seededkey2)).to.eql(false)
|
||||||
crypto.keys.generateKeyPairFromSeed('Ed25519', seed2, 512, (err, seededkey2) => {
|
expect(seededkey1.public.equals(seededkey2.public)).to.eql(false)
|
||||||
expect(err).to.not.exist()
|
|
||||||
|
|
||||||
expect(seededkey1.equals(seededkey2)).to.eql(false)
|
|
||||||
expect(seededkey1.public.equals(seededkey2.public))
|
|
||||||
.to.eql(false)
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('signs', (done) => {
|
it('signs', async () => {
|
||||||
const text = crypto.randomBytes(512)
|
const text = crypto.randomBytes(512)
|
||||||
|
const sig = await key.sign(text)
|
||||||
key.sign(text, (err, sig) => {
|
const res = await key.public.verify(text, sig)
|
||||||
expect(err).to.not.exist()
|
expect(res).to.be.eql(true)
|
||||||
|
|
||||||
key.public.verify(text, sig, (err, res) => {
|
|
||||||
expect(err).to.not.exist()
|
|
||||||
expect(res).to.be.eql(true)
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('encoding', (done) => {
|
it('encoding', async () => {
|
||||||
const keyMarshal = key.marshal()
|
const keyMarshal = key.marshal()
|
||||||
ed25519.unmarshalEd25519PrivateKey(keyMarshal, (err, key2) => {
|
const key2 = await ed25519.unmarshalEd25519PrivateKey(keyMarshal)
|
||||||
if (err) {
|
const keyMarshal2 = key2.marshal()
|
||||||
return done(err)
|
|
||||||
}
|
|
||||||
const keyMarshal2 = key2.marshal()
|
|
||||||
|
|
||||||
expect(keyMarshal).to.eql(keyMarshal2)
|
expect(keyMarshal).to.eql(keyMarshal2)
|
||||||
|
|
||||||
const pk = key.public
|
const pk = key.public
|
||||||
const pkMarshal = pk.marshal()
|
const pkMarshal = pk.marshal()
|
||||||
const pk2 = ed25519.unmarshalEd25519PublicKey(pkMarshal)
|
const pk2 = ed25519.unmarshalEd25519PublicKey(pkMarshal)
|
||||||
const pkMarshal2 = pk2.marshal()
|
const pkMarshal2 = pk2.marshal()
|
||||||
|
|
||||||
expect(pkMarshal).to.eql(pkMarshal2)
|
expect(pkMarshal).to.eql(pkMarshal2)
|
||||||
done()
|
})
|
||||||
})
|
|
||||||
|
it('key id', async () => {
|
||||||
|
const id = await key.id()
|
||||||
|
expect(id).to.exist()
|
||||||
|
expect(id).to.be.a('string')
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('key equals', () => {
|
describe('key equals', () => {
|
||||||
@@ -130,80 +93,52 @@ describe('ed25519', () => {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('not equals other key', (done) => {
|
it('not equals other key', async () => {
|
||||||
crypto.keys.generateKeyPair('Ed25519', 512, (err, key2) => {
|
const key2 = await crypto.keys.generateKeyPair('Ed25519', 512)
|
||||||
if (err) return done(err)
|
expect(key.equals(key2)).to.eql(false)
|
||||||
|
expect(key2.equals(key)).to.eql(false)
|
||||||
expect(key.equals(key2)).to.eql(false)
|
expect(key.public.equals(key2.public)).to.eql(false)
|
||||||
expect(key2.equals(key)).to.eql(false)
|
expect(key2.public.equals(key.public)).to.eql(false)
|
||||||
expect(key.public.equals(key2.public)).to.eql(false)
|
|
||||||
expect(key2.public.equals(key.public)).to.eql(false)
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
it('sign and verify', (done) => {
|
it('sign and verify', async () => {
|
||||||
const data = Buffer.from('hello world')
|
const data = Buffer.from('hello world')
|
||||||
key.sign(data, (err, sig) => {
|
const sig = await key.sign(data)
|
||||||
if (err) {
|
const valid = await key.public.verify(data, sig)
|
||||||
return done(err)
|
expect(valid).to.eql(true)
|
||||||
}
|
|
||||||
|
|
||||||
key.public.verify(data, sig, (err, valid) => {
|
|
||||||
if (err) {
|
|
||||||
return done(err)
|
|
||||||
}
|
|
||||||
expect(valid).to.eql(true)
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('fails to verify for different data', (done) => {
|
it('fails to verify for different data', async () => {
|
||||||
const data = Buffer.from('hello world')
|
const data = Buffer.from('hello world')
|
||||||
key.sign(data, (err, sig) => {
|
const sig = await key.sign(data)
|
||||||
if (err) {
|
const valid = await key.public.verify(Buffer.from('hello'), sig)
|
||||||
return done(err)
|
expect(valid).to.be.eql(false)
|
||||||
}
|
})
|
||||||
|
|
||||||
key.public.verify(Buffer.from('hello'), sig, (err, valid) => {
|
describe('returns error via cb instead of crashing', () => {
|
||||||
if (err) {
|
const key = crypto.keys.unmarshalPublicKey(fixtures.verify.publicKey)
|
||||||
return done(err)
|
testGarbage.doTests('key.verify', key.verify.bind(key), 2)
|
||||||
}
|
testGarbage.doTests('crypto.keys.unmarshalPrivateKey', crypto.keys.unmarshalPrivateKey.bind(crypto.keys))
|
||||||
expect(valid).to.be.eql(false)
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('go interop', () => {
|
describe('go interop', () => {
|
||||||
let privateKey
|
let privateKey
|
||||||
|
|
||||||
before((done) => {
|
before(async () => {
|
||||||
crypto.keys.unmarshalPrivateKey(fixtures.verify.privateKey, (err, key) => {
|
const key = await crypto.keys.unmarshalPrivateKey(fixtures.verify.privateKey)
|
||||||
expect(err).to.not.exist()
|
privateKey = key
|
||||||
privateKey = key
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('verifies with data from go', (done) => {
|
it('verifies with data from go', async () => {
|
||||||
const key = crypto.keys.unmarshalPublicKey(fixtures.verify.publicKey)
|
const key = crypto.keys.unmarshalPublicKey(fixtures.verify.publicKey)
|
||||||
|
const ok = await key.verify(fixtures.verify.data, fixtures.verify.signature)
|
||||||
key.verify(fixtures.verify.data, fixtures.verify.signature, (err, ok) => {
|
expect(ok).to.eql(true)
|
||||||
expect(err).to.not.exist()
|
|
||||||
expect(ok).to.eql(true)
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('generates the same signature as go', (done) => {
|
it('generates the same signature as go', async () => {
|
||||||
privateKey.sign(fixtures.verify.data, (err, sig) => {
|
const sig = await privateKey.sign(fixtures.verify.data)
|
||||||
expect(err).to.not.exist()
|
expect(sig).to.eql(fixtures.verify.signature)
|
||||||
expect(sig).to.eql(fixtures.verify.signature)
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
@@ -6,7 +6,6 @@ const chai = require('chai')
|
|||||||
const dirtyChai = require('dirty-chai')
|
const dirtyChai = require('dirty-chai')
|
||||||
const expect = chai.expect
|
const expect = chai.expect
|
||||||
chai.use(dirtyChai)
|
chai.use(dirtyChai)
|
||||||
const parallel = require('async/parallel')
|
|
||||||
|
|
||||||
const fixtures = require('../fixtures/go-elliptic-key')
|
const fixtures = require('../fixtures/go-elliptic-key')
|
||||||
const crypto = require('../../src')
|
const crypto = require('../../src')
|
||||||
@@ -25,49 +24,40 @@ const secretLengths = {
|
|||||||
|
|
||||||
describe('generateEphemeralKeyPair', () => {
|
describe('generateEphemeralKeyPair', () => {
|
||||||
curves.forEach((curve) => {
|
curves.forEach((curve) => {
|
||||||
it(`generate and shared key ${curve}`, (done) => {
|
it(`generate and shared key ${curve}`, async () => {
|
||||||
parallel([
|
const keys = await Promise.all([
|
||||||
(cb) => crypto.keys.generateEphemeralKeyPair(curve, cb),
|
crypto.keys.generateEphemeralKeyPair(curve),
|
||||||
(cb) => crypto.keys.generateEphemeralKeyPair(curve, cb)
|
crypto.keys.generateEphemeralKeyPair(curve)
|
||||||
], (err, keys) => {
|
])
|
||||||
expect(err).to.not.exist()
|
|
||||||
expect(keys[0].key).to.have.length(lengths[curve])
|
|
||||||
expect(keys[1].key).to.have.length(lengths[curve])
|
|
||||||
|
|
||||||
keys[0].genSharedKey(keys[1].key, (err, shared) => {
|
expect(keys[0].key).to.have.length(lengths[curve])
|
||||||
expect(err).to.not.exist()
|
expect(keys[1].key).to.have.length(lengths[curve])
|
||||||
expect(shared).to.have.length(secretLengths[curve])
|
|
||||||
done()
|
const shared = await keys[0].genSharedKey(keys[1].key)
|
||||||
})
|
expect(shared).to.have.length(secretLengths[curve])
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('go interop', () => {
|
describe('go interop', () => {
|
||||||
it('generates a shared secret', (done) => {
|
it('generates a shared secret', async () => {
|
||||||
const curve = fixtures.curve
|
const curve = fixtures.curve
|
||||||
|
|
||||||
parallel([
|
const keys = await Promise.all([
|
||||||
(cb) => crypto.keys.generateEphemeralKeyPair(curve, cb),
|
crypto.keys.generateEphemeralKeyPair(curve),
|
||||||
(cb) => crypto.keys.generateEphemeralKeyPair(curve, cb)
|
crypto.keys.generateEphemeralKeyPair(curve)
|
||||||
], (err, res) => {
|
])
|
||||||
expect(err).to.not.exist()
|
|
||||||
const alice = res[0]
|
|
||||||
const bob = res[1]
|
|
||||||
bob.key = fixtures.bob.public
|
|
||||||
|
|
||||||
parallel([
|
const alice = keys[0]
|
||||||
(cb) => alice.genSharedKey(bob.key, cb),
|
const bob = keys[1]
|
||||||
(cb) => bob.genSharedKey(alice.key, fixtures.bob, cb)
|
bob.key = fixtures.bob.public
|
||||||
], (err, secrets) => {
|
|
||||||
expect(err).to.not.exist()
|
|
||||||
|
|
||||||
expect(secrets[0]).to.eql(secrets[1])
|
const secrets = await Promise.all([
|
||||||
expect(secrets[0]).to.have.length(32)
|
alice.genSharedKey(bob.key),
|
||||||
|
bob.genSharedKey(alice.key, fixtures.bob)
|
||||||
|
])
|
||||||
|
|
||||||
done()
|
expect(secrets[0]).to.eql(secrets[1])
|
||||||
})
|
expect(secrets[0]).to.have.length(32)
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
@@ -16,35 +16,17 @@ describe('keyStretcher', () => {
|
|||||||
let res
|
let res
|
||||||
let secret
|
let secret
|
||||||
|
|
||||||
before((done) => {
|
before(async () => {
|
||||||
crypto.keys.generateEphemeralKeyPair('P-256', (err, _res) => {
|
res = await crypto.keys.generateEphemeralKeyPair('P-256')
|
||||||
if (err) {
|
secret = await res.genSharedKey(res.key)
|
||||||
return done(err)
|
|
||||||
}
|
|
||||||
res = _res
|
|
||||||
res.genSharedKey(res.key, (err, _secret) => {
|
|
||||||
if (err) {
|
|
||||||
return done(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
secret = _secret
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
ciphers.forEach((cipher) => {
|
ciphers.forEach((cipher) => {
|
||||||
hashes.forEach((hash) => {
|
hashes.forEach((hash) => {
|
||||||
it(`${cipher} - ${hash}`, (done) => {
|
it(`${cipher} - ${hash}`, async () => {
|
||||||
crypto.keys.keyStretcher(cipher, hash, secret, (err, keys) => {
|
const keys = await crypto.keys.keyStretcher(cipher, hash, secret)
|
||||||
if (err) {
|
expect(keys.k1).to.exist()
|
||||||
return done(err)
|
expect(keys.k2).to.exist()
|
||||||
}
|
|
||||||
|
|
||||||
expect(keys.k1).to.exist()
|
|
||||||
expect(keys.k2).to.exist()
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -52,24 +34,19 @@ describe('keyStretcher', () => {
|
|||||||
|
|
||||||
describe('go interop', () => {
|
describe('go interop', () => {
|
||||||
fixtures.forEach((test) => {
|
fixtures.forEach((test) => {
|
||||||
it(`${test.cipher} - ${test.hash}`, (done) => {
|
it(`${test.cipher} - ${test.hash}`, async () => {
|
||||||
const cipher = test.cipher
|
const cipher = test.cipher
|
||||||
const hash = test.hash
|
const hash = test.hash
|
||||||
const secret = test.secret
|
const secret = test.secret
|
||||||
crypto.keys.keyStretcher(cipher, hash, secret, (err, keys) => {
|
const keys = await crypto.keys.keyStretcher(cipher, hash, secret)
|
||||||
if (err) {
|
|
||||||
return done(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(keys.k1.iv).to.be.eql(test.k1.iv)
|
expect(keys.k1.iv).to.be.eql(test.k1.iv)
|
||||||
expect(keys.k1.cipherKey).to.be.eql(test.k1.cipherKey)
|
expect(keys.k1.cipherKey).to.be.eql(test.k1.cipherKey)
|
||||||
expect(keys.k1.macKey).to.be.eql(test.k1.macKey)
|
expect(keys.k1.macKey).to.be.eql(test.k1.macKey)
|
||||||
|
|
||||||
expect(keys.k2.iv).to.be.eql(test.k2.iv)
|
expect(keys.k2.iv).to.be.eql(test.k2.iv)
|
||||||
expect(keys.k2.cipherKey).to.be.eql(test.k2.cipherKey)
|
expect(keys.k2.cipherKey).to.be.eql(test.k2.cipherKey)
|
||||||
expect(keys.k2.macKey).to.be.eql(test.k2.macKey)
|
expect(keys.k2.macKey).to.be.eql(test.k2.macKey)
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
53
test/keys/rsa-crypto-libs.js
Normal file
53
test/keys/rsa-crypto-libs.js
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
'use strict'
|
||||||
|
|
||||||
|
/* eslint-env mocha */
|
||||||
|
/* eslint max-nested-callbacks: ["error", 8] */
|
||||||
|
|
||||||
|
const chai = require('chai')
|
||||||
|
const dirtyChai = require('dirty-chai')
|
||||||
|
const expect = chai.expect
|
||||||
|
chai.use(dirtyChai)
|
||||||
|
chai.use(require('chai-string'))
|
||||||
|
|
||||||
|
const LIBS = ['ursa', 'keypair']
|
||||||
|
|
||||||
|
describe('RSA crypto libs', function () {
|
||||||
|
this.timeout(20 * 1000)
|
||||||
|
|
||||||
|
LIBS.forEach(lib => {
|
||||||
|
describe(lib, () => {
|
||||||
|
let crypto
|
||||||
|
let rsa
|
||||||
|
|
||||||
|
before(() => {
|
||||||
|
process.env.LP2P_FORCE_CRYPTO_LIB = lib
|
||||||
|
|
||||||
|
for (const path in require.cache) { // clear module cache
|
||||||
|
if (path.endsWith('.js')) {
|
||||||
|
delete require.cache[path]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
crypto = require('../../src')
|
||||||
|
rsa = crypto.keys.supportedKeys.rsa
|
||||||
|
})
|
||||||
|
|
||||||
|
it('generates a valid key', async () => {
|
||||||
|
const key = await crypto.keys.generateKeyPair('RSA', 512)
|
||||||
|
expect(key).to.be.an.instanceof(rsa.RsaPrivateKey)
|
||||||
|
const digest = await key.hash()
|
||||||
|
expect(digest).to.have.length(34)
|
||||||
|
})
|
||||||
|
|
||||||
|
after(() => {
|
||||||
|
for (const path in require.cache) { // clear module cache
|
||||||
|
if (path.endsWith('.js')) {
|
||||||
|
delete require.cache[path]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
delete process.env.LP2P_FORCE_CRYPTO_LIB
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint max-nested-callbacks: ["error", 8] */
|
||||||
/* eslint-env mocha */
|
/* eslint-env mocha */
|
||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
@@ -5,75 +6,54 @@ const chai = require('chai')
|
|||||||
const dirtyChai = require('dirty-chai')
|
const dirtyChai = require('dirty-chai')
|
||||||
const expect = chai.expect
|
const expect = chai.expect
|
||||||
chai.use(dirtyChai)
|
chai.use(dirtyChai)
|
||||||
const Buffer = require('safe-buffer').Buffer
|
chai.use(require('chai-string'))
|
||||||
|
|
||||||
const crypto = require('../../src')
|
const crypto = require('../../src')
|
||||||
const rsa = crypto.keys.keys.rsa
|
const rsa = crypto.keys.supportedKeys.rsa
|
||||||
const fixtures = require('../fixtures/go-key-rsa')
|
const fixtures = require('../fixtures/go-key-rsa')
|
||||||
|
|
||||||
describe('RSA', () => {
|
const testGarbage = require('../helpers/test-garbage-error-handling')
|
||||||
|
|
||||||
|
describe('RSA', function () {
|
||||||
|
this.timeout(20 * 1000)
|
||||||
let key
|
let key
|
||||||
|
|
||||||
before((done) => {
|
before(async () => {
|
||||||
crypto.keys.generateKeyPair('RSA', 2048, (err, _key) => {
|
key = await crypto.keys.generateKeyPair('RSA', 512)
|
||||||
if (err) {
|
|
||||||
return done(err)
|
|
||||||
}
|
|
||||||
key = _key
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('generates a valid key', (done) => {
|
it('generates a valid key', async () => {
|
||||||
expect(key).to.be.an.instanceof(rsa.RsaPrivateKey)
|
expect(key).to.be.an.instanceof(rsa.RsaPrivateKey)
|
||||||
|
const digest = await key.hash()
|
||||||
key.hash((err, digest) => {
|
expect(digest).to.have.length(34)
|
||||||
if (err) {
|
|
||||||
return done(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(digest).to.have.length(34)
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('signs', (done) => {
|
it('signs', async () => {
|
||||||
const text = key.genSecret()
|
const text = key.genSecret()
|
||||||
|
const sig = await key.sign(text)
|
||||||
key.sign(text, (err, sig) => {
|
const res = await key.public.verify(text, sig)
|
||||||
if (err) {
|
expect(res).to.be.eql(true)
|
||||||
return done(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
key.public.verify(text, sig, (err, res) => {
|
|
||||||
if (err) {
|
|
||||||
return done(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(res).to.be.eql(true)
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('encoding', (done) => {
|
it('encoding', async () => {
|
||||||
const keyMarshal = key.marshal()
|
const keyMarshal = key.marshal()
|
||||||
rsa.unmarshalRsaPrivateKey(keyMarshal, (err, key2) => {
|
const key2 = await rsa.unmarshalRsaPrivateKey(keyMarshal)
|
||||||
if (err) {
|
const keyMarshal2 = key2.marshal()
|
||||||
return done(err)
|
|
||||||
}
|
|
||||||
const keyMarshal2 = key2.marshal()
|
|
||||||
|
|
||||||
expect(keyMarshal).to.eql(keyMarshal2)
|
expect(keyMarshal).to.eql(keyMarshal2)
|
||||||
|
|
||||||
const pk = key.public
|
const pk = key.public
|
||||||
const pkMarshal = pk.marshal()
|
const pkMarshal = pk.marshal()
|
||||||
const pk2 = rsa.unmarshalRsaPublicKey(pkMarshal)
|
const pk2 = rsa.unmarshalRsaPublicKey(pkMarshal)
|
||||||
const pkMarshal2 = pk2.marshal()
|
const pkMarshal2 = pk2.marshal()
|
||||||
|
|
||||||
expect(pkMarshal).to.eql(pkMarshal2)
|
expect(pkMarshal).to.eql(pkMarshal2)
|
||||||
done()
|
})
|
||||||
})
|
|
||||||
|
it('key id', async () => {
|
||||||
|
const id = await key.id()
|
||||||
|
expect(id).to.exist()
|
||||||
|
expect(id).to.be.a('string')
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('key equals', () => {
|
describe('key equals', () => {
|
||||||
@@ -83,65 +63,282 @@ describe('RSA', () => {
|
|||||||
expect(key.public.equals(key.public)).to.eql(true)
|
expect(key.public.equals(key.public)).to.eql(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('not equals other key', (done) => {
|
it('not equals other key', async () => {
|
||||||
crypto.keys.generateKeyPair('RSA', 2048, (err, key2) => {
|
const key2 = await crypto.keys.generateKeyPair('RSA', 512)
|
||||||
if (err) {
|
expect(key.equals(key2)).to.eql(false)
|
||||||
return done(err)
|
expect(key2.equals(key)).to.eql(false)
|
||||||
}
|
expect(key.public.equals(key2.public)).to.eql(false)
|
||||||
|
expect(key2.public.equals(key.public)).to.eql(false)
|
||||||
expect(key.equals(key2)).to.eql(false)
|
|
||||||
expect(key2.equals(key)).to.eql(false)
|
|
||||||
expect(key.public.equals(key2.public)).to.eql(false)
|
|
||||||
expect(key2.public.equals(key.public)).to.eql(false)
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
it('sign and verify', (done) => {
|
it('sign and verify', async () => {
|
||||||
const data = Buffer.from('hello world')
|
const data = Buffer.from('hello world')
|
||||||
key.sign(data, (err, sig) => {
|
const sig = await key.sign(data)
|
||||||
if (err) {
|
const valid = await key.public.verify(data, sig)
|
||||||
return done(err)
|
expect(valid).to.be.eql(true)
|
||||||
}
|
})
|
||||||
|
|
||||||
key.public.verify(data, sig, (err, valid) => {
|
it('fails to verify for different data', async () => {
|
||||||
if (err) {
|
const data = Buffer.from('hello world')
|
||||||
return done(err)
|
const sig = await key.sign(data)
|
||||||
}
|
const valid = await key.public.verify(Buffer.from('hello'), sig)
|
||||||
expect(valid).to.be.eql(true)
|
expect(valid).to.be.eql(false)
|
||||||
done()
|
})
|
||||||
})
|
|
||||||
|
describe('export and import', () => {
|
||||||
|
it('password protected PKCS #8', async () => {
|
||||||
|
const pem = await key.export('my secret', 'pkcs-8')
|
||||||
|
expect(pem).to.startsWith('-----BEGIN ENCRYPTED PRIVATE KEY-----')
|
||||||
|
const clone = await crypto.keys.import(pem, 'my secret')
|
||||||
|
expect(clone).to.exist()
|
||||||
|
expect(key.equals(clone)).to.eql(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('defaults to PKCS #8', async () => {
|
||||||
|
const pem = await key.export('another secret')
|
||||||
|
expect(pem).to.startsWith('-----BEGIN ENCRYPTED PRIVATE KEY-----')
|
||||||
|
const clone = await crypto.keys.import(pem, 'another secret')
|
||||||
|
expect(clone).to.exist()
|
||||||
|
expect(key.equals(clone)).to.eql(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('needs correct password', async () => {
|
||||||
|
const pem = await key.export('another secret')
|
||||||
|
try {
|
||||||
|
await crypto.keys.import(pem, 'not the secret')
|
||||||
|
} catch (err) {
|
||||||
|
return // expected
|
||||||
|
}
|
||||||
|
throw new Error('Expected error to be thrown')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
it('fails to verify for different data', (done) => {
|
describe('returns error via cb instead of crashing', () => {
|
||||||
const data = Buffer.from('hello world')
|
const key = crypto.keys.unmarshalPublicKey(fixtures.verify.publicKey)
|
||||||
key.sign(data, (err, sig) => {
|
testGarbage.doTests('key.verify', key.verify.bind(key), 2, true)
|
||||||
if (err) {
|
testGarbage.doTests('crypto.keys.unmarshalPrivateKey', crypto.keys.unmarshalPrivateKey.bind(crypto.keys))
|
||||||
return done(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
key.public.verify(Buffer.from('hello'), sig, (err, valid) => {
|
|
||||||
if (err) {
|
|
||||||
return done(err)
|
|
||||||
}
|
|
||||||
expect(valid).to.be.eql(false)
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('go interop', () => {
|
describe('go interop', () => {
|
||||||
it('verifies with data from go', (done) => {
|
it('verifies with data from go', async () => {
|
||||||
const key = crypto.keys.unmarshalPublicKey(fixtures.verify.publicKey)
|
const key = crypto.keys.unmarshalPublicKey(fixtures.verify.publicKey)
|
||||||
|
const ok = await key.verify(fixtures.verify.data, fixtures.verify.signature)
|
||||||
|
expect(ok).to.equal(true)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
key.verify(fixtures.verify.data, fixtures.verify.signature, (err, ok) => {
|
describe('openssl interop', () => {
|
||||||
if (err) throw err
|
it('can read a private key', async () => {
|
||||||
expect(err).to.not.exist()
|
/*
|
||||||
expect(ok).to.equal(true)
|
* Generated with
|
||||||
done()
|
* openssl genpkey -algorithm RSA
|
||||||
})
|
* -pkeyopt rsa_keygen_bits:3072
|
||||||
|
* -pkeyopt rsa_keygen_pubexp:65537
|
||||||
|
*/
|
||||||
|
const pem = `-----BEGIN PRIVATE KEY-----
|
||||||
|
MIIG/wIBADANBgkqhkiG9w0BAQEFAASCBukwggblAgEAAoIBgQDp0Whyqa8KmdvK
|
||||||
|
0MsQGJEBzDAEHAZc0C6cr0rkb6Xwo+yB5kjZBRDORk0UXtYGE1pYt4JhUTmMzcWO
|
||||||
|
v2xTIsdbVMQlNtput2U8kIqS1cSTkX5HxOJtCiIzntMzuR/bGPSOexkyFQ8nCUqb
|
||||||
|
ROS7cln/ixprra2KMAKldCApN3ue2jo/JI1gyoS8sekhOASAa0ufMPpC+f70sc75
|
||||||
|
Y53VLnGBNM43iM/2lsK+GI2a13d6rRy86CEM/ygnh/EDlyNDxo+SQmy6GmSv/lmR
|
||||||
|
xgWQE2dIfK504KIxFTOphPAQAr9AsmcNnCQLhbz7YTsBz8WcytHGQ0Z5pnBQJ9AV
|
||||||
|
CX9E6DFHetvs0CNLVw1iEO06QStzHulmNEI/3P8I1TIxViuESJxSu3pSNwG1bSJZ
|
||||||
|
+Qee24vvlz/slBzK5gZWHvdm46v7vl5z7SA+whncEtjrswd8vkJk9fI/YTUbgOC0
|
||||||
|
HWMdc2t/LTZDZ+LUSZ/b2n5trvdJSsOKTjEfuf0wICC08pUUk8MCAwEAAQKCAYEA
|
||||||
|
ywve+DQCneIezHGk5cVvp2/6ApeTruXalJZlIxsRr3eq2uNwP4X2oirKpPX2RjBo
|
||||||
|
NMKnpnsyzuOiu+Pf3hJFrTpfWzHXXm5Eq+OZcwnQO5YNY6XGO4qhSNKT9ka9Mzbo
|
||||||
|
qRKdPrCrB+s5rryVJXKYVSInP3sDSQ2IPsYpZ6GW6Mv56PuFCpjTzElzejV7M0n5
|
||||||
|
0bRmn+MZVMVUR54KYiaCywFgUzmr3yfs1cfcsKqMRywt2J58lRy/chTLZ6LILQMv
|
||||||
|
4V01neVJiRkTmUfIWvc1ENIFM9QJlky9AvA5ASvwTTRz8yOnxoOXE/y4OVyOePjT
|
||||||
|
cz9eumu9N5dPuUIMmsYlXmRNaeGZPD9bIgKY5zOlfhlfZSuOLNH6EHBNr6JAgfwL
|
||||||
|
pdP43sbg2SSNKpBZ0iSMvpyTpbigbe3OyhnFH/TyhcC2Wdf62S9/FRsvjlRPbakW
|
||||||
|
YhKAA2kmJoydcUDO5ccEga8b7NxCdhRiczbiU2cj70pMIuOhDlGAznyxsYbtyxaB
|
||||||
|
AoHBAPy6Cbt6y1AmuId/HYfvms6i8B+/frD1CKyn+sUDkPf81xSHV7RcNrJi1S1c
|
||||||
|
V55I0y96HulsR+GmcAW1DF3qivWkdsd/b4mVkizd/zJm3/Dm8p8QOnNTtdWvYoEB
|
||||||
|
VzfAhBGaR/xflSLxZh2WE8ZHQ3IcRCXV9ZFgJ7PMeTprBJXzl0lTptvrHyo9QK1v
|
||||||
|
obLrL/KuXWS0ql1uSnJr1vtDI5uW8WU4GDENeU5b/CJHpKpjVxlGg+7pmLknxlBl
|
||||||
|
oBnZnQKBwQDs2Ky29qZ69qnPWowKceMJ53Z6uoUeSffRZ7xuBjowpkylasEROjuL
|
||||||
|
nyAihIYB7fd7R74CnRVYLI+O2qXfNKJ8HN+TgcWv8LudkRcnZDSvoyPEJAPyZGfr
|
||||||
|
olRCXD3caqtarlZO7vXSAl09C6HcL2KZ8FuPIEsuO0Aw25nESMg9eVMaIC6s2eSU
|
||||||
|
NUt6xfZw1JC0c+f0LrGuFSjxT2Dr5WKND9ageI6afuauMuosjrrOMl2g0dMcSnVz
|
||||||
|
KrtYa7Wi1N8CgcBFnuJreUplDCWtfgEen40f+5b2yAQYr4fyOFxGxdK73jVJ/HbW
|
||||||
|
wsh2n+9mDZg9jIZQ/+1gFGpA6V7W06dSf/hD70ihcKPDXSbloUpaEikC7jxMQWY4
|
||||||
|
uwjOkwAp1bq3Kxu21a+bAKHO/H1LDTrpVlxoJQ1I9wYtRDXrvBpxU2XyASbeFmNT
|
||||||
|
FhSByFn27Ve4OD3/NrWXtoVwM5/ioX6ZvUcj55McdTWE3ddbFNACiYX9QlyOI/TY
|
||||||
|
bhWafDCPmU9fj6kCgcEAjyQEfi9jPj2FM0RODqH1zS6OdG31tfCOTYicYQJyeKSI
|
||||||
|
/hAezwKaqi9phHMDancfcupQ89Nr6vZDbNrIFLYC3W+1z7hGeabMPNZLYAs3rE60
|
||||||
|
dv4tRHlaNRbORazp1iTBmvRyRRI2js3O++3jzOb2eILDUyT5St+UU/LkY7R5EG4a
|
||||||
|
w1df3idx9gCftXufDWHqcqT6MqFl0QgIzo5izS68+PPxitpRlR3M3Mr4rCU20Rev
|
||||||
|
blphdF+rzAavYyj1hYuRAoHBANmxwbq+QqsJ19SmeGMvfhXj+T7fNZQFh2F0xwb2
|
||||||
|
rMlf4Ejsnx97KpCLUkoydqAs2q0Ws9Nkx2VEVx5KfUD7fWhgbpdnEPnQkfeXv9sD
|
||||||
|
vZTuAoqInN1+vj1TME6EKR/6D4OtQygSNpecv23EuqEvyXWqRVsRt9Qd2B0H4k7h
|
||||||
|
gnjREs10u7zyqBIZH7KYVgyh27WxLr859ap8cKAH6Fb+UOPtZo3sUeeume60aebn
|
||||||
|
4pMwXeXP+LO8NIfRXV8mgrm86g==
|
||||||
|
-----END PRIVATE KEY-----
|
||||||
|
`
|
||||||
|
const key = await crypto.keys.import(pem, '')
|
||||||
|
expect(key).to.exist()
|
||||||
|
const id = await key.id()
|
||||||
|
expect(id).to.equal('QmfWu2Xp8DZzCkZZzoPB9rcrq4R4RZid6AWE6kmrUAzuHy')
|
||||||
|
})
|
||||||
|
|
||||||
|
// AssertionError: expected 'this only supports pkcs5PBES2' to not exist
|
||||||
|
it.skip('can read a private encrypted key (v1)', async () => {
|
||||||
|
/*
|
||||||
|
* Generated with
|
||||||
|
* openssl genpkey -algorithm RSA
|
||||||
|
* -pkeyopt rsa_keygen_bits:1024
|
||||||
|
* -pkeyopt rsa_keygen_pubexp:65537
|
||||||
|
* -out foo.pem
|
||||||
|
* openssl pkcs8 -in foo.pem -topk8 -passout pass:mypassword
|
||||||
|
*/
|
||||||
|
const pem = `-----BEGIN ENCRYPTED PRIVATE KEY-----
|
||||||
|
MIICoTAbBgkqhkiG9w0BBQMwDgQI2563Jugj/KkCAggABIICgPxHkKtUUE8EWevq
|
||||||
|
eX9nTjqpbsv0QoXQMhegfxDELJLU8tj6V0bWNt7QDdfQ1n6FRgnNvNGick6gyqHH
|
||||||
|
yH9qC2oXwkDFP7OrHp2NEZd7DHQLLc+L4KJ/0dzsiZ1U9no7XzQMUay9Bc918ADE
|
||||||
|
pN2/EqigWkaG4gNjkAeKWr6+BNRevDXlSvls7YDboNcTiACi5zJkthivB9g3vT1m
|
||||||
|
gPdN6Gf/mmqtBTDHeqj5QsmXYqeCyo5b26JgYsziABVZDHph4ekPUsTvudRpE9Ex
|
||||||
|
baXwdYEAZxVpSbTvQ3A5qysjSZeM9ttfRTSSwL391q7dViz4+aujpk0Vj7piH+1B
|
||||||
|
CkfO8/XudRdRlnOe+KjMidktKCsMGCIOW92IlfMvIQ/Zn1GTYj9bRXONFNJ2WPND
|
||||||
|
UmCKnL7cmworwg/weRorrGKBWIGspU+tDASOPSvIGKo6Hoxm4CN1TpDRY7DAGlgm
|
||||||
|
Y3TEbMYfpXyzkPjvAhJDt03D3J9PrTO6uM5d7YUaaTmJ2TQFQVF2Lc3Uz8lDJLs0
|
||||||
|
ZYtfQ/4H+YY2RrX7ua7t6ArUcYXZtv0J4lRYWjwV8fGPUVc0d8xLJU0Yjf4BD7K8
|
||||||
|
rsavHo9b5YvBUX7SgUyxAEembEOe3SjQ+gPu2U5wovcjUuC9eItEEsXGrx30BQ0E
|
||||||
|
8BtK2+hp0eMkW5/BYckJkH+Yl8ypbzRGRRIZzLgeI4JveSx/mNhewfgTr+ORPThZ
|
||||||
|
mBdkD5r+ixWF174naw53L8U9wF8kiK7pIE1N9TR4USEeovLwX6Ni/2MMDZedOfof
|
||||||
|
2f77eUdLsK19/5/lcgAAYaXauXWhy2d2r3SayFrC9woy0lh2VLKRMBjcx1oWb7dp
|
||||||
|
0uxzo5Y=
|
||||||
|
-----END ENCRYPTED PRIVATE KEY-----
|
||||||
|
`
|
||||||
|
const key = await crypto.keys.import(pem, 'mypassword')
|
||||||
|
expect(key).to.exist()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('can read a private encrypted key (v2 aes-128-cbc)', async () => {
|
||||||
|
/*
|
||||||
|
* Generated with
|
||||||
|
* openssl genpkey -algorithm RSA
|
||||||
|
* -pkeyopt rsa_keygen_bits:1024
|
||||||
|
* -pkeyopt rsa_keygen_pubexp:65537
|
||||||
|
* -out foo.pem
|
||||||
|
* openssl pkcs8 -in foo.pem -topk8 -v2 aes-128-cbc -passout pass:mypassword
|
||||||
|
*/
|
||||||
|
const pem = `-----BEGIN ENCRYPTED PRIVATE KEY-----
|
||||||
|
MIICzzBJBgkqhkiG9w0BBQ0wPDAbBgkqhkiG9w0BBQwwDgQIP5QK2RfqUl4CAggA
|
||||||
|
MB0GCWCGSAFlAwQBAgQQj3OyM9gnW2dd/eRHkxjGrgSCAoCpM5GZB0v27cxzZsGc
|
||||||
|
O4/xqgwB0c/bSJ6QogtYU2KVoc7ZNQ5q9jtzn3I4ONvneOkpm9arzYz0FWnJi2C3
|
||||||
|
BPiF0D1NkfvjvMLv56bwiG2A1oBECacyAb2pXYeJY7SdtYKvcbgs3jx65uCm6TF2
|
||||||
|
BylteH+n1ewTQN9DLfASp1n81Ajq9lQGaK03SN2MUtcAPp7N9gnxJrlmDGeqlPRs
|
||||||
|
KpQYRcot+kE6Ew8a5jAr7mAxwpqvr3SM4dMvADZmRQsM4Uc/9+YMUdI52DG87EWc
|
||||||
|
0OUB+fnQ8jw4DZgOE9KKM5/QTWc3aEw/dzXr/YJsrv01oLazhqVHnEMG0Nfr0+DP
|
||||||
|
q+qac1AsCsOb71VxaRlRZcVEkEfAq3gidSPD93qmlDrCnmLYTilcLanXUepda7ez
|
||||||
|
qhjkHtpwBLN5xRZxOn3oUuLGjk8VRwfmFX+RIMYCyihjdmbEDYpNUVkQVYFGi/F/
|
||||||
|
1hxOyl9yhGdL0hb9pKHH10GGIgoqo4jSTLlb4ennihGMHCjehAjLdx/GKJkOWShy
|
||||||
|
V9hj8rAuYnRNb+tUW7ChXm1nLq14x9x1tX0ciVVn3ap/NoMkbFTr8M3pJ4bQlpAn
|
||||||
|
wCT2erYqwQtgSpOJcrFeph9TjIrNRVE7Zlmr7vayJrB/8/oPssVdhf82TXkna4fB
|
||||||
|
PcmO0YWLa117rfdeNM/Duy0ThSdTl39Qd+4FxqRZiHjbt+l0iSa/nOjTv1TZ/QqF
|
||||||
|
wqrO6EtcM45fbFJ1Y79o2ptC2D6MB4HKJq9WCt064/8zQCVx3XPbb3X8Z5o/6koy
|
||||||
|
ePGbz+UtSb9xczvqpRCOiFLh2MG1dUgWuHazjOtUcVWvilKnkjCMzZ9s1qG0sUDj
|
||||||
|
nPyn
|
||||||
|
-----END ENCRYPTED PRIVATE KEY-----
|
||||||
|
`
|
||||||
|
const key = await crypto.keys.import(pem, 'mypassword')
|
||||||
|
expect(key).to.exist()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('can read a private encrypted key (v2 aes-256-cbc)', async () => {
|
||||||
|
/*
|
||||||
|
* Generated with
|
||||||
|
* openssl genpkey -algorithm RSA
|
||||||
|
* -pkeyopt rsa_keygen_bits:1024
|
||||||
|
* -pkeyopt rsa_keygen_pubexp:65537
|
||||||
|
* -out foo.pem
|
||||||
|
* openssl pkcs8 -in foo.pem -topk8 -v2 aes-256-cbc -passout pass:mypassword
|
||||||
|
*/
|
||||||
|
const pem = `-----BEGIN ENCRYPTED PRIVATE KEY-----
|
||||||
|
MIICzzBJBgkqhkiG9w0BBQ0wPDAbBgkqhkiG9w0BBQwwDgQIhuL894loRucCAggA
|
||||||
|
MB0GCWCGSAFlAwQBKgQQEoEtsjW3iC9/u0uGvkxX7wSCAoAsX3l6JoR2OGbT8CkY
|
||||||
|
YT3RQFqquOgItYOHw6E3tir2YrmxEAo99nxoL8pdto37KSC32eAGnfv5R1zmHHSx
|
||||||
|
0M3/y2AWiCBTX95EEzdtGC1hK3PBa/qpp/xEmcrsjYN6NXxMAkhC0hMP/HdvqMAg
|
||||||
|
ee7upvaYJsJcl8QLFNayAWr8b8cZA/RBhGEIRl59Eyj6nNtxDt3bCrfe06o1CPCV
|
||||||
|
50/fRZEwFOi/C6GYvPN6MrPZO3ALBWgopLT2yQqycTKtfxYWIdOsMBkAjKf2D6Pk
|
||||||
|
u2mqBsaP4b71jIIeT4euSJLsoJV+O39s8YHXtW8GtOqp7V5kIlnm90lZ9wzeLTZ7
|
||||||
|
HJsD/jEdYto5J3YWm2wwEDccraffJSm7UDtJBvQdIx832kxeFCcGQjW38Zl1qqkg
|
||||||
|
iTH1PLTypxj2ZuviS2EkXVFb/kVU6leWwOt6fqWFC58UvJKeCk/6veazz3PDnTWM
|
||||||
|
92ClUqFd+CZn9VT4CIaJaAc6v5NLpPp+T9sRX9AtequPm7FyTeevY9bElfyk9gW9
|
||||||
|
JDKgKxs6DGWDa16RL5vzwtU+G3o6w6IU+mEwa6/c+hN+pRFs/KBNLLSP9OHBx7BJ
|
||||||
|
X/32Ft+VFhJaK+lQ+f+hve7od/bgKnz4c/Vtp7Dh51DgWgCpBgb8p0vqu02vTnxD
|
||||||
|
BXtDv3h75l5PhvdWfVIzpMWRYFvPR+vJi066FjAz2sjYc0NMLSYtZWyWoIInjhoX
|
||||||
|
Dp5CQujCtw/ZSSlwde1DKEWAW4SeDZAOQNvuz0rU3eosNUJxEmh3aSrcrRtDpw+Y
|
||||||
|
mBUuWAZMpz7njBi7h+JDfmSW/GAaMwrVFC2gef5375R0TejAh+COAjItyoeYEvv8
|
||||||
|
DQd8
|
||||||
|
-----END ENCRYPTED PRIVATE KEY-----
|
||||||
|
`
|
||||||
|
const key = await crypto.keys.import(pem, 'mypassword')
|
||||||
|
expect(key).to.exist()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('can read a private encrypted key (v2 des)', async () => {
|
||||||
|
/*
|
||||||
|
* Generated with
|
||||||
|
* openssl genpkey -algorithm RSA
|
||||||
|
* -pkeyopt rsa_keygen_bits:1024
|
||||||
|
* -pkeyopt rsa_keygen_pubexp:65537
|
||||||
|
* -out foo.pem
|
||||||
|
* openssl pkcs8 -in foo.pem -topk8 -v2 des -passout pass:mypassword
|
||||||
|
*/
|
||||||
|
const pem = `-----BEGIN ENCRYPTED PRIVATE KEY-----
|
||||||
|
MIICwzA9BgkqhkiG9w0BBQ0wMDAbBgkqhkiG9w0BBQwwDgQI0lXp62ozXvwCAggA
|
||||||
|
MBEGBSsOAwIHBAiR3Id5vH0u4wSCAoDQQYOrrkPFPIa0S5fQGXnJw1F/66g92Gs1
|
||||||
|
TkGydn4ouabWb++Vbi2chee1oyZsN2l8YNzDi0Gb2PfjsGpg2aJk0a3/efgA0u6T
|
||||||
|
leEH1dA/7Hr9NVspgHkaXpHt3X6wdbznLYJeAelfj7sDXpOkULGWCkCst0Txb6bi
|
||||||
|
Oxv4c0yYykiuUrp+2xvHbF9c2PrcDb58u/OBZcCg3QB1gTugQKM+ZIBRhcTEFLrm
|
||||||
|
8gWbzBfwYiUm6aJce4zoafP0NSlEOBbpbr73A08Q1IK6pISwltOUhhTvspSZnK41
|
||||||
|
y2CHt5Drnpl1pfOw9Q0svO3VrUP+omxP1SFP17ZfaRGw2uHd08HJZs438x5dIQoH
|
||||||
|
QgjlZ8A5rcT3FjnytSh3fln2ZxAGuObghuzmOEL/+8fkGER9QVjmQlsL6OMfB4j4
|
||||||
|
ZAkLf74uaTdegF3SqDQaGUwWgk7LyualmUXWTBoeP9kRIsRQLGzAEmd6duBPypED
|
||||||
|
HhKXP/ZFA1kVp3x1fzJ2llMFB3m1JBwy4PiohqrIJoR+YvKUvzVQtbOjxtCEAj87
|
||||||
|
JFnlQj0wjTd6lfNn+okewMNjKINZx+08ui7XANNU/l18lHIIz3ssXJSmqMW+hRZ9
|
||||||
|
9oB2tntLrnRMhkVZDVHadq7eMFOPu0rkekuaZm9CO2vu4V7Qa2h+gOoeczYza0H7
|
||||||
|
A+qCKbprxyL8SKI5vug2hE+mfC1leXVRtUYm1DnE+oet99bFd0fN20NwTw0rOeRg
|
||||||
|
0Z+/ZpQNizrXxfd3sU7zaJypWCxZ6TD/U/AKBtcb2gqmUjObZhbfbWq6jU2Ye//w
|
||||||
|
EBqQkwAUXR1tNekF8CWLOrfC/wbLRxVRkayb8bQUfdgukLpz0bgw
|
||||||
|
-----END ENCRYPTED PRIVATE KEY-----
|
||||||
|
`
|
||||||
|
const key = await crypto.keys.import(pem, 'mypassword')
|
||||||
|
expect(key).to.exist()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('can read a private encrypted key (v2 des3)', async () => {
|
||||||
|
/*
|
||||||
|
* Generated with
|
||||||
|
* openssl genpkey -algorithm RSA
|
||||||
|
* -pkeyopt rsa_keygen_bits:1024
|
||||||
|
* -pkeyopt rsa_keygen_pubexp:65537
|
||||||
|
* -out foo.pem
|
||||||
|
* openssl pkcs8 -in foo.pem -topk8 -v2 des3 -passout pass:mypassword
|
||||||
|
*/
|
||||||
|
const pem = `-----BEGIN ENCRYPTED PRIVATE KEY-----
|
||||||
|
MIICxjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQISznrfHd+D58CAggA
|
||||||
|
MBQGCCqGSIb3DQMHBAhx0DnnUvDiHASCAoCceplm+Cmwlgvn4hNsv6e4c/S1iA7w
|
||||||
|
2hU7Jt8JgRCIMWjP2FthXOAFLa2fD4g3qncYXcDAFBXNyoh25OgOwstO14YkxhDi
|
||||||
|
wG4TeppGUt9IlyyCol6Z4WhQs1TGm5OcD5xDta+zBXsBnlgmKLD5ZXPEYB+3v/Dg
|
||||||
|
SvM4sQz6NgkVHN52hchERsnknwSOghiK9mIBH0RZU5LgzlDy2VoBCiEPVdZ7m4F2
|
||||||
|
dft5e82zFS58vwDeNN/0r7fC54TyJf/8k3q94+4Hp0mseZ67LR39cvnEKuDuFROm
|
||||||
|
kLPLekWt5R2NGdunSQlA79BkrNB1ADruO8hQOOHMO9Y3/gNPWLKk+qrfHcUni+w3
|
||||||
|
Ofq+rdfakHRb8D6PUmsp3wQj6fSOwOyq3S50VwP4P02gKcZ1om1RvEzTbVMyL3sh
|
||||||
|
hZcVB3vViu3DO2/56wo29lPVTpj9bSYjw/CO5jNpPBab0B/Gv7JAR0z4Q8gn6OPy
|
||||||
|
qf+ddyW4Kcb6QUtMrYepghDthOiS3YJV/zCNdL3gTtVs5Ku9QwQ8FeM0/5oJZPlC
|
||||||
|
TxGuOFEJnYRWqIdByCP8mp/qXS5alSR4uoYQSd7vZG4vkhkPNSAwux/qK1IWfqiW
|
||||||
|
3XlZzrbD//9IzFVqGRs4nRIFq85ULK0zAR57HEKIwGyn2brEJzrxpV6xsHBp+m4w
|
||||||
|
6r0+PtwuWA0NauTCUzJ1biUdH8t0TgBL6YLaMjlrfU7JstH3TpcZzhJzsjfy0+zV
|
||||||
|
NT2TO3kSzXpQ5M2VjOoHPm2fqxD/js+ThDB3QLi4+C7HqakfiTY1lYzXl9/vayt6
|
||||||
|
DUD29r9pYL9ErB9tYko2rat54EY7k7Ts6S5jf+8G7Zz234We1APhvqaG
|
||||||
|
-----END ENCRYPTED PRIVATE KEY-----
|
||||||
|
`
|
||||||
|
const key = await crypto.keys.import(pem, 'mypassword')
|
||||||
|
expect(key).to.exist()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
@@ -5,49 +5,36 @@ const chai = require('chai')
|
|||||||
const dirtyChai = require('dirty-chai')
|
const dirtyChai = require('dirty-chai')
|
||||||
const expect = chai.expect
|
const expect = chai.expect
|
||||||
chai.use(dirtyChai)
|
chai.use(dirtyChai)
|
||||||
|
const sinon = require('sinon')
|
||||||
|
|
||||||
const fixtures = require('../fixtures/secp256k1')
|
const fixtures = require('../fixtures/secp256k1')
|
||||||
const crypto = require('../../src')
|
const crypto = require('../../src')
|
||||||
|
|
||||||
const mockPublicKey = {
|
|
||||||
bytes: fixtures.pbmPublicKey
|
|
||||||
}
|
|
||||||
|
|
||||||
const mockPrivateKey = {
|
|
||||||
bytes: fixtures.pbmPrivateKey,
|
|
||||||
public: mockPublicKey
|
|
||||||
}
|
|
||||||
|
|
||||||
const mockSecp256k1Module = {
|
|
||||||
generateKeyPair (bits, callback) {
|
|
||||||
callback(null, mockPrivateKey)
|
|
||||||
},
|
|
||||||
|
|
||||||
unmarshalSecp256k1PrivateKey (buf, callback) {
|
|
||||||
callback(null, mockPrivateKey)
|
|
||||||
},
|
|
||||||
|
|
||||||
unmarshalSecp256k1PublicKey (buf) {
|
|
||||||
return mockPublicKey
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('without libp2p-crypto-secp256k1 module present', () => {
|
describe('without libp2p-crypto-secp256k1 module present', () => {
|
||||||
crypto.keys.keys['secp256k1'] = undefined
|
before(() => {
|
||||||
|
sinon.replace(crypto.keys.supportedKeys, 'secp256k1', null)
|
||||||
it('fails to generate a secp256k1 key', (done) => {
|
|
||||||
crypto.keys.generateKeyPair('secp256k1', 256, (err, key) => {
|
|
||||||
expect(err).to.exist()
|
|
||||||
expect(key).to.not.exist()
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('fails to unmarshal a secp256k1 private key', (done) => {
|
after(() => {
|
||||||
crypto.keys.unmarshalPrivateKey(fixtures.pbmPrivateKey, (err, key) => {
|
sinon.restore()
|
||||||
expect(err).to.exist()
|
})
|
||||||
expect(key).to.not.exist()
|
|
||||||
done()
|
it('fails to generate a secp256k1 key', async () => {
|
||||||
})
|
try {
|
||||||
|
await crypto.keys.generateKeyPair('secp256k1', 256)
|
||||||
|
} catch (err) {
|
||||||
|
return // expected
|
||||||
|
}
|
||||||
|
throw new Error('Expected error to be thrown')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('fails to unmarshal a secp256k1 private key', async () => {
|
||||||
|
try {
|
||||||
|
await crypto.keys.unmarshalPrivateKey(fixtures.pbmPrivateKey)
|
||||||
|
} catch (err) {
|
||||||
|
return // expected
|
||||||
|
}
|
||||||
|
throw new Error('Expected error to be thrown')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('fails to unmarshal a secp256k1 public key', () => {
|
it('fails to unmarshal a secp256k1 public key', () => {
|
||||||
@@ -58,42 +45,36 @@ describe('without libp2p-crypto-secp256k1 module present', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe('with libp2p-crypto-secp256k1 module present', () => {
|
describe('with libp2p-crypto-secp256k1 module present', () => {
|
||||||
let key
|
it('generates a valid key', async () => {
|
||||||
|
const key = await crypto.keys.generateKeyPair('secp256k1', 256)
|
||||||
before((done) => {
|
|
||||||
crypto.keys.keys['secp256k1'] = mockSecp256k1Module
|
|
||||||
crypto.keys.generateKeyPair('secp256k1', 256, (err, _key) => {
|
|
||||||
if (err) return done(err)
|
|
||||||
key = _key
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
after((done) => {
|
|
||||||
delete crypto.keys['secp256k1']
|
|
||||||
done()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('generates a valid key', (done) => {
|
|
||||||
expect(key).to.exist()
|
expect(key).to.exist()
|
||||||
done()
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('protobuf encoding', (done) => {
|
it('protobuf encoding', async () => {
|
||||||
|
const key = await crypto.keys.generateKeyPair('secp256k1', 256)
|
||||||
|
expect(key).to.exist()
|
||||||
|
|
||||||
const keyMarshal = crypto.keys.marshalPrivateKey(key)
|
const keyMarshal = crypto.keys.marshalPrivateKey(key)
|
||||||
crypto.keys.unmarshalPrivateKey(keyMarshal, (err, key2) => {
|
const key2 = await crypto.keys.unmarshalPrivateKey(keyMarshal)
|
||||||
if (err) return done(err)
|
const keyMarshal2 = crypto.keys.marshalPrivateKey(key2)
|
||||||
const keyMarshal2 = crypto.keys.marshalPrivateKey(key2)
|
|
||||||
|
|
||||||
expect(keyMarshal).to.eql(keyMarshal2)
|
expect(keyMarshal).to.eql(keyMarshal2)
|
||||||
|
|
||||||
const pk = key.public
|
const pk = key.public
|
||||||
const pkMarshal = crypto.keys.marshalPublicKey(pk)
|
const pkMarshal = crypto.keys.marshalPublicKey(pk)
|
||||||
const pk2 = crypto.keys.unmarshalPublicKey(pkMarshal)
|
const pk2 = crypto.keys.unmarshalPublicKey(pkMarshal)
|
||||||
const pkMarshal2 = crypto.keys.marshalPublicKey(pk2)
|
const pkMarshal2 = crypto.keys.marshalPublicKey(pk2)
|
||||||
|
|
||||||
expect(pkMarshal).to.eql(pkMarshal2)
|
expect(pkMarshal).to.eql(pkMarshal2)
|
||||||
done()
|
})
|
||||||
})
|
|
||||||
|
it('unmarshals a secp256k1 private key', async () => {
|
||||||
|
const key = await crypto.keys.unmarshalPrivateKey(fixtures.pbmPrivateKey)
|
||||||
|
expect(key).to.exist()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('unmarshals a secp256k1 public key', () => {
|
||||||
|
const key = crypto.keys.unmarshalPublicKey(fixtures.pbmPublicKey)
|
||||||
|
expect(key).to.exist()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
3
test/node.js
Normal file
3
test/node.js
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
'use strict'
|
||||||
|
|
||||||
|
require('./keys/rsa-crypto-libs')
|
Reference in New Issue
Block a user