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:

which generates a raw vector

## aes raw ba:0a:3d:e8:3d:34:b9:5a:24:9d:5c:b6:f5:77:af:99

(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

## <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:

## [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

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:

## <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.

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

##   [1] 58 0a 00 00 00 02 00 03 05 02 00 02 03 00 00 00 02 13 00 00 00 04 00
##  [24] 00 00 18 00 00 00 10 9f bc a2 72 03 b9 3c 58 42 67 0e e7 7b e3 71 57
##  [47] 00 00 00 18 00 00 01 00 a1 7b 48 d2 e8 4d ab e9 01 44 46 c1 52 38 02
##  [70] 64 a2 97 0c 64 56 08 f2 61 e4 d0 1f 16 d9 02 66 32 46 af 8e 4d 4f 04
##  [93] 4f b1 42 93 cb 33 77 bc ab e3 74 69 72 a8 61 ca 26 4c 34 dd 56 08 3a
## [116] 9a eb fb 74 50 17 7f a1 c9 72 b3 a1 7f c7 bd 24 2a fa f0 46 ad e5 79
## [139] 65 ff 76 84 af 9b 5d ae 05 e6 c5 4c 4f 12 ef e1 e8 06 89 02 9d 9f b2
## [162] 13 a6 8d a5 8b d6 2a bc b9 6b 5e 75 d1 7b 59 3a 21 e2 1f f9 34 ae 2a
## [185] d9 55 59 95 4a 97 ca e4 aa 44 6a 79 75 17 50 9c 86 e0 d8 c3 b6 29 6d
## [208] 63 01 e3 3c 8e 8c 52 f5 17 33 01 36 39 b4 21 6e da bb 41 db da 08 00
## [231] df 54 c4 16 ad ed 60 25 7f 98 d0 97 0a 75 92 51 fa 54 28 2f ba 86 0f
## [254] 8f d4 ce 3b c4 31 b7 05 71 9b e9 d8 f6 15 34 25 25 3b 75 25 72 dc 42
## [277] 68 89 6a df 20 33 94 a2 4e 42 40 fe 68 47 d3 39 99 40 85 6c 7b 26 26
## [300] d3 f1 d9 bb 15 24 87 b1 08 15 47 00 00 00 18 00 00 00 10 cb fd 50 3e
## [323] 8d 24 78 0e 5f c2 63 cb 52 91 1d 9a 00 00 00 18 00 00 01 00 07 af 72
## [346] 38 6f 0f 18 d6 bf 8a c9 20 b2 26 5b 4a 1b db 8e 59 44 cf 90 ed 93 ec
## [369] aa 64 ad 54 11 51 b1 7f f9 d7 8c f4 27 cd 19 03 4a 1a d3 35 bb 88 52
## [392] 57 02 ed dc e5 ef b5 18 ef 63 ec a7 2c 81 da cf 3d 2f 9b 94 1e c7 45
## [415] fa 11 15 8c 16 5c 8d a7 48 61 eb a5 bd b6 8d f9 2c a2 a7 cb 18 ba f1
## [438] 72 a6 5e 87 a9 8e fa 68 4a 08 15 9a de 05 2d 49 8a aa 25 e3 a6 51 d5
## [461] 82 c5 b6 ee 75 c1 20 aa 6b 76 26 a1 d7 fd d7 c5 d0 1e 98 f9 ab e1 51
## [484] fb 1e 03 d4 ca 1c e8 a1 ca 74 ac 6a de a3 fb 6f 69 4f d8 e5 6f c0 0e
## [507] 7a d5 d8 c1 6f 48 8f aa 95 22 17 93 ed 2c b8 ac e8 69 cf 06 71 dd b7
## [530] 78 17 96 0c e5 7a db d0 5f fb 0c 8f 78 e5 f1 aa 49 7b 43 eb 59 1a 18
## [553] 58 09 d9 9e 38 80 a7 10 16 c8 eb 02 57 01 3b f6 fe 0f 89 3a 1a 0b 97
## [576] 91 7d 97 74 aa 9a 6b 17 de eb 26 1a c2 2e 60 45 e5 7e ff 38 2d ba 85
## [599] 00 00 04 02 00 00 00 01 00 04 00 09 00 00 00 05 6e 61 6d 65 73 00 00
## [622] 00 10 00 00 00 04 00 04 00 09 00 00 00 02 69 76 00 04 00 09 00 00 00
## [645] 07 73 65 73 73 69 6f 6e 00 04 00 09 00 00 00 04 64 61 74 61 00 04 00
## [668] 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 02 00 03 05 02 00 02 03 00 00 00 02 13 00 00 00 04 00
##  [24] 00 00 18 00 00 00 10 35 0f 94 90 a1 b7 fc 0e a6 a6 dc 48 66 c2 81 cd
##  [47] 00 00 00 18 00 00 01 00 1c 34 9d bd 2e c2 82 a5 86 bc 92 39 0a f0 3f
##  [70] d0 c9 a0 42 36 65 0e d3 3e 12 da 6c a2 97 cc 04 fd 88 e8 85 c1 73 ae
##  [93] 9e ee d1 34 f2 ac 48 f8 9d 48 26 9e 07 ba 32 52 32 b2 ba 36 6a f5 60
## [116] f1 8a c6 a6 ae 13 07 7a 1b 5e 21 3c 47 d0 25 96 2f eb d6 94 f6 8a 5b
## [139] c9 3e 6a 15 e3 54 b1 0e ad 9e 98 dc 0f 0d 1a 5f 0e f2 40 4b 74 e3 93
## [162] 05 33 97 db b5 bd ee af 41 cd 6a 2c b3 ab 09 48 06 ca b6 42 e8 ba d8
## [185] 94 03 7f d5 d9 cc 61 7b 90 2f 33 8d af 4a 88 ec 99 ac 9e 9a 37 f9 75
## [208] 38 e4 55 71 3b e2 14 56 75 05 ff 67 d5 e1 ed d5 c5 81 4b 4e c4 84 f6
## [231] f4 6f 52 8c ae 6d ec f4 92 9c 31 dd e9 6b cb e5 44 c7 34 f4 08 80 9e
## [254] aa ac 66 ed c9 00 55 01 7a af 96 a8 43 84 b8 38 8a e1 ae 01 d8 5a f5
## [277] dd b7 e3 21 47 dc c0 69 14 b2 d5 b5 eb 53 71 ab 5e 45 9f 85 81 9f 01
## [300] de 43 ff 4b fa 4e 95 9f 17 ad 73 00 00 00 18 00 00 00 10 f4 fb 4c 57
## [323] 36 92 9e eb 42 1c 7f f1 95 2d 58 b2 00 00 00 18 00 00 01 00 02 4a 1e
## [346] 52 9f fa 63 33 65 e0 70 0c 2f 85 3f b2 c3 71 5a c5 86 d3 c8 a1 2e 89
## [369] dc bb 38 13 cf 1a 6c 18 be b4 33 06 90 63 be 6a 92 59 b2 23 d2 70 a8
## [392] f2 f1 bf c1 6b 5d be 1a 31 a3 9f 59 8d 3b 40 3f 04 70 85 f3 e2 01 18
## [415] d3 ad 96 30 b0 00 53 54 89 f2 c0 5a 90 e9 f6 c4 70 d9 2e d7 60 42 f2
## [438] 46 ad bc bd ed e6 7a c3 7b 2f f9 ab 40 3f 3a 85 9d 92 d9 17 a5 10 97
## [461] a7 ee f0 eb 8c f4 20 e7 c8 25 81 82 91 1f 4d 0a c2 1b 8c af 58 d8 ae
## [484] 40 1e 72 71 de b4 83 76 b9 26 c9 2e 35 93 ba 8c e6 2e 3f 97 b0 6e 81
## [507] 2d 47 eb f9 5e 81 11 ab e2 ba b1 ec b4 67 45 ce 1c 73 44 8a 23 20 d5
## [530] ae 95 86 4b 69 fe 5a 30 2b f9 14 3b 1c 05 95 a7 bc 0a 06 8c cd 73 bc
## [553] 1f 0e 6e de b9 14 ac f7 5a 85 15 e5 94 b8 af a6 a9 e2 d4 6f d5 bb ab
## [576] e7 d9 c3 15 9e 18 87 6b c3 35 8e 4b a2 b7 f6 20 a0 26 e0 61 15 f2 05
## [599] 00 00 04 02 00 00 00 01 00 04 00 09 00 00 00 05 6e 61 6d 65 73 00 00
## [622] 00 10 00 00 00 04 00 04 00 09 00 00 00 02 69 76 00 04 00 09 00 00 00
## [645] 07 73 65 73 73 69 6f 6e 00 04 00 09 00 00 00 04 64 61 74 61 00 04 00
## [668] 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.

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:

## [1] "WAoAAAACAAMFAgACAwAAAAITAAAABAAAABgAAAAQFqZQPY2gAbr9FZA3zpS3LAAAABgAAAEAB9PVA3feKHx13fxYFGbSfc3U756txV7LRvMbrHwczwgkwiPuoxCE3RU8xD103OVfxfkZTd22SBxhepRh9egBUEH7YR7GRUFN1Y+2iafibwvHVCjFeK26cN+JBFwJ//2XnsguxWogXqsYTBPMjhltO0OMlXUhEraBXmeQMFGWXjRIxZGbutkbwoDQxJ2blIURsd7S77GnF4xXN9lamdxDtTDaoQL50+KgnDG+L98xv/bA7oHuZX9kGop9pTU4L1xZAyUOaeVAP+fE1k5vTJFHU/8GBu+nEw8xT0gNmNGW067bNICC4ajY8tVzZ4uPqTjll/x2xQ3OtEnCvOgK2+8NWgAAABgAAAAQMjhuU9ciU6ngRQyegouUIAAAABgAAAEAB69yOG8PGNa/iskgsiZbShvbjllEz5Dtk+yqZK1UEVGxf/nXjPQnzRkDShrTNbuIUlcC7dzl77UY72PspyyB2s89L5uUHsdF+hEVjBZcjadIYeulvbaN+Syip8sYuvFypl6HqY76aEoIFZreBS1Jiqol46ZR1YLFtu51wSCqa3Ymodf918XQHpj5q+FR+x4D1Moc6KHKdKxq3qP7b2lP2OVvwA561djBb0iPqpUiF5PtLLis6GnPBnHdt3gXlgzletvQX/sMj3jl8apJe0PrWRoYWAnZnjiApxAWyOsCVwE79v4PiToaC5eRfZd0qpprF97rJhrCLmBF5X7/OC26hQAABAIAAAABAAQACQAAAAVuYW1lcwAAABAAAAAEAAQACQAAAAJpdgAEAAkAAAAHc2Vzc2lvbgAEAAkAAAAEZGF0YQAEAAkAAAAJc2lnbmF0dXJlAAAA/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:

## [1] "580a0000000200030502000203000000021300000004000000180000001016a6503d8da001bafd159037ce94b72c000000180000010007d3d50377de287c75ddfc581466d27dcdd4ef9eadc55ecb46f31bac7c1ccf0824c223eea31084dd153cc43d74dce55fc5f9194dddb6481c617a9461f5e8015041fb611ec645414dd58fb689a7e26f0bc75428c578adba70df89045c09fffd979ec82ec56a205eab184c13cc8e196d3b438c95752112b6815e67903051965e3448c5919bbad91bc280d0c49d9b948511b1ded2efb1a7178c5737d95a99dc43b530daa102f9d3e2a09c31be2fdf31bff6c0ee81ee657f641a8a7da535382f5c5903250e69e5403fe7c4d64e6f4c914753ff0606efa7130f314f480d98d196d3aedb348082e1a8d8f2d573678b8fa938e597fc76c50dceb449c2bce80adbef0d5a000000180000001032386e53d72253a9e0450c9e828b9420000000180000010007af72386f0f18d6bf8ac920b2265b4a1bdb8e5944cf90ed93ecaa64ad541151b17ff9d78cf427cd19034a1ad335bb88525702eddce5efb518ef63eca72c81dacf3d2f9b941ec745fa11158c165c8da74861eba5bdb68df92ca2a7cb18baf172a65e87a98efa684a08159ade052d498aaa25e3a651d582c5b6ee75c120aa6b7626a1d7fdd7c5d01e98f9abe151fb1e03d4ca1ce8a1ca74ac6adea3fb6f694fd8e56fc00e7ad5d8c16f488faa95221793ed2cb8ace869cf0671ddb77817960ce57adbd05ffb0c8f78e5f1aa497b43eb591a185809d99e3880a71016c8eb0257013bf6fe0f893a1a0b97917d9774aa9a6b17deeb261ac22e6045e57eff382dba85000004020000000100040009000000056e616d6573000000100000000400040009000000026976000400090000000773657373696f6e00040009000000046461746100040009000000097369676e6174757265000000fe"

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

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

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:

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

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:

As above, she can now send a message:

secret <- cyphr::encrypt_string("secret message", pair_a)
secret
##  [1] 5c d7 6c fa 40 df 22 ba 00 bb b1 22 38 ae 9f 92 0a 3a b2 8f 1b d3 c1
## [24] 89 33 6b c3 8c 62 cc 1f 23 7c 38 1a b7 45 0f 68 1f 42 80 a7 5b 36 e8
## [47] c1 1a 52 39 65 20 74 83

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:

## [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

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).

