@xeredo/easy-crypto
Opinionated crypto library building only on node's native crypto module
Usage
const ec = require('@xeredo/easy-crypto')
// generate a keypair
const pair = ec.generateKeyPair('rsa', 4096)
// store it on disk, encrypted with the machine id
// (this isn't strong security, but it prevents people just stealing your files from using the key)
pair.exportToFile('private.pem', ec.machineId)
pair.pub.exportToFile('public.pem')
// encrypt and decrypt something
const data = 'keyboardcat'
// pair.encrypt is an alias for pair.pub.encrypt
const encrypted = pair.encrypt(data)
const decrypted = pair.decrypt(encrypted)
console.log('decrypted: %s', decrypted)
// sign & verify something
const signature = pair.sign(data)
// pair.verify is an alias for pair.pub.verify
const isValid = pair.verify(data, signature)
console.log('is valid signature: %s', isValid)
// load the key
const fromDisk = ec.private.fromFile('private.pem', ec.machineId,
ec.public.fromFile('public.pem'))
API
-
generateKeyPair(type<string>, modulusLength<number>, extraOptions = {})
- Generates a new key pair
- Returns a PrivateKey object
- For more info see https://nodejs.org/api/crypto.html#crypto_crypto_generatekeypairsync_type_options
-
public
PublicKey class-
.fromFile(file<string<y)
- Load a public key from a file sync
- Returns a PublicKey object
-
.fromBuffer(buffer<Buffer>)
- Load a public key from a PEM encoded buffer
- Returns a PublicKey object
-
.fromDERBuffer(buffer<Buffer>)
- Load a public key from a DER encoded buffer
- Returns a PublicKey object
-
.fromKeyObject(key<KeyObject>)
- Wraps a crypto.KeyObject
- Returns a PublicKey object
-
-
private
PrivateKey class-
.fromFile(file<string>, passphrase<string, Buffer>, pub<PublicKey>)
- Load a private key from a file sync
- Returns a PrivateKey object
-
.fromBuffer(buffer<Buffer>, passphrase<string, Buffer>, pub<PublicKey>)
- Load a private key from a PEM encoded buffer
- Returns a PrivateKey object
-
.fromDERBuffer(buffer<Buffer>, passphrase<string, Buffer>, pub<PublicKey>)
- Load a private key from a DER encoded buffer
- Returns a PrivateKey object
-
.fromKeyObject(key<KeyObject>, pub<PublicKey>)
- Wraps a crypto.KeyObject
- Returns a PrivateKey object
-
-
machineId
- On Linux: Contains the value of
/etc/machine-id
- On Linux: Contains the value of
PublicKey
-
.verify(data<string, Buffer>, signature<Buffer>)
- Verify if the signature is valid for the data
-
.encrypt(data<string, Buffer>)
- Encrypt data
-
.spkiFingerprint(hexString<bool> = true)
- Get spki fingerprint
- NOTE: This is not the default RSA PKCS#11 fingerprint. It uses SPKI as key format instead
PrivateKey
-
.sign(data<string, Buffer>)
- Sign data
-
.decrypt(data)
- Decrypt encrypted data
-
.verify(data<string, Buffer>, signature<Buffer>)
- Alias
.pub.verify
- Alias
-
.encrypt(data<string, Buffer>)
- Alias
.pub.encrypt
- Alias