This repository was archived by the owner on Jun 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
Merged
CMS - PKCS #7 #19
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
481dab6
test: decrypting CMS
richardschneider c7182bc
feat: cryptographically protected messages (aka PKCS 7 and RFC 5652)
richardschneider 83fbdc4
chore: linting
richardschneider ecb25b8
test(cms.encrypt): requires a key and a buffer
richardschneider 482b38f
feat: create protected data
richardschneider 8030d33
docs(readme): talk about CMS
richardschneider c5954e4
feat: read protected data
richardschneider 1d25d67
docs: about cms
richardschneider 074cfa5
feat: faster crypto, so up the PBKDF2 iteration count to current NIST…
richardschneider 321682d
chore: coverage not needed in Travis, Circle CI does it
richardschneider ae3e4d5
rollback deepmerge
daviddias File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,142 @@ | ||
'use strict' | ||
|
||
const async = require('async') | ||
const forge = require('node-forge') | ||
const util = require('./util') | ||
|
||
/** | ||
* Cryptographic Message Syntax (aka PKCS #7) | ||
* | ||
* CMS describes an encapsulation syntax for data protection. It | ||
* is used to digitally sign, digest, authenticate, or encrypt | ||
* arbitrary message content. | ||
* | ||
* See RFC 5652 for all the details. | ||
*/ | ||
class CMS { | ||
/** | ||
* Creates a new instance with a keychain | ||
* | ||
* @param {Keychain} keychain - the available keys | ||
*/ | ||
constructor (keychain) { | ||
if (!keychain) { | ||
throw new Error('keychain is required') | ||
} | ||
|
||
this.keychain = keychain | ||
} | ||
|
||
/** | ||
* Creates some protected data. | ||
* | ||
* The output Buffer contains the PKCS #7 message in DER. | ||
* | ||
* @param {string} name - The local key name. | ||
* @param {Buffer} plain - The data to encrypt. | ||
* @param {function(Error, Buffer)} callback | ||
* @returns {undefined} | ||
*/ | ||
encrypt (name, plain, callback) { | ||
const self = this | ||
const done = (err, result) => async.setImmediate(() => callback(err, result)) | ||
|
||
if (!Buffer.isBuffer(plain)) { | ||
return done(new Error('Plain data must be a Buffer')) | ||
} | ||
|
||
async.series([ | ||
(cb) => self.keychain.findKeyByName(name, cb), | ||
(cb) => self.keychain._getPrivateKey(name, cb) | ||
], (err, results) => { | ||
if (err) return done(err) | ||
|
||
let key = results[0] | ||
let pem = results[1] | ||
try { | ||
const privateKey = forge.pki.decryptRsaPrivateKey(pem, self.keychain._()) | ||
util.certificateForKey(key, privateKey, (err, certificate) => { | ||
if (err) return callback(err) | ||
|
||
// create a p7 enveloped message | ||
const p7 = forge.pkcs7.createEnvelopedData() | ||
p7.addRecipient(certificate) | ||
p7.content = forge.util.createBuffer(plain) | ||
p7.encrypt() | ||
|
||
// convert message to DER | ||
const der = forge.asn1.toDer(p7.toAsn1()).getBytes() | ||
done(null, Buffer.from(der, 'binary')) | ||
}) | ||
} catch (err) { | ||
done(err) | ||
} | ||
}) | ||
} | ||
|
||
/** | ||
* Reads some protected data. | ||
* | ||
* The keychain must contain one of the keys used to encrypt the data. If none of the keys | ||
* exists, an Error is returned with the property 'missingKeys'. It is array of key ids. | ||
* | ||
* @param {Buffer} cmsData - The CMS encrypted data to decrypt. | ||
* @param {function(Error, Buffer)} callback | ||
* @returns {undefined} | ||
*/ | ||
decrypt (cmsData, callback) { | ||
const done = (err, result) => async.setImmediate(() => callback(err, result)) | ||
|
||
if (!Buffer.isBuffer(cmsData)) { | ||
return done(new Error('CMS data is required')) | ||
} | ||
|
||
const self = this | ||
let cms | ||
try { | ||
const buf = forge.util.createBuffer(cmsData.toString('binary')) | ||
const obj = forge.asn1.fromDer(buf) | ||
cms = forge.pkcs7.messageFromAsn1(obj) | ||
} catch (err) { | ||
return done(new Error('Invalid CMS: ' + err.message)) | ||
} | ||
|
||
// Find a recipient whose key we hold. We only deal with recipient certs | ||
// issued by ipfs (O=ipfs). | ||
const recipients = cms.recipients | ||
.filter(r => r.issuer.find(a => a.shortName === 'O' && a.value === 'ipfs')) | ||
.filter(r => r.issuer.find(a => a.shortName === 'CN')) | ||
.map(r => { | ||
return { | ||
recipient: r, | ||
keyId: r.issuer.find(a => a.shortName === 'CN').value | ||
} | ||
}) | ||
async.detect( | ||
recipients, | ||
(r, cb) => self.keychain.findKeyById(r.keyId, (err, info) => cb(null, !err && info)), | ||
(err, r) => { | ||
if (err) return done(err) | ||
if (!r) { | ||
const missingKeys = recipients.map(r => r.keyId) | ||
err = new Error('Decryption needs one of the key(s): ' + missingKeys.join(', ')) | ||
err.missingKeys = missingKeys | ||
return done(err) | ||
} | ||
|
||
async.waterfall([ | ||
(cb) => self.keychain.findKeyById(r.keyId, cb), | ||
(key, cb) => self.keychain._getPrivateKey(key.name, cb) | ||
], (err, pem) => { | ||
if (err) return done(err) | ||
|
||
const privateKey = forge.pki.decryptRsaPrivateKey(pem, self.keychain._()) | ||
cms.decrypt(r.recipient, privateKey) | ||
done(null, Buffer.from(cms.content.getBytes(), 'binary')) | ||
}) | ||
} | ||
) | ||
} | ||
} | ||
|
||
module.exports = CMS |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
'use strict' | ||
|
||
const forge = require('node-forge') | ||
const pki = forge.pki | ||
exports = module.exports | ||
|
||
/** | ||
* Gets a self-signed X.509 certificate for the key. | ||
* | ||
* The output Buffer contains the PKCS #7 message in DER. | ||
* | ||
* TODO: move to libp2p-crypto package | ||
* | ||
* @param {KeyInfo} key - The id and name of the key | ||
* @param {RsaPrivateKey} privateKey - The naked key | ||
* @param {function(Error, Certificate)} callback | ||
* @returns {undefined} | ||
*/ | ||
exports.certificateForKey = (key, privateKey, callback) => { | ||
const publicKey = pki.setRsaPublicKey(privateKey.n, privateKey.e) | ||
const cert = pki.createCertificate() | ||
cert.publicKey = publicKey | ||
cert.serialNumber = '01' | ||
cert.validity.notBefore = new Date() | ||
cert.validity.notAfter = new Date() | ||
cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 10) | ||
const attrs = [{ | ||
name: 'organizationName', | ||
value: 'ipfs' | ||
}, { | ||
shortName: 'OU', | ||
value: 'keystore' | ||
}, { | ||
name: 'commonName', | ||
value: key.id | ||
}] | ||
cert.setSubject(attrs) | ||
cert.setIssuer(attrs) | ||
cert.setExtensions([{ | ||
name: 'basicConstraints', | ||
cA: true | ||
}, { | ||
name: 'keyUsage', | ||
keyCertSign: true, | ||
digitalSignature: true, | ||
nonRepudiation: true, | ||
keyEncipherment: true, | ||
dataEncipherment: true | ||
}, { | ||
name: 'extKeyUsage', | ||
serverAuth: true, | ||
clientAuth: true, | ||
codeSigning: true, | ||
emailProtection: true, | ||
timeStamping: true | ||
}, { | ||
name: 'nsCertType', | ||
client: true, | ||
server: true, | ||
email: true, | ||
objsign: true, | ||
sslCA: true, | ||
emailCA: true, | ||
objCA: true | ||
}]) | ||
// self-sign certificate | ||
cert.sign(privateKey) | ||
|
||
return callback(null, cert) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Doesn't seem that coverage got added to Circle https://github.com/libp2p/js-libp2p-keychain/blob/master/circle.yml