# Introduction

#### 2021-05-17

This package tries to smooth over some of the differences in encryption approaches (symmetric vs. asymmetric, sodium vs. openssl) to provide a simple interface for users who just want to encrypt or decrypt things.

The scope of the package is to protect data that has been saved to disk. It is not designed to stop an attacker targeting the R process itself to determine the contents of sensitive data. The package does try to prevent you accidentally saving to disk the contents of sensitive information, including the keys that could decrypt such information.

This vignette works through the basic functionality of the package. It does not offer much in the way of an introduction to encryption itself; for that see the excellent vignettes in the openssl and sodium packages (see vignette("crypto101") and vignette("bignum") for information about how encryption works). This package is a wrapper around those packages in order to make them more accessible.

# Keys and the like

To encrypt anything we need a key. There are two sorts of key “types” we will concern ourselves with here “symmetric” and “asymmetric”.

• “symmetric” keys are used for storing secrets that multiple people need to access. Everyone has the same key (which is just a bunch of bytes) and with that we can either encrypt data or decrypt it.

• a “key pair” is a public and a private key; this is used in communication. You hold a private key that nobody else ever sees and a public key that you can copy around all over the show. These can be used for a couple of different patterns of communication (see below).

We support symmetric keys and asymmetric key pairs from the openssl and sodium packages (which wrap around industry-standard cryptographic libraries) - this vignette will show how to create and load keys of different types as they’re used.

The openssl keys have the advantage of a standard key format, and that many people (especially on Linux and macOS) have a keypair already (see below if you’re not sure if you do). The sodium keys have the advantage of being a new library, starting from a clean slate rather than carrying with it accumulated ideas from the last 20 years of development.

The idea in cyphr is that we can abstract away some differences in the types of keys and the functions that go with them to create a standardised interface to encrypting and decrypting strings, R objects, files and raw vectors. With that, we can then create wrappers around functions that create files and simplify the process of adding encryption into a data workflow.

Below, I’ll describe the sorts of keys that cyphr supports and in the sections following describe how these can be used to actually do some encryption.

## Symmetric encryption

This is the simplest form of encryption because everyone has the same key (like a key to your house or a single password). This raises issues (like how do you store the key without other people reading it) but we can deal with that below.

### openssl

To generate a key with openssl, you can use:

k <- openssl::aes_keygen()

which generates a raw vector

k
## aes 92:09:17:41:61:66:af:35:5b:f2:2d:20:62:5b:c3:07

(this prints nicely but it really is stored as a 16 byte raw vector).

The encryption functions that this key supports are openssl::aes_cbc_encrypt, openssl::aes_ctr_encrypt and openssl::aes_gcm_encrypt (along with the corresponding decryption functions). The cyphr package tries to abstract this away by using a wrapper cyphr::key_openssl

key <- cyphr::key_openssl(k)
key
## <cyphr_key: openssl>

With this key, one can encrypt a string with cyphr::encrypt_string:

secret <- cyphr::encrypt_string("my secret string", key)

and decrypt it again with cyphr::decrypt_string:

cyphr::decrypt_string(secret, key)
## [1] "my secret string"

See below for more functions that use these key objects.

### sodium

The interface is almost identical using sodium symmetric keys. To generate a symmetric key with libsodium you would use sodium::keygen

k <- sodium::keygen()

This is really just a raw vector of length 32, without even any class attribute!

The encryption functions that this key supports are sodium::data_encrypt and sodium::data_decrypt. To create a key for use with cyphr that knows this, use:

key <- cyphr::key_sodium(k)
key
## <cyphr_key: sodium>

This key can then be used with the high-level cyphr encryption functions described below.

## Asymmetric encryption (“key pairs”)

With asymmetric encryption everybody has two keys that differ from everyone else’s key. One key is public and can be shared freely with anyone you would like to communicate with and the other is private and must never be disclosed.

In the sodium package there is a vignette (vignette("crypto101")) that gives a gentle introduction to how this all works. In practice, you end up creating a pair of keys for yourself. Then to encrypt or decrypt something you encrypt messages with the recipient’s public key and they (and only they) can decrypt it with their private key.

One use for asymmetric encryption is to encrypt a shared secret (such as a symmetric key) - with this you can then safely store or communicate a symmetric key without disclosing it.

### openssl

Let’s suppose that we have two parties “Alice” and “Bob” who want to talk with one another. For demonstration purposes we need to generate SSH keys (with no password) in temporary directories (to comply with CRAN policies). In a real situation these would be on different machines (Alice has no access to Bob’s key!) and these keys would be password protected.

