Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I encrypt data with a public key in Node.js? [duplicate]

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?

like image 750
teerapap Avatar asked Oct 15 '11 16:10

teerapap


People also ask

Can you encrypt with a 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.

Can a file be encrypt with multiple public keys?

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.

How do you encrypt data in node JS?

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.


2 Answers

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);
like image 69
Jalaleddin Hosseini Avatar answered Oct 28 '22 06:10

Jalaleddin Hosseini


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
like image 43
thejh Avatar answered Oct 28 '22 05:10

thejh