Skip to contents

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 55:28:26:c4:5c:a5:47:c0:c4:05:4c:6f:05:3a:42:78

(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 01 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 de f5 9e 15 53 97 ab f8 bf f1 64
##  [51] ac 6c 48 43 09 00 00 00 18 00 00 01 00 19 54 33 bf 7a 44 92 8a 8a ee e8 1a
##  [76] 2e 6a 97 34 38 49 d1 32 6c 4b ab 5c 59 07 05 68 c7 13 65 16 9f 14 11 b5 0c
## [101] ab d1 da ba 8e 00 a7 14 7d fc a1 05 68 9a 78 32 1d 2f b7 b5 c4 7c e7 8e 4a
## [126] 3f 25 fc 8f 5a 11 f0 db 28 46 1f 39 b6 77 1c 1b 46 1f d3 ef ff 82 68 1e 31
## [151] e1 d5 4e df fd 09 3a 82 1d 62 94 d3 66 a9 cb 7d 25 03 9b 88 b7 d9 71 17 37
## [176] 7f d9 79 ee c7 83 2c a0 f5 b1 0d 50 dc e2 69 4d 6d 2a 95 1d 44 cc 3e 03 9e
## [201] 57 4b 38 e4 8f bf 3d 71 16 0b 74 85 72 d8 c5 cf 53 48 1a 43 c1 39 0e 36 72
## [226] b6 10 01 25 7f 8f e4 3a 11 2e 31 6d 71 aa 1f f7 37 aa b1 56 3c 49 73 d1 ca
## [251] 21 f0 bb fc 99 ab 44 ce 38 6b 2b a3 c2 51 95 7a f3 ec 96 a9 ae e6 61 2e 71
## [276] 12 0f d7 fe b0 90 7c 17 dd bd 06 ac 4c 64 88 9a ea fd 72 4a 41 ad 02 d9 3b
## [301] 44 95 e9 85 e1 37 8d 22 1d 29 98 6d 70 24 b4 1f 68 58 d3 00 00 00 18 00 00
## [326] 00 10 dd c9 c5 85 eb 82 77 5f fc d4 48 31 6f 81 8e d0 00 00 00 18 00 00 01
## [351] 00 4a f6 1c b0 8d 3f 44 9b 68 90 e7 7c b6 51 96 8f 29 68 43 0b cb 9a ac b6
## [376] 98 8e f3 ae 8e 07 8d f8 f8 27 c3 a8 76 57 39 4c 01 ce 9d 36 97 03 f9 79 33
## [401] 4f c3 42 48 71 7b df c8 da 09 17 71 79 d3 b7 18 a2 c8 cb ae f6 e8 a9 9e 30
## [426] 82 e3 2c e4 6e 82 35 04 63 aa 62 b8 fe d0 49 18 0a 71 07 1f 55 4d 92 c6 06
## [451] 6e 22 ff 33 e9 d3 85 cd 47 8a 28 3d ac c6 ce ed d1 2e ab a8 4b 23 46 36 f2
## [476] c3 c7 c9 6a 80 ee f8 aa 45 b6 80 23 2a 5e 0e ae cf 18 e4 21 97 05 14 b4 99
## [501] ef 2b 02 86 bb b0 2b bc 62 9c 37 28 11 c7 b0 b6 eb 72 f3 1d fb 20 8a e3 33
## [526] 67 74 af 6d f8 43 51 71 ee 74 5e c6 ae ea cb e5 42 b4 d6 54 d0 b1 e3 6d 69
## [551] 1c f9 3d 15 35 9e 61 12 1f f7 00 7f e7 d2 dd fd a8 f8 4b 00 c9 18 93 4e d1
## [576] 0c b4 8e f9 f0 7d b9 b3 58 00 a8 d7 80 7c 4f 02 73 ff 94 9a 6d 22 de e3 f4
## [601] e5 14 86 6b cf 49 ce 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: 00E89E35B37F0000: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 01 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 d8 7c d6 1b 81 1a de 95 07 20 ae
##  [51] 45 71 a6 8d 80 00 00 00 18 00 00 01 00 55 c9 5e cf 36 15 ba a4 61 10 0a 9b
##  [76] 35 17 6f 48 2d 4f 15 c5 b9 43 32 d1 83 56 bb 5c b2 f0 04 22 2f d8 6c 1b f3
## [101] 10 ce 08 24 1e 1a 34 2b be 52 82 41 45 46 74 e4 6a d1 2d 03 ad e2 56 89 d8
## [126] 4a 55 58 66 e4 a7 e2 48 96 51 15 a0 ec 53 a9 5a 3b 63 54 eb b5 c9 06 19 a0
## [151] 94 50 bc cc 9a 78 7b 9f 2d a6 cd 07 4a 1f 77 72 76 78 15 b9 32 9e 3b d8 fb
## [176] f7 8b d4 a1 97 53 7a 2d ac 0e d9 61 73 a7 f3 92 a7 d2 be 52 de 9d d8 e1 58
## [201] 21 0d e3 f0 82 6c e1 4e eb 8b 8a e0 48 1f 2d bb b7 41 66 9a e4 7d 93 1f be
## [226] c5 9e 54 aa 53 6b 4d 1d bd 94 5b 6d 89 2b d8 8c 0d e0 67 fc 27 b1 d8 a9 a6
## [251] 7c 3f 3c 7e 3c f7 82 87 84 25 fd c4 25 e6 eb 17 f8 49 b3 81 25 11 f7 3a 34
## [276] 25 db b3 04 e2 5f 31 ed 2b 24 16 93 46 20 c7 88 d1 2d 95 89 f3 ae a3 40 40
## [301] 19 a8 3d e6 9c 6c e5 e5 e4 66 ba 4a 4a 32 0b 37 0f f8 2a 00 00 00 18 00 00
## [326] 00 10 58 84 2e df 98 9d 92 4b 24 41 6f d6 40 a9 3f dd 00 00 00 18 00 00 01
## [351] 00 3d d7 9b 48 2c f4 1f 40 70 cb 47 6e fa 42 da fe d2 6c 2a 45 0c d5 78 37
## [376] b5 a5 06 0c eb 0b 70 82 4f 73 1f d5 30 ae 25 ac 81 d7 62 69 da c5 66 6c c4
## [401] 09 be 08 ae 6a 68 8c 5f 2c e2 e3 a6 6b 6a 30 4e 03 8f 0f 2b de 17 91 18 31
## [426] 58 f0 7a 59 59 7e 83 2c 88 8d 4f 81 15 9c e9 11 50 5e 5b ba 5b 93 2a ea f2
## [451] 5c 6e f4 1d 19 a1 94 cd e9 a4 06 46 c1 6f 13 fc 36 03 d0 38 bc 1d 04 a0 49
## [476] c0 0e cc 48 18 ec 17 24 db 55 05 ce 43 bd 8d e3 5a 5b ed 67 2d 62 d1 e3 ba
## [501] e7 4e 75 e9 fb db 74 aa c6 8c 25 4e 8f d0 02 77 1e 01 3e 33 aa 89 77 bc 8f
## [526] 5b 23 85 67 99 c5 ec 19 48 fd 88 fe c7 48 f2 76 cd b9 18 5a ac 8b 0a 3d 68
## [551] d1 e1 38 31 93 93 d2 63 1e bd db 6a 74 62 5d 58 69 20 ae 6e 07 89 da c9 a6
## [576] b8 83 6d 43 d5 df 78 0a eb 0f a1 9d 1b da 4e 6e 68 6b 28 d6 87 6f c8 bf c0
## [601] 91 d9 5e c0 d0 65 40 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] "WAoAAAADAAQEAQADBQAAAAAFVVRGLTgAAAITAAAABAAAABgAAAAQFodU5RyH8tLhTpbwR20xLAAAABgAAAEAEhkC29AzBpNa3PP2+YFbhcGrTYY4NnpvhY/Q+Qgyd3/fY2NR0aE0z/O30sJFLE8uFOkbIOe7IrCW9m2ec1Egd4FlDESWymS9O+01NDk28wwx6CChae/Frfonhr+WfUZT1PYtcNMrfCf1kKZ5z1fdeI/ERAybGXsnv2U7w2qkZ+u03/ECbORum9xybjTB81uHS6lygCi5qrAIelQH1/vd7HCvdX7uKVprM1jAr7U9QbOHm/p3tGzZkkzbcDf2mIqGfysBDHrgDkzDzyo2kxwMUVTuzOtyO4uuAa4uA3OfSuOutXu58YxfrCs3+pV/Tdvrz6sl9RD8tc3i40kRSF3hkQAAABgAAAAQ3bg9M7JmsNjRX7WsiBjYGwAAABgAAAEASvYcsI0/RJtokOd8tlGWjyloQwvLmqy2mI7zro4Hjfj4J8Oodlc5TAHOnTaXA/l5M0/DQkhxe9/I2gkXcXnTtxiiyMuu9uipnjCC4yzkboI1BGOqYrj+0EkYCnEHH1VNksYGbiL/M+nThc1Hiig9rMbO7dEuq6hLI0Y28sPHyWqA7viqRbaAIypeDq7PGOQhlwUUtJnvKwKGu7ArvGKcNygRx7C263LzHfsgiuMzZ3SvbfhDUXHudF7GrurL5UK01lTQseNtaRz5PRU1nmESH/cAf+fS3f2o+EsAyRiTTtEMtI758H25s1gAqNeAfE8Cc/+Umm0i3uP05RSGa89JzgAABAIAAAABAAQACQAAAAVuYW1lcwAAABAAAAAEAAQACQAAAAJpdgAEAAkAAAAHc2Vzc2lvbgAEAAkAAAAEZGF0YQAEAAkAAAAJc2lnbmF0dXJlAAAA/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] "580a000000030004040100030500000000055554462d3800000213000000040000001800000010168754e51c87f2d2e14e96f0476d312c0000001800000100121902dbd03306935adcf3f6f9815b85c1ab4d8638367a6f858fd0f90832777fdf636351d1a134cff3b7d2c2452c4f2e14e91b20e7bb22b096f66d9e7351207781650c4496ca64bd3bed35343936f30c31e820a169efc5adfa2786bf967d4653d4f62d70d32b7c27f590a679cf57dd788fc4440c9b197b27bf653bc36aa467ebb4dff1026ce46e9bdc726e34c1f35b874ba9728028b9aab0087a5407d7fbddec70af757eee295a6b3358c0afb53d41b3879bfa77b46cd9924cdb7037f6988a867f2b010c7ae00e4cc3cf2a36931c0c5154eecceb723b8bae01ae2e03739f4ae3aeb57bb9f18c5fac2b37fa957f4ddbebcfab25f510fcb5cde2e34911485de1910000001800000010ddb83d33b266b0d8d15fb5ac8818d81b00000018000001004af61cb08d3f449b6890e77cb651968f2968430bcb9aacb6988ef3ae8e078df8f827c3a87657394c01ce9d369703f979334fc34248717bdfc8da09177179d3b718a2c8cbaef6e8a99e3082e32ce46e82350463aa62b8fed049180a71071f554d92c6066e22ff33e9d385cd478a283dacc6ceedd12eaba84b234636f2c3c7c96a80eef8aa45b680232a5e0eaecf18e421970514b499ef2b0286bbb02bbc629c372811c7b0b6eb72f31dfb208ae3336774af6df8435171ee745ec6aeeacbe542b4d654d0b1e36d691cf93d15359e61121ff7007fe7d2ddfda8f84b00c918934ed10cb48ef9f07db9b35800a8d7807c4f0273ff949a6d22dee3f4e514866bcf49ce000004020000000100040009000000056e616d6573000000100000000400040009000000026976000400090000000773657373696f6e00040009000000046461746100040009000000097369676e6174757265000000fe"

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] c3 94 c2 21 58 e2 30 30 f9 a9 ed 33 63 cf 84 75 8b 26 6a 03 9c 7b 2b 1f 21
## [26] 56 0f df ec a6 b7 87 5d 3a 03 a2 03 8e 13 94 a8 78 50 51 5b 76 ac 6f c9 57
## [51] 53 0c ca 63

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] 5f ad 0f 35 18 c1 e9 70 97 3a fd 15 0a 2e f3 9c 34 35 f7 4c f6 2d e0 1b ee
##  [26] bb fe 5b 38 77 ea de 68 24 df 2f 52 08 19 97 1c 67 54 e1 8a 4d 40 c2 10 44
##  [51] 29 c7 ca 19 d4 b5 66 fa aa 98 c1 1c 64 ba 46 2e 2b c2 5f e2 34 a6 a9 05 9b
##  [76] 82 a3 ee 87 15 c5 a0 7a 1d f0 f2 79 5f ad b9 5e 9b 98 be 7d a6 30 16 1e 13
## [101] 90 0c e1 6a 14 41 cd 8d 99 88 1f ca 31 26 c8 ae 52 36 bf 9d 11 b5 4b a1 bd
## [126] 73 00 96 83 8c fb fc 4f 0b 24 23 4c db c1 9e 94 1c de 2c 86 64 b9 b9 a0 40
## [151] 24 54 64 67 11 f9 66 d7 ed 86 93 17 67 2e 4c 69 53 70 c5 1d a7 63 0c de d8
## [176] a3 2d f5 30 5e df 8f 39 97 91 e4 73 0d 9d a7 69 7c 22 82 b4 76 fd be 3d b1
## [201] ab 52 4a 52 ee 49 06 17 72 4a b3 46 3c 8e ea a3 e1 92 82 f2 c5 75 6b 08 16
## [226] df 56 f9 41 0d 2f 2c 7a 6d 2a 39 30 16 fc 72 38 b0 98 6b fc b5 bc 89 38 4b
## [251] e1 97 c3 02

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] d4 67 35 43 ba 43 82 c0 ab e2 1b d3 ab 58 6b e7 cc a6 aa a6 21 1d fd b9 10
## [26] 86 56 1d 8e c5 be 38 54 20 92 3e 03 00 91 62 ce 54 d5 a1 9a 78

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] 48 1e f7 fb 49 22 20 c1 bd a3 18 41 82 01 4b 36 61 2d ba 22 15 a0 5c fe 06
##  [26] 98 fe f1 1a c1 a3 58 fe 5a 1f 66 99 6e 65 f1 a6 45 f5 81 b3 d5 a1 46 9d 98
##  [51] ef 90 e3 e7 51 b8 d2 54 91 b1 c3 f2 d1 56 4c 9d 9f 88 44 bc d0 a9 38 c8 09
##  [76] 9e c5 27 80 1e af e7 56 fe a8 25 01 6e 1d 81 7c 76 7e 29 f8 2d 08 cd 0c f0
secret <- cyphr::encrypt_data(dat, key)
secret
##   [1] 9d fb d6 94 ad e7 cd df 57 e8 b3 5d 6f 55 80 fe e1 45 69 72 6c 0f cc e3 55
##  [26] 19 64 10 1c 5f 87 43 a0 f7 51 a4 e2 b3 f8 34 1c 72 f1 cd f1 dc 23 30 27 5a
##  [51] a4 27 2c 40 7b cd 67 f3 aa 1a 63 29 61 97 3b 6e 00 bc b8 73 ae 0b ef 32 1a
##  [76] b7 d3 86 9c 88 35 49 bf 4e ac 25 24 43 1a 07 2e 84 90 a6 2f 1c fa bc 25 d0
## [101] ae e9 0d 41 71 c2 a1 14 88 b2 16 e9 c5 86 f3 fa e3 b3 5b 76 ed 7f 40 02 db
## [126] c8 ce cf 8d b6 44 d3 2c f7 3f 75 e9 90 cb 68

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

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?