path_key_alice <- cyphr::ssh_keygen(password = FALSE)
path_key_bob <- cyphr::ssh_keygen(password = FALSE)

Note that each directory contains a public key (id_rsa.pub) and a private key (id_rsa).

dir(path_key_alice)
## [1] "id_rsa"     "id_rsa.pub"
dir(path_key_bob)
## [1] "id_rsa"     "id_rsa.pub"

Below, the full path to the key (e.g., .../id_rsa) could be used in place of the directory name if you prefer.

If Alice wants to send a message to Bob she needs to use her private key and his public key

pair_a <- cyphr::keypair_openssl(path_key_bob, path_key_alice)
pair_a
## <cyphr_keypair: openssl>

with this pair she can write a message to “bob”:

secret <- cyphr::encrypt_string("secret message", pair_a)

The secret is now just a big pile of bytes

secret
##   [1] 58 0a 00 00 00 03 00 04 00 05 00 03 05 00 00 00 00 05 55 54 46 2d 38 00 00
##  [26] 02 13 00 00 00 04 00 00 00 18 00 00 00 10 72 4f 1c 81 9d 6f ba a7 50 64 20
##  [51] ca 57 ef c1 68 00 00 00 18 00 00 01 00 20 36 4d 02 d1 ea 7a 09 18 19 88 63
##  [76] 0b 20 19 2c 62 eb db 36 27 7e 58 61 f3 3d 84 ef 78 fb 03 ea b6 1a fb 59 0b
## [101] ad 5c 34 69 f3 b1 4c cc f7 e3 42 1f dd 4c 75 1d ed e0 ae c0 8f e4 29 a7 2e
## [126] ed f5 f2 a9 7d ad 1b 2f b6 f8 d7 12 45 31 6a 98 bc 8a cf e6 df d9 74 8b 27
## [151] 0b 2e 3e 1f 3c 57 e8 2c 07 11 e8 b7 67 7c 1c 73 e6 29 2d 93 e4 2a 8d c9 c2
## [176] c5 c9 d4 c6 27 af a9 ea c5 03 71 96 c2 ea 92 d5 06 75 03 03 09 82 28 b8 4e
## [201] ba d1 54 0c 29 c2 92 cc 1d 73 19 7f 32 e9 2d 12 1c f3 92 71 ec 27 09 c1 fd
## [226] e0 92 e0 56 90 b1 af 7f 66 f8 31 1d 8c aa 9c fa d6 ac 60 d1 2b ce 5c 50 76
## [251] fd 89 1f 4a 5a be de c1 fa 2b 5f 74 5e 79 07 74 47 5d 63 7f 56 23 24 44 06
## [276] c3 6f ce c7 57 2d 79 15 85 1b a5 aa 6b 26 9b b4 58 ee 0b 94 29 9d 62 ed 65
## [301] 27 8e 9b b1 8b 44 07 f4 4f b0 35 63 72 eb d7 c6 38 c7 15 00 00 00 18 00 00
## [326] 00 10 48 ab 14 fb 07 82 5d 11 89 8d 21 d3 80 90 a0 c3 00 00 00 18 00 00 01
## [351] 00 54 d8 1d b9 c2 8c 85 15 04 f6 3a 89 75 34 1a 88 d2 dd ea ec 40 30 33 5f
## [376] 28 74 cc 2d 5e cd 83 90 05 1f 2b 8c b4 5d bc 9c 23 ca 56 d7 c6 f7 ce 4d 69
## [401] ef f2 19 4e fa 03 39 54 1f 0b 23 77 bd 26 79 82 63 87 1a 24 4e 1d 96 57 e4
## [426] 7f 7d 17 20 fe 49 8f 4d 98 72 e2 91 be 87 47 06 a6 56 0e a2 f1 18 e9 ab 10
## [451] cd d3 fb 7a 7c b7 1e 71 09 62 49 64 67 e4 3d 8a 29 c7 76 cc ff 2e 14 15 69
## [476] 06 af 74 9e 54 7d b5 3e 0e f4 c7 69 b7 fd 4c aa 06 af c9 ea 3f 01 99 23 48
## [501] 72 52 0c f4 a8 62 e2 12 5e fb bb 0b 3d 48 fe c3 a7 1f 06 5d ed dc 6d 0c 33
## [526] e5 c7 2e 6d eb 3d ce fb bb 6d 1b fd f9 ee 4b 0a 60 d0 9d 69 40 55 a4 55 95
## [551] 58 17 a3 1e 73 b7 d1 bd fc 52 b6 6f 7b 14 a5 3d 1e 4e 18 8d 34 ca 50 47 15
## [576] 7b 73 61 38 64 d5 d6 23 6c 8a d8 b2 18 46 1f 33 f9 25 82 f4 17 e2 34 9a c8
## [601] 84 c6 2e bf 37 8e 8e 00 00 04 02 00 00 00 01 00 04 00 09 00 00 00 05 6e 61
## [626] 6d 65 73 00 00 00 10 00 00 00 04 00 04 00 09 00 00 00 02 69 76 00 04 00 09
## [651] 00 00 00 07 73 65 73 73 69 6f 6e 00 04 00 09 00 00 00 04 64 61 74 61 00 04
## [676] 00 09 00 00 00 09 73 69 67 6e 61 74 75 72 65 00 00 00 fe

