encrypt
Encrypts plaintext with a key and an optional nonce.
encryptkey, [ nonce,] plaintextenvelope
name | type | description |
---|---|---|
key | Key to be used in the encryption operation. | |
nonce | Helps to prevent replay attacks. If you don’t provide a nonce, Confidential generates one for you. | |
plaintext | Value wrapper for the plaintext to be encrypted. | |
envelope | Wrapper for the ciphertext and nonce products of encryption. Suitable for use with decrypt. |
encrypt
is a generic function, accepting an encryption key and plaintext to return a ciphertext wrapper that can be decrypted with decrypt
.
-
When given a
SymmetricKey
,encrypt
uses symmetric encryption. -
When given a
SharedKey
,encrypt
uses authenticated, asymmetric encryption.
Warning: Signing key pairs are incompatible with
encrypt
and causesencrypt
to throw.
You may use an existing nonce (such as a counter), using Nonce.from
. The nonce must be nacl.box.nonceLength
bytes long.
Warning: Re-using a nonce can compromise your private keys.
The plaintext must be first placed in a Message
container using the Message.from
class method.
encrypt
returns a Promise
that yields Envelope
, which encapsulates the ciphertext and nonce. This container may be passed to decrypt
to recover the original plaintext. You may format the envelope using Envelope::to
.
Examples
Symmetric Encryption
Warning: Private keys should only be accessible to their owners.
import {confidential} from "panda-confidential"
{encrypt, Message} = confidential()
import {keyLookup, write} from "my-library"
do ->
alice = keyLookup "Alice/private"
plaintext = Message.from "utf8", "Hello, Alice!"
envelope = await encrypt alice, plaintext
# You may serialize with the instance method `to`
write "greeting", envelope.to "base64"
Asymmetric Encryption
Warning: Private keys should only be accessible to their owners.
import {confidential} from "panda-confidential"
{SharedKey, encrypt, Message} = confidential()
import {keyLookup, send} from "my-library"
do ->
alice = keyLookup "Alice/private"
bob = keyLookup "Bob/public"
fromAliceToBob = sharedKey.create alice, bob
plaintext = Message.from "utf8", "Hello, Bob!"
envelope = await encrypt fromAliceToBob, plaintext
# You may serialize with the instance method `to`
send "Bob", envelope.to "base64"