简体   繁体   中英

In R cyphr, how can I encrypt (symmetric) a string or file, save the ws, reload it and then decrypt the file or string, as simply as possible?

I'm just learning to use cyphr and doing a very simply exercise, but having a problem that involves session keys. I want to encrypt a file and then, at some later date & time, decrypt, but I ran into the problem below. I'm the only one who will be encrypting and decrypting the file, and occasionally modifying the file. Here's what happened.

library(cyphr)

# SimpFile is a simple character file of length 107.
cykey123022 <- cyphr::key_sodium(sodium::keygen()) # generate a cyphr key 
encrypt_file("SimpFile.txt", cykey123022, dest = "SimpFile.enc")
# That worked.
decrypt_file("SimpFile.enc", cykey123022, dest = "SimpFile.dec")
# That worked too.

Another session: reloaded R and the workspace.

library(cyphr)

decrypt_file("SimpFile.enc", cykey123022, dest = "SimpFile.dec")   
Error: Failed to decrypt key as session key has changed

The problem now is that, while I understand the purpose of the session key, I haven't been able to reset it or to do the simple task I'm trying to do. By the way, I'm happy, in this particular case, to dispense with session keys all together if I can. I would be happy to simply encrypt the file, hide the encryption key and then reload the same key at the later time in order to decrypt the file.

How can I do that most simply?

I already described what happened in the previous frame. I expected to be able to decrypt the file but couldn't. When I tried to do that, I got the following error message:

Error: Failed to decrypt key as session key has changed

Your decryption commands should probably not have the same input and output file names - you are overwriting the encrypted file each time. I don't think that's the source of the issue but worth trying decrypt_file("SimpFile.enc", cykey123022, dest = "SimpFile_2.txt")

Also, check: https://cran.r-project.org/web/packages/cyphr/vi.nettes/cyphr.html

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM