Introduction

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

Illustration of Symmetric Encryption
Illustration of 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 3c:21:51:7c:48:9d:83:d4:e7:0e:65:f7:cc:10:3c:90

(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”)

Illustration of Asymmetric Encryption
Illustration of Asymmetric Encryption

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 04 02 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 3e 5c c6 e9 4b 65 4f 62 27 b1 b0
##  [51] a3 df cc 90 a4 00 00 00 18 00 00 01 00 2a 21 9e 40 f4 0d 06 fe 9d 40 ed c8
##  [76] a0 df 2d 2a fa 79 93 e7 2e 59 c5 77 1b d4 72 71 73 4c e9 30 7f 1f 23 24 ed
## [101] e0 39 d8 d4 87 d3 1a 64 50 58 1b 6d b0 f4 f9 ba aa 54 49 2a 66 a6 83 00 76
## [126] 9e d7 ce 53 d7 cb c3 bc 5e b1 94 4f 6a e0 94 3a c9 81 d0 b2 71 19 d8 23 e5
## [151] 6f 1e 7c 85 1c 7a 7f 00 d7 aa 2a 95 68 c1 83 ce bd 1c d9 3a 8c 68 a7 dd 9a
## [176] 47 69 49 8b 60 eb 71 8a b2 56 30 61 47 58 4c 5f 6a 76 b8 06 06 c1 77 5d 49
## [201] 9f 4d ab 38 ef e3 e3 6b df 4c ef ec 78 94 f0 e7 8d 76 2d f1 e0 3e 89 3c d9
## [226] c6 0c 4f 70 33 0b 89 6d 2a 41 8d c6 27 a1 00 20 6a 4d c2 39 a5 ae 1d 88 dd
## [251] ef 9c fc 0a 6c a5 31 37 2c d4 89 9d 65 76 5e 22 67 31 85 85 6d e9 15 7d 20
## [276] 24 93 d2 63 e2 56 53 a1 bd 71 1d d6 96 0c 15 61 06 5d 29 a2 eb 69 54 9b 53
## [301] 2d e4 e9 a8 8c 35 49 ba 2d ae e7 34 bf 0b 0b 57 9b 21 e8 00 00 00 18 00 00
## [326] 00 10 b8 70 03 fd 3d 08 40 7e f8 54 a5 3b de 55 3d ef 00 00 00 18 00 00 01
## [351] 00 59 0c ee 0b 32 10 44 7c 93 3d 01 f5 f6 78 33 f7 4a 9f 6b 5d 23 b6 33 5b
## [376] 9f 6d 3b 1d e5 f6 62 b9 20 84 c3 34 d8 56 e0 85 ba 2b 05 cc 05 df e1 88 ed
## [401] d4 a9 77 0a 65 91 bc 4c 9e 05 f0 d8 f5 c1 3d 72 b1 aa 00 f1 ec b1 56 9c a6
## [426] 35 8b 1e 68 ac 70 1c 50 76 62 a4 d7 2c aa 8c 4c 8f 0f 07 71 b2 f6 ab e3 56
## [451] f2 1a e5 86 f1 b4 59 ce 3f bc 09 8b bb cc ac 6d 08 c8 41 e5 41 0d 30 99 c4
## [476] e8 0b ec 4d 18 0b 29 7b 57 ef 34 40 a8 6f 5a 7b 27 ae 36 43 5d b4 c4 d5 9a
## [501] 8e d1 e0 d2 1a 7c af 4f bc 14 c4 bc 4b 42 d6 67 93 24 2c 5f 6e 01 fb d2 0e
## [526] 63 b5 a9 95 5c d3 e9 0c 24 cc 1a 43 3c 83 e0 09 27 55 92 68 b2 a0 42 0d ca
## [551] 84 c9 23 96 cf 1f e9 18 b1 8f 94 53 d0 f2 46 29 1c 3e 4d 54 41 28 c1 98 b0
## [576] dc 83 32 72 79 25 af b7 f4 11 b3 d4 b7 30 c6 cd 2a 65 4d 72 e6 3e 07 68 34
## [601] 0c 1b 7c d0 2d 16 b5 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 in openssl::decrypt_envelope(x$data, x$iv, x$session, key): OpenSSL error: 00F8EB33C97F0000:error:03000082:digital envelope routines:EVP_CIPHER_CTX_set_key_length:invalid key length:../crypto/evp/evp_enc.c:1046:

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 04 02 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 f1 46 ac f6 b3 ee d8 62 f5 e3 40
##  [51] da 62 22 18 de 00 00 00 18 00 00 01 00 2f e1 71 6d 83 18 5a 36 54 9b db 59
##  [76] 45 e3 f2 15 36 65 78 b9 07 12 62 08 f9 1e 6f b5 bc b4 87 ae bb 5d 4f 9d ee
## [101] c0 a8 73 40 e8 5e 62 29 7b 41 45 a9 5c 34 b7 36 56 e3 b4 1d ec 94 e7 4a 7a
## [126] d0 53 57 1b 80 91 ee a0 e1 4a f7 11 d1 d8 1e af ff b8 d9 bd 26 42 c0 60 c2
## [151] bf 3b f3 5b 10 e7 42 65 79 f9 2e 5a 76 3b 0c e3 c1 cd c7 34 44 dc e9 94 4a
## [176] 80 81 f9 72 a4 c6 06 d1 df c2 50 eb 96 b7 52 b5 92 b5 f0 ff 3b c5 cd 2a 96
## [201] ad 3b a4 59 c8 19 28 09 2e aa 60 2b ab 4e 44 96 fd 59 ca 53 7a df 35 60 86
## [226] d7 bb bc 64 21 93 e0 be b6 bf 85 7f 97 98 03 a6 da 01 17 f8 9a 8a 24 dc 55
## [251] 64 3b 76 1f 1d 9e e8 9e 1d 7d 11 0b a0 c2 c4 35 ab a4 c0 c4 01 82 ed 73 1a
## [276] 27 a9 2f c8 8c c2 be e3 8e a9 15 72 0c 33 26 64 e1 a8 62 ea dd e7 76 6d 11
## [301] 06 bd 06 0f f2 28 48 67 58 fe b7 ea 08 55 62 c4 ab ad 74 00 00 00 18 00 00
## [326] 00 10 26 cd cf 2f c2 fc 22 10 54 83 5c 85 5e fd 68 a4 00 00 00 18 00 00 01
## [351] 00 04 1a ed 7d 30 2f b6 bd 51 56 86 bc e5 52 04 47 e8 53 ca db 81 ff 38 9d
## [376] a3 1d e6 3e 21 7a 17 20 69 1e 2f 27 d5 f5 3a 6a ca d0 46 d1 81 23 da ef 26
## [401] 42 ab 76 c2 4f bd c0 fe bd f5 fc d6 f2 d7 4b bb 93 c9 65 de 98 26 fe 6a 49
## [426] b5 1a 68 fa bd 0d 73 d8 39 68 e6 38 f0 c9 04 e4 f0 10 e8 ae 33 69 49 0d f6
## [451] 15 3d 1d cb 67 76 c1 98 c6 7b d5 54 2d d0 72 43 b4 74 da c2 69 b5 49 91 08
## [476] 0f a7 16 b4 9f 38 54 0d a5 dd 28 a7 47 39 31 b2 40 10 0c 01 ce 28 39 37 06
## [501] 61 2e 37 cf 5f 78 14 38 79 af b9 f1 98 2d 84 36 66 ed 55 47 bc ee 0f 42 17
## [526] 59 80 6c 4e 88 b7 3c c8 10 b5 20 e5 32 45 dd c8 39 6c 3c e1 3d fb 78 9c 1f
## [551] 2c 72 70 84 41 81 60 ea cc 01 64 3d ab bf e3 93 8d 6d fd b9 ad 8c f8 b5 a4
## [576] cf 1e 18 0b ef 3f 5c 51 c9 8a 21 f1 37 69 bd 04 97 c0 cd 17 c4 89 96 db 3b
## [601] 3c b3 e8 93 8c d9 9d 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] "WAoAAAADAAQEAgADBQAAAAAFVVRGLTgAAAITAAAABAAAABgAAAAQzid2D13HB8oj2JaO7SCxKQAAABgAAAEAkiqSpTLZzTAiRb02Jp92iBSCBoYWT/kcVCWV2zMqiKrNgCMMPHD8HTeYj3J9KKEPocD56EGy6Iwkc1ppJGrxi9hVTwcCLDXRILPNhJdwtib3cjDijQsgqqsg3HCzKBEtarwSIUk41KIzjvI9Ad3T18u3uAJkgaY9/1ESXtz7j3LROPHmAq27JttJNlJSCIPQ38wk3QC/lUGlQVPDci2+//QBNbWfa6Wo2csrhzxcLj16ndkpAm3unX6XtHqqTCTnEI6AXxI3VQEKa1ewsJESgcg4NFmC+rUgs6HdnnWrhKgqAMaw78LTNvE9P35BkdCBbzv6Otm10f0xgiMO1bJiRQAAABgAAAAQmzLoRYfJyvfwcIgYzNHYmAAAABgAAAEAWQzuCzIQRHyTPQH19ngz90qfa10jtjNbn207HeX2YrkghMM02FbghborBcwF3+GI7dSpdwplkbxMngXw2PXBPXKxqgDx7LFWnKY1ix5orHAcUHZipNcsqoxMjw8HcbL2q+NW8hrlhvG0Wc4/vAmLu8ysbQjIQeVBDTCZxOgL7E0YCyl7V+80QKhvWnsnrjZDXbTE1ZqO0eDSGnyvT7wUxLxLQtZnkyQsX24B+9IOY7WplVzT6QwkzBpDPIPgCSdVkmiyoEINyoTJI5bPH+kYsY+UU9DyRikcPk1UQSjBmLDcgzJyeSWvt/QRs9S3MMbNKmVNcuY+B2g0DBt80C0WtQAABAIAAAABAAQACQAAAAVuYW1lcwAAABAAAAAEAAQACQAAAAJpdgAEAAkAAAAHc2Vzc2lvbgAEAAkAAAAEZGF0YQAEAAkAAAAJc2lnbmF0dXJlAAAA/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] "580a000000030004040200030500000000055554462d3800000213000000040000001800000010ce27760f5dc707ca23d8968eed20b1290000001800000100922a92a532d9cd302245bd36269f768814820686164ff91c542595db332a88aacd80230c3c70fc1d37988f727d28a10fa1c0f9e841b2e88c24735a69246af18bd8554f07022c35d120b3cd849770b626f77230e28d0b20aaab20dc70b328112d6abc12214938d4a2338ef23d01ddd3d7cbb7b8026481a63dff51125edcfb8f72d138f1e602adbb26db493652520883d0dfcc24dd00bf9541a54153c3722dbefff40135b59f6ba5a8d9cb2b873c5c2e3d7a9dd929026dee9d7e97b47aaa4c24e7108e805f123755010a6b57b0b0911281c838345982fab520b3a1dd9e75ab84a82a00c6b0efc2d336f13d3f7e4191d0816f3bfa3ad9b5d1fd3182230ed5b2624500000018000000109b32e84587c9caf7f0708818ccd1d8980000001800000100590cee0b3210447c933d01f5f67833f74a9f6b5d23b6335b9f6d3b1de5f662b92084c334d856e085ba2b05cc05dfe188edd4a9770a6591bc4c9e05f0d8f5c13d72b1aa00f1ecb1569ca6358b1e68ac701c507662a4d72caa8c4c8f0f0771b2f6abe356f21ae586f1b459ce3fbc098bbbccac6d08c841e5410d3099c4e80bec4d180b297b57ef3440a86f5a7b27ae36435db4c4d59a8ed1e0d21a7caf4fbc14c4bc4b42d66793242c5f6e01fbd20e63b5a9955cd3e90c24cc1a433c83e00927559268b2a0420dca84c92396cf1fe918b18f9453d0f246291c3e4d544128c198b0dc8332727925afb7f411b3d4b730c6cd2a654d72e63e0768340c1b7cd02d16b5000004020000000100040009000000056e616d6573000000100000000400040009000000026976000400090000000773657373696f6e00040009000000046461746100040009000000097369676e6174757265000000fe"

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] ff 45 a4 78 90 04 6c 18 f9 1a f4 ad cc 4b b1 37 8e d7 72 a7 77 96 f5 73 d6
## [26] f8 a4 e1 10 fe fa cb 16 88 09 5b 68 b4 01 97 71 5d a2 09 f6 30 fd 35 c3 24
## [51] 6c db a1 cf

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] 73 cb dc b3 ec 21 73 47 8d 99 9e 70 9b 0a 96 07 15 07 f7 98 bf 5d 2c a5 22
##  [26] 06 10 dd 09 e8 3a 93 6e 0d c5 dd 53 5f 04 46 1b 66 c9 7a 9f 04 6f 9d 35 60
##  [51] 0a 32 e1 35 f2 18 66 ff 89 fe 9f 7a 8a 7a 88 01 92 fd a6 b4 bc da f9 ed 28
##  [76] 4f 98 e8 54 52 88 18 77 96 df 56 1d e6 38 fc 40 cb ff 11 b6 f0 d3 48 4a 94
## [101] 3f 15 76 29 c0 1a c7 d7 20 1e 60 c3 9f 84 2e b3 89 32 78 90 f2 3e 5b ab f2
## [126] 14 f6 dc 3d b5 1a 37 7c 30 e4 7d 1b 9e e6 c7 aa 6c bd 9f 43 1e f8 05 71 ac
## [151] e7 17 a1 a0 95 27 ae bd 0e 6a 1f d5 8e c6 c1 2e 25 52 cd 1a 76 9a 82 3d b0
## [176] d8 0d 55 17 52 e8 1c b5 2c cc 45 4c 8c 55 2a e7 52 c9 04 d2 e2 b8 98 48 67
## [201] c8 03 bb 35 85 b9 84 af b2 bf 20 5c 65 9c 30 62 d8 77 83 5b f8 b7 69 d4 da
## [226] 85 00 d4 34 84 54 d4 15 f7 12 a4 3d 64 b7 08 b0 0b aa 16 b7 35 16 9a 52 5a
## [251] 11 95 18 dc

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] a8 a8 5c 60 62 42 b3 04 93 36 6b 93 b9 53 70 42 eb 3d 69 b7 51 6b 14 fc 10
## [26] 77 38 2d 0a 42 5d 20 83 0b c9 8c 3d eb 66 fa 85 ec 0e a4 c8 df

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] 3c a0 4f df 03 70 f3 96 a5 55 6d 2b 1f 1f 27 ac c1 6a a0 bd 57 6a 18 e4 7c
##  [26] 93 57 a5 cc c3 dc 09 4c 99 3c 83 74 74 17 58 71 d5 1f 17 47 a0 8b 2f 26 f3
##  [51] 7a 8c b3 cc 90 52 4a ea c2 ad 26 ba 47 08 bf 38 b1 a3 76 58 43 81 b6 96 da
##  [76] 8f 1e 19 ce f4 4c 1e c5 41 8f 4f 98 a0 4b c6 c2 be 4b 17 70 a3 6d f7 52 a9
secret <- cyphr::encrypt_data(dat, key)
secret
##   [1] 8b bc 7a ad 72 61 08 9c 7d cd e2 7a 5d 02 2d 71 ea 62 6a 6a 81 42 e5 13 91
##  [26] 53 bb f6 19 9f c4 08 63 10 c1 2f e8 67 05 8c d9 42 ab e2 02 cd b6 5c cd 42
##  [51] 87 82 ec 0c 6e e0 3a 4c 32 03 07 50 51 5b 74 85 6d 6a 80 d5 e1 09 ea ae 24
##  [76] 41 86 6b 2e 41 ec 5d dd 44 88 ec b4 6c 1b df 61 12 fd 59 79 0c 70 9e 3d d0
## [101] 34 9d 72 c4 da 92 88 80 8b b2 31 89 2d a5 2c 81 51 8b 47 cb a7 42 4f 9c bc
## [126] 22 ef 22 ae c8 28 a7 fc 64 48 9c 75 bb 21 41

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/RtmpamMGk4/iris.csv          /tmp/RtmpamMGk4/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.

Further reading

  • The wikipedia page on Public Key cryptography has some nice diagrams that explain how key and data interact https://en.wikipedia.org/wiki/Public-key_cryptography
  • 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.

Confused? Need help? Found a bug?