Wrap a pair of sodium keys for asymmetric encryption. You should pass your private key and the public key of the person that you are communicating with.
Arguments
- pub
A sodium public key. This is either a raw vector of length 32 or a path to file containing the contents of the key (written by
writeBin()
).- key
A sodium private key. This is either a raw vector of length 32 or a path to file containing the contents of the key (written by
writeBin()
).- authenticated
Logical, indicating if authenticated encryption (via
sodium::auth_encrypt()
/sodium::auth_decrypt()
) should be used. IfFALSE
thensodium::simple_encrypt()
/sodium::simple_decrypt()
will be used. The difference is that withauthenticated = TRUE
the message is signed with your private key so that tampering with the message will be detected.
Details
NOTE: the order here (pub, key) is very important; if the wrong order is used you cannot decrypt things. Unfortunately because sodium keys are just byte sequences there is nothing to distinguish the public and private keys so this is a pretty easy mistake to make.
See also
keypair_openssl()
for a similar function using
openssl keypairs
Examples
# Generate two keypairs, one for Alice, and one for Bob
key_alice <- sodium::keygen()
pub_alice <- sodium::pubkey(key_alice)
key_bob <- sodium::keygen()
pub_bob <- sodium::pubkey(key_bob)
# Alice wants to send Bob a message so she creates a key pair with
# her private key and bob's public key (she does not have bob's
# private key).
pair_alice <- cyphr::keypair_sodium(pub = pub_bob, key = key_alice)
# She can then encrypt a secret message:
secret <- cyphr::encrypt_string("hi bob", pair_alice)
secret
#> [1] 27 96 08 c3 17 4e ca 34 80 71 82 23 56 fc 9a 35 f0 c2 e3 03 da a6 b9 66 e9
#> [26] 93 c1 b1 8a 7c 97 b6 ad da 08 88 dd 5a 7d 74 de 7c 03 3c 50 b5
# Bob wants to read the message so he creates a key pair using
# Alice's public key and his private key:
pair_bob <- cyphr::keypair_sodium(pub = pub_alice, key = key_bob)
cyphr::decrypt_string(secret, pair_bob)
#> [1] "hi bob"