##   [1] 60 b1 dd 25 28 b0 13 46 98 da 12 2b 7c 16 3a f6 04 13 72 a7 36 d7 a5
##  [24] ac fc 65 48 7c 4e 7f 68 12 fe 47 33 01 bd f3 fb 7e 41 57 1a 3f 96 9c
##  [47] 6a e8 5a b0 32 f0 29 29 4c de c4 8f 8b 95 cc de 2e 0c d4 77 1e 59 a2
##  [70] 0b 78 25 21 af a9 de e6 05 10 55 6a 4c 58 b6 a1 73 5b 9b c0 9b 2d e1
##  [93] a4 ea 24 af 0c 5e fc 4a 09 48 7a 79 84 9f 7f 52 2e 40 b7 8c 64 91 f6
## [116] d6 0c 33 b5 96 a6 34 a5 39 47 3b f2 e9 11 ec ed 65 8d af df 93 46 25
## [139] c0 79 a6 ea 55 e2 c0 af 10 da 76 17 08 50 f0 8d 53 b9 a3 28 26 22 5c
## [162] eb 8b a5 fc e2 3a a0 85 d8 43 9d 86 21 4f e4 46 1d e5 22 10 b2 df

The data can be decrypted with the decrypt_object function:

## $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)

##  [1] 4c 1a 0f 87 39 3e c3 33 f5 85 34 62 8c a8 3e fb e9 23 2d 7c 3c db f3
## [24] b7 92 a4 5c 13 7d 06 e9 0b 83 5b b1 a3 ff 9c 31 c8 c4 29 b1 ef 8d d1

and decrypt:

## [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:

##   [1] af 51 8a 6f 3f 66 01 25 27 2d 7d 13 ff 73 91 8e d4 a7 ea 86 29 54 71
##  [24] 1d d6 cf bb dd 93 3d 00 bb b2 81 18 37 1b b8 a1 eb 00 40 62 11 a2 7d
##  [47] 80 1c 14 38 31 02 b0 5b a9 f2 6c 59 cc 6f 31 35 6c 0b e5 3a 19 1d 6f
##  [70] c4 1d f1 cc 35 2b c0 81 8d fe c7 34 73 b3 e6 04 a2 80 9b 80 d4 62 a4
##  [93] 78 a6 18 fd 6e 34 95 42
##   [1] 74 46 a2 13 bc ea a6 b5 37 d7 59 d9 5d b2 52 17 aa 7c c1 2d 13 fc 5c
##  [24] 35 cc e3 70 d1 b2 9a 21 a4 06 33 e5 03 f6 bd 01 d9 ff 7b 51 a5 7c 2c
##  [47] 96 64 76 4d d0 9d 69 0f c7 c2 e1 58 71 f8 69 c7 db 1a 9e ea 3d 15 d0
##  [70] 10 01 69 b9 57 6f 40 5d 1e da 86 63 96 e1 68 6e 92 d8 6a bb aa 47 a7
##  [93] 73 b4 7e 28 0c 8e 30 8c be 89 9c 5a 1e 99 2b 9a 6c 2d b1 7b 46 a5 54
## [116] 0c 27 4d 96 bc d9 df 60 ae 8c c8 12 ac 9f db 28 3d a6 82 1e 8d c4 52
## [139] 61 14

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

which we can use to encrypt a secret string

and decrypt it:

## [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

## Error in is.raw(key): 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?