In crypto, I see only Signer/Verifier for doing digital signature and Cipher/Decipher with symmetric key encryption.
How do I encrypt data with public key?
The other key is distributed to anyone who wants it; this key is the public key. Anyone can encrypt a message by using your public key, but only you can read it. When you receive the message, you decrypt it by using your private key.
Yes, any of the recipient keys will be able to decrypt the message. Strictly speaking, the message is encrypted using a common key, and that key is encrypted using each provided public key. Thus any of the corresponding private keys can decrypt the common key and then the message.
Using Clean architecture for Node.NodeJS provides inbuilt library crypto to encrypt and decrypt data in NodeJS. We can use this library to encrypt data of any type. You can do the cryptographic operations on a string, buffer, and even a stream of data. The crypto also holds multiple crypto algorithms for encryption.
As mentioned in the official nodejs api docs here: crypto.publicEncrypt(key, buffer)
Encrypts the content of buffer with key and returns a new Buffer with encrypted content. The returned data can be decrypted using the corresponding private key, for example using crypto.privateDecrypt().
If key is not a KeyObject, this function behaves as if key had been passed to crypto.createPublicKey(). If it is an object, the padding property can be passed. Otherwise, this function uses RSA_PKCS1_OAEP_PADDING.
Because RSA public keys can be derived from private keys, a private key may be passed instead of a public key.
So the answer is:
var encrypted = crypto.publicEncrypt(publicKey, buffer);
You might be interested in my NaCl bindings. From its API:
// Encrypt and sign
box(message, nonce, pubkey, privkey)
// Decrypt and validate
unbox(box, nonce, pubkey, privkey)
// Generates a new keypair, returns {private: <buffer>, public: <buffer>}
boxKeypair()
// Lengths of nonces and public and private keys in bytes
// { nonce: x, pubkey: x, privkey: x }
lengths.box
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With