Note that unlike symmetric encryption above, Alice cannot decrypt her own message:

cyphr::decrypt_string(secret, pair_a)
## Error: OpenSSL error in RSA_padding_check_PKCS1_type_2: pkcs decoding error

For Bob to read the message, he uses his private key and Alice’s public key (which she has transmitted to him previously).

pair_b <- cyphr::keypair_openssl(path_key_alice, path_key_bob)

With this keypair, Bob can decrypt Alice’s message

cyphr::decrypt_string(secret, pair_b)
## [1] "secret message"

And send one back of his own:

secret2 <- cyphr::encrypt_string("another message", pair_b)
secret2
##   [1] 58 0a 00 00 00 03 00 04 00 05 00 03 05 00 00 00 00 05 55 54 46 2d 38 00 00
##  [26] 02 13 00 00 00 04 00 00 00 18 00 00 00 10 b2 c3 3a 71 f3 1a 0a 6f 48 00 96
##  [51] ba c4 66 20 24 00 00 00 18 00 00 01 00 01 cb 90 5f 2c 15 5c 74 15 db 04 6d
##  [76] 28 ce 36 06 0a 44 3b ce 3e 41 22 27 20 a8 98 c3 d6 76 8a d8 ff ef fe c7 19
## [101] 66 49 2f 86 bb 05 27 4d c7 f3 31 b6 17 31 fe c4 38 60 9e c9 f5 b3 4b 48 25
## [126] e5 51 ed 81 0e 3a 3a 71 53 e2 2c 19 c6 e3 f4 6f e2 3b 6d f1 d5 0e 51 00 ee
## [151] 82 47 20 d7 33 56 e0 40 f5 56 aa 70 89 e7 5f d4 65 b6 0e 0a d3 ac 36 b0 ad
## [176] d4 ac 4e 3c 0a 9d 03 16 f1 76 60 07 27 59 42 5f b6 01 cd e6 ef 3e a1 9e 44
## [201] 1c e5 2e 38 75 da 1b d5 bf 1c 56 56 ab 58 ed 10 ae 21 10 3b 16 1a d1 5f f3
## [226] ea 92 e4 90 01 53 77 50 73 26 5a 4f 77 27 af 0e f1 9b 9d 76 71 0a de 65 41
## [251] 16 5c b1 2f 0a 81 8d bc 4c a5 d5 df 81 5b 6f df b5 9e eb 2f 22 f1 e1 e5 20
## [276] 96 d4 54 48 6e ef f0 de 2e 9e 08 65 d8 9b 88 a2 47 1e e1 9e a2 48 2c c9 f6
## [301] 65 2b 99 32 08 13 71 2c d1 a0 32 77 46 3b d0 c1 03 cc 70 00 00 00 18 00 00
## [326] 00 10 8e 5d e7 6c e8 ea 8b 30 4a c9 1a b3 90 b6 d0 e7 00 00 00 18 00 00 01
## [351] 00 9c e2 8d 2d b2 63 f2 ab 46 df 9f 2f f3 92 2c 08 f0 55 43 dc 53 4e 0e ad
## [376] 1d 55 87 1f 4b 92 62 42 8a 45 75 ff 6d 0b 40 1e 21 c7 6b 52 4a ac a5 1c 84
## [401] 6a 57 46 4f 49 ec f9 bf f9 f5 6e 7f 82 8f d6 c4 a3 c5 a3 02 1a 9f 8f 27 75
## [426] 8e a6 7f b1 d5 b8 f2 da f9 3f f8 ef 71 47 c9 6d b9 b9 52 0c 61 3a 6f ec c0
## [451] 57 85 a0 f7 11 4c de db fd 08 e7 5e c5 30 04 3b 7c 9a 17 b0 7f 6f 9d 97 37
## [476] 14 50 0b 68 51 d4 18 84 60 92 59 81 d4 4b 05 0f d3 3f 80 21 6d ef 92 a9 bf
## [501] 0c 55 34 1b 39 ee 4b 64 2e ad 8e 66 d0 ce 32 09 16 b0 ab 0c a9 61 14 2d 85
## [526] a2 c1 22 e0 cc 53 29 f4 bb 9b b2 03 a7 52 4f 4f 32 2f 18 a8 b8 cd 01 5a a7
## [551] 02 4d 1d 56 67 b4 d4 84 7a 6e 08 15 e7 0f b7 86 8b d7 79 ec d2 f4 12 ba 7e
## [576] bf a7 58 2f 23 e3 d9 06 76 9f 78 d1 09 92 a9 65 23 8c 7d c0 e1 4a 2b 8c 6c
## [601] 87 b9 07 e2 fd 8b 8f 00 00 04 02 00 00 00 01 00 04 00 09 00 00 00 05 6e 61
## [626] 6d 65 73 00 00 00 10 00 00 00 04 00 04 00 09 00 00 00 02 69 76 00 04 00 09
## [651] 00 00 00 07 73 65 73 73 69 6f 6e 00 04 00 09 00 00 00 04 64 61 74 61 00 04
## [676] 00 09 00 00 00 09 73 69 67 6e 61 74 75 72 65 00 00 00 fe

which she can decrypt

cyphr::decrypt_string(secret2, pair_a)
## [1] "another message"

Chances are, you have an openssl keypair in your .ssh/ directory. If so, you would pass NULL as the path for the private (or less usefully, the public) key pair part. So to send a message to Bob, we’d include the path to Bob’s public key.

pair_us <- cyphr::keypair_openssl(path_key_bob, NULL)

This all skips over how Alice and Bob will exchange this secret information. Because the secret is bytes, it’s a bit odd to work with. Alice could save the secret to disk with

secret <- cyphr::encrypt_string("secret message", pair_a)
path_for_bob <- file.path(tempdir(), "for_bob_only")
writeBin(secret, path_for_bob)

And then send Bob the file for_bob_only (over email or any other insecure medium).

and bob could read the secret in with:

secret <- readBin(path_for_bob, raw(), file.size(path_for_bob))
cyphr::decrypt_string(secret, pair_b)
## [1] "secret message"

As an alternative, you can “base64 encode” the bytes into something that you can just email around:

secret_base64 <- openssl::base64_encode(secret)
secret_base64
## [1] "WAoAAAADAAQABQADBQAAAAAFVVRGLTgAAAITAAAABAAAABgAAAAQOWanYMPpixlX3lVur9PA5AAAABgAAAEAFnfYPaZNiyuahIGW/sELsPnf07Py21k2RMQDVWcF6tJxFFwgwF5yhD+w/iR1fz/SrUJ5c22jOzzHfEwZgfEhiPTlPF4YQqRawGko2uLPI8R/wqiOnxaiyETJLyNiTdS1r5HdxWHjgPaEshf+mh6ONCJzT/IlY/Zxwjuv4/iSgaXDoSad+CMjKZdkyebfSu9SMbXRz9dEw3c6kIdPHShZS3vNizDydjX5jCnKtrc5MVYgAck0D30NRmvS/2J+p6YeUtVKtCezo4+n281000d+5nTRR2stim7G/fTgNuGIUmGbuA/CnHTOQ3iSPOUIL0G19ITQLwjhmqasDrP1zfTYaAAAABgAAAAQFhQL0pNm859jgnLbNLUNLQAAABgAAAEAVNgducKMhRUE9jqJdTQaiNLd6uxAMDNfKHTMLV7Ng5AFHyuMtF28nCPKVtfG985Nae/yGU76AzlUHwsjd70meYJjhxokTh2WV+R/fRcg/kmPTZhy4pG+h0cGplYOovEY6asQzdP7eny3HnEJYklkZ+Q9iinHdsz/LhQVaQavdJ5UfbU+DvTHabf9TKoGr8nqPwGZI0hyUgz0qGLiEl77uws9SP7Dpx8GXe3cbQwz5ccubes9zvu7bRv9+e5LCmDQnWlAVaRVlVgXox5zt9G9/FK2b3sUpT0eThiNNMpQRxV7c2E4ZNXWI2yK2LIYRh8z+SWC9BfiNJrIhMYuvzeOjgAABAIAAAABAAQACQAAAAVuYW1lcwAAABAAAAAEAAQACQAAAAJpdgAEAAkAAAAHc2Vzc2lvbgAEAAkAAAAEZGF0YQAEAAkAAAAJc2lnbmF0dXJlAAAA/g=="

This can be converted back with openssl::base64_decode:

identical(openssl::base64_decode(secret_base64), secret)
## [1] TRUE

Or, less compactly but also suitable for email, you might just convert the bytes into their hex representation:

secret_hex <- sodium::bin2hex(secret)
secret_hex
## [1] "580a000000030004000500030500000000055554462d38000002130000000400000018000000103966a760c3e98b1957de556eafd3c0e400000018000001001677d83da64d8b2b9a848196fec10bb0f9dfd3b3f2db593644c403556705ead271145c20c05e72843fb0fe24757f3fd2ad4279736da33b3cc77c4c1981f12188f4e53c5e1842a45ac06928dae2cf23c47fc2a88e9f16a2c844c92f23624dd4b5af91ddc561e380f684b217fe9a1e8e3422734ff22563f671c23bafe3f89281a5c3a1269df82323299764c9e6df4aef5231b5d1cfd744c3773a90874f1d28594b7bcd8b30f27635f98c29cab6b73931562001c9340f7d0d466bd2ff627ea7a61e52d54ab427b3a38fa7dbcd74d3477ee674d1476b2d8a6ec6fdf4e036e18852619bb80fc29c74ce4378923ce5082f41b5f484d02f08e19aa6ac0eb3f5cdf4d868000000180000001016140bd29366f39f638272db34b50d2d000000180000010054d81db9c28c851504f63a8975341a88d2ddeaec4030335f2874cc2d5ecd8390051f2b8cb45dbc9c23ca56d7c6f7ce4d69eff2194efa0339541f0b2377bd26798263871a244e1d9657e47f7d1720fe498f4d9872e291be874706a6560ea2f118e9ab10cdd3fb7a7cb71e710962496467e43d8a29c776ccff2e14156906af749e547db53e0ef4c769b7fd4caa06afc9ea3f0199234872520cf4a862e2125efbbb0b3d48fec3a71f065deddc6d0c33e5c72e6deb3dcefbbb6d1bfdf9ee4b0a60d09d694055a455955817a31e73b7d1bdfc52b66f7b14a53d1e4e188d34ca5047157b73613864d5d6236c8ad8b218461f33f92582f417e2349ac884c62ebf378e8e000004020000000100040009000000056e616d6573000000100000000400040009000000026976000400090000000773657373696f6e00040009000000046461746100040009000000097369676e6174757265000000fe"

and the reverse with sodium::hex2bin:

identical(sodium::hex2bin(secret_hex), secret)
## [1] TRUE

(this is somewhat less space efficient than base64 encoding.

As a final option, you can just save the secret with saveRDS and read it in with readRDS like any other option. This will be the best route if the secret is saved into a more complicated R object (e.g., a list or data.frame).

See the other cyphr vignette (vignette("data", package = "cyphr")) for a suggested workflow for exchanging secrets within a team, and the wrapper functions below for more convenient ways of working with encrypted data.

Do you already have an ssh keypair? To find out, run

cyphr::keypair_openssl(NULL, NULL)

One of three things will happen:

1. you will be prompted for your password to decrypt your private key, and then after entering it an object <cyphr_keypair: openssl> will be returned - you’re good to go!

2. you were not prompted for your password, but got a <cyphr_keypair: openssl> object. You should consider whether this is appropriate and consider generating a new keypair with the private key encrypted. If you don’t then anyone who can read your private key can decrypt any message intended for you.

3. you get an error like Did not find default ssh public key at ~/.ssh/id_rsa.pub. You need to create a keypair.

To create a keypair, you can use the cyphr::ssh_keygen() function as

cyphr::ssh_keygen("~/.ssh")

This will create the keypair as ~/.ssh/id_rsa and ~/.ssh/id_rsa.pub, which is where cyphr will look for your keys by default. See ?ssh_keygen for more information. (On Linux and macOS you might use the ssh-keygen command line utility. On windows, PuTTY has a utility for creating keys.)

### sodium

With sodium, things are largely the same with the exception that there is no standard format for saving sodium keys. The bits below use an in-memory key (which is just a collection of bytes) but these can also be filenames, each of which contains the contents of the key written out with writeBin.

First, generate keys for Alice:

key_a <- sodium::keygen()
pub_a <- sodium::pubkey(key_a)

the public key is derived from the private key, and Alice can share that with Bob. We next generate Bob’s keys

key_b <- sodium::keygen()
pub_b <- sodium::pubkey(key_b)

Bob would now share is public key with Alice.

If Alice wants to send a message to Bob she again uses her private key and Bob’s public key:

pair_a <- cyphr::keypair_sodium(pub_b, key_a)

As above, she can now send a message:

secret <- cyphr::encrypt_string("secret message", pair_a)
secret
##  [1] 36 e9 82 69 41 97 55 25 c9 b5 67 a2 19 ab a9 51 0f 5e da a2 8e 3f 70 d8 e3
## [26] c6 f3 e8 85 57 db 0c cf 11 36 c5 7b 67 ef 5e 36 b9 97 49 b8 0c 56 ed d8 cf
## [51] 78 dd 4a 19

Note how this line is identical to the one in the openssl section.

To decrypt this message, Bob would use Alice’s public key and his private key:

pair_b <- cyphr::keypair_sodium(pub_a, key_b)
cyphr::decrypt_string(secret, pair_b)
## [1] "secret message"

# Encrypting things

Above, we used cyphr::encrypt_string and cyphr::decrypt_string to encrypt and decrypt a string. There are several such functions in the package that encrypt and decrypt

• R objects encrypt_object / decrypt_object (using serialization and deserialization)
• strings: encrypt_string / decrypt_string
• raw vectors: encrypt_data / decrypt_data
• files: encrypt_file / decrypt_file

For this section we will just use a sodium symmetric encryption key

key <- cyphr::key_sodium(sodium::keygen())

For the examples below, in the case of asymmetric encryption (using either cyphr::keypair_openssl or cyphr::keypair_sodium) the sender would use their private key and the recipient’s public key and the recipient would use the complementary key pair.

## Objects

Here’s an object to encrypt:

obj <- list(x = 1:10, y = "secret")

This creates a bunch of raw bytes corresponding to the data (it’s not really possible to print this as anything nicer than bytes).

secret <- cyphr::encrypt_object(obj, key)
secret
##   [1] ed e7 79 76 08 30 54 92 84 7e 60 84 31 2c 72 45 1a df ec 93 00 b3 b2 59 f0
##  [26] 6a ca 2e 85 0f 56 21 ac e1 11 74 d3 91 c5 a6 68 4b 6e f6 d1 5b 50 75 93 d2
##  [51] 4d fb 2e 9a 9b 44 de a5 a6 f9 7a 72 9b c0 86 19 50 cf cc 62 29 19 03 ba 8b
##  [76] f5 9b bb b8 49 40 69 a4 b6 9f 9b 93 ca c1 b4 ad 30 6c 05 60 40 2c 9d 6a f2
## [101] 87 24 0e 6e 3d f4 ad ae c0 a2 d9 f6 52 b7 80 8d 6b d4 9a 9d ce 83 63 80 b8
## [126] c6 b2 ae a5 72 92 a0 73 ae fc d3 d5 51 15 bf 12 00 16 8e 95 08 0c 97 ff a4
## [151] 34 3a b5 11 21 b8 af 2c 36 0c 92 c7 81 47 1b 9a a9 d4 1b 46 81 96 85 20 7f
## [176] c2 3a 03 83 17 eb 63 4e 50 73 c0 03 83 6d ec a3 f1 e4 71 62 f6 e6 55 7c 20
## [201] aa 9f b8 f1 e6 fb d8 7d 3c d2 01 19 28 e6 e0 63 93 28 f1 83 c5 23 ed 8a d2
## [226] bb 41 10 be 77 51 b1 ff 60 d6 2c 59 39 4f 5c 37 bd e2 df ef 57 74 87 c7 06
## [251] fa 95 b6 c0

The data can be decrypted with the decrypt_object function:

cyphr::decrypt_object(secret, key)
## $x ## [1] 1 2 3 4 5 6 7 8 9 10 ## ##$y
## [1] "secret"

Optionally, this process can go via a file, using a third argument to the functions (note that temporary files are used here for compliance with CRAN policies - any path may be used in practice).

path_secret <- file.path(tempdir(), "secret.rds")
cyphr::encrypt_object(obj, key, path_secret)

There is now a file called secret.rds in the temporary directory:

file.exists(path_secret)
## [1] TRUE

though it is not actually an rds file:

readRDS(path_secret)
## Error in readRDS(path_secret): unknown input format

When passed a filename (as opposed to a raw vector), cyphr::decrypt_object will read the object in before decrypting it

cyphr::decrypt_object(path_secret, key)
## $x ## [1] 1 2 3 4 5 6 7 8 9 10 ## ##$y
## [1] "secret"

## Strings

For the case of strings we can do this in a slightly more lightweight way (the above function routes through serialize / deserialize which can be slow and will create larger objects than using charToRaw / rawToChar)

secret <- cyphr::encrypt_string("secret", key)
secret
##  [1] e6 9b b4 44 fd a9 cf 6c 00 c1 49 a2 fd 1a 31 60 42 23 5c 0f c0 85 3c 35 87
## [26] 19 60 61 65 03 05 39 ba 9f 5e ce 85 41 3d 5c bd d6 04 bd d0 30

and decrypt:

cyphr::decrypt_string(secret, key)
## [1] "secret"

## Plain raw data

If these are not enough for you, you can work directly with raw objects (bunches of bytes) by using encrypt_data:

dat <- sodium::random(100)
dat # some random bytes
##   [1] 70 06 a8 21 e0 7f ce e3 a3 f8 af 4c 23 53 c2 4f 43 c1 ca a8 6c 2c bd 3f e7
##  [26] 0f 9a 28 d2 c8 68 02 c1 8c c1 63 a7 b7 0d 5b cc bc ed 3d 0d b1 de 31 56 41
##  [51] fa d0 f7 43 e0 2f 4c 3b 6c ec 9d a7 d3 56 20 fe be 65 57 ab 8e cd c7 5c a2
##  [76] da be d4 60 7c 86 91 2a 16 96 41 7f 40 f1 87 82 68 f2 83 a4 d2 df 8d 9f da
secret <- cyphr::encrypt_data(dat, key)
secret
##   [1] 9b 84 82 80 ba 0c e6 72 5d 46 3a c2 97 1a b2 0d b8 a0 68 9c 6a 16 18 53 07
##  [26] f3 07 e2 08 55 a7 f7 16 1f 21 79 3e a0 2b 96 31 6e 3a 2d 2a fe 61 0e ab 54
##  [51] 31 20 a2 c7 b2 58 4d fb d2 1e 90 2f a9 fe 94 1c d1 bd 01 b1 c9 94 38 52 c1
##  [76] ef f8 c2 b9 aa ff 9a 62 55 1d ba 9f b5 65 35 5b cd 96 7a 63 d2 b2 97 5d e3
## [101] b5 d5 f0 11 98 2f ed 53 ab 25 5d 85 02 77 d5 a9 c2 92 d9 d6 34 43 30 b9 64
## [126] ae e1 26 ea 86 58 67 f5 b6 94 31 4e ba 8b d5

Decrypted data is the same as a the original data

identical(cyphr::decrypt_data(secret, key), dat)
## [1] TRUE

## Files

Suppose we have written a file that we want to encrypt to send to someone (in a temporary directory for compliance with CRAN policies)

path_data_csv <- file.path(tempdir(), "iris.csv")
write.csv(iris, path_data_csv, row.names = FALSE)

You can encrypt that file with

path_data_enc <- file.path(tempdir(), "iris.csv.enc")
cyphr::encrypt_file(path_data_csv, key, path_data_enc)

This encrypted file can then be decrypted with

path_data_decrypted <- file.path(tempdir(), "idis2.csv")
cyphr::decrypt_file(path_data_enc, key, path_data_decrypted)

Which is identical to the original:

tools::md5sum(c(path_data_csv, path_data_decrypted))
##           /tmp/RtmpnVhGBY/iris.csv          /tmp/RtmpnVhGBY/idis2.csv
## "5fe92fe6a2c1928ef5a67b8939fdaf8d" "5fe92fe6a2c1928ef5a67b8939fdaf8d"

# An even higher level interface for files

This is the most user-friendly way of using the package when the aim is to encrypt and decrypt files. The package provides a pair of functions cyphr::encrypt and cyphr::decrypt that wrap file writing and file reading functions. In general you would use encrypt when writing a file and decrypt when reading one. They’re designed to be used like so:

Suppose you have a super-secret object that you want to share privately

key <- cyphr::key_sodium(sodium::keygen())
x <- list(a = 1:10, b = "don't tell anyone else")

If you save x to disk with saveRDS it will be readable by everyone until it is deleted. But if you encrypted the file that saveRDS produced it would be protected and only people with the key can read it:

path_object <- file.path(tempdir(), "secret.rds")
cyphr::encrypt(saveRDS(x, path_object), key)

(see below for some more details on how this works).

This file cannot be read with readRDS:

readRDS(path_object)
## Error in readRDS(path_object): unknown input format

but if we wrap the call with decrypt and pass in the config object it can be decrypted and read:

cyphr::decrypt(readRDS(path_object), key)
## $a ## [1] 1 2 3 4 5 6 7 8 9 10 ## ##$b
## [1] "don't tell anyone else"

What happens in the call above is cyphr uses “non standard evaluation” to rewrite the call above so that it becomes (approximately)

1. use cyphr::decrypt_file to decrypt “secret.rds” as a temporary file
2. call readRDS on that temporary file
3. delete the temporary file (even if there is an error in the above calls)

This non-standard evaluation breaks referential integrity (so may not be suitable for programming). You can always do this manually with encrypt_file / decrypt_file so long as you make sure to clean up after yourself.

The encrypt function inspects the call in the first argument passed to it and works out for the function provided (saveRDS) which argument corresponds to the filename (here "secret.rds"). It then rewrites the call to write out to a temporary file (using tempfile()). Then it calls encrypt_file (see below) on this temporary file to create the file asked for ("secret.rds"). Then it deletes the temporary file, though this will also happen in case of an error in any of the above.

The decrypt function works similarly. It inspects the call and detects that the first argument represents the filename. It decrypts that file to create a temporary file, and then runs readRDS on that file. Again it will delete the temporary file on exit.

The functions supported via this interface are:

• readLines / writeLines
• readRDS / writeRDS
• read / save
• read.table / write.table
• read.csv / read.csv2 / write.csv
• read.delim / read.delim2

But new functions can be added with the rewrite_register function. For example, to support the excellent rio package, whose import and export functions take the filename file you could use:

cyphr::rewrite_register("rio", "import", "file")
cyphr::rewrite_register("rio", "export", "file")

now you can read and write tabular data into and out of a great many different file formats with encryption with calls like

cyphr::encrypt(rio::export(mtcars, "file.json"), key)
cyphr::decrypt(rio::import("file.json"), key)

The functions above use non standard evaluation and so may not be suitable for programming or use in packages. An “escape hatch” is provided via encrypt_ and decrypt_ where the first argument is a quoted expression.

cyphr::encrypt_(quote(saveRDS(x, path_object)), key)
cyphr::decrypt_(quote(readRDS(path_object)), key)
## $a ## [1] 1 2 3 4 5 6 7 8 9 10 ## ##$b
## [1] "don't tell anyone else"

# Session keys

When using key_openssl, keypair_openssl, key_sodium, or keypair_sodium we generate something that can decrypt data. The objects that are returned by these functions can encrypt and decrypt data and so it is reasonable to be concerned that if these objects were themselves saved to disk your data would be compromised.

To avoid this, cyphr does not store private or symmetric keys directly in these objects but instead encrypts the sensitive keys with a cyphr-specific session key that is regenerated each time the package is loaded. This means that the objects are practically only useful within one session, and if saved with save.image (perhaps automatically at the end of a session) the keys cannot be used to decrypt data.

To manually invalidate all keys you can use the cyphr::session_key_refresh function. For example, here is a symmetric key:

key <- cyphr::key_sodium(sodium::keygen())

which we can use to encrypt a secret string

secret <- cyphr::encrypt_string("my secret", key)

and decrypt it:

cyphr::decrypt_string(secret, key)
## [1] "my secret"

If we refresh the session key we invalidate the key object

cyphr::session_key_refresh()

and after this point the key cannot be used any further

cyphr::decrypt_string(secret, key)
## Error: Failed to decrypt key as session key has changed

This approach works because the package holds the session key within its environment (in cyphr:::session\$key) which R will not serialize. As noted above - this approach does not prevent an attacker with the ability to snoop on your R session from discovering your private keys or sensitive data but it does prevent accidentally saving keys in a way that would be useful for an attacker to use in a subsequent session.

• The vignettes in the openssl (vignette(package = "openssl")) and sodium (vignette(package = "openssl")) packages have explanations of how the tools used in cyphr work and interface with R.