jeroen / openssl

OpenSSL bindings for R
Other
63 stars 20 forks source link

aes-gcm requires an iv of length 12 #51

Closed dansmith01 closed 6 years ago

dansmith01 commented 6 years ago

I'm getting a strange error from openssl after updating it and it's dependencies to the latest version. (R 3.4.1)

install.packages("openssl", dependencies=TRUE)
# Necessary to restart R at this point before continuing to see the error
data <- serialize("Secret Text", connection=NULL)
key <- openssl::sha256(charToRaw("password"))
openssl::aes_gcm_encrypt(data, key)

Error in aes_any(data, key, iv, TRUE, mode) : aes-gcm requires an iv of length 12

It's fixable by overriding the default IV length of 16 with 12: openssl::aes_gcm_encrypt(data, key, iv=openssl::rand_bytes(12))

However, I have a large database of encrypted objects that were created with IVs of length 16. Is it possible to get backwards-compatibility working?

Thanks! ~ Dan

jeroen commented 6 years ago

Hmm that certainly was not intended. So you are not able to decrypt your object anymore? It doesn't work to just take the initial 12 bytes of the stored IV?

dansmith01 commented 6 years ago

Downgrading to openssl 0.9.6 seems to fix it also:

v096 <- "https://cran.r-project.org/src/contrib/Archive/openssl/openssl_0.9.6.tar.gz"
install.packages(v096, repos=NULL, type="source")
# Restart R
data <- serialize("Secret Text", connection=NULL)
key <- openssl::sha256(charToRaw("password"))
openssl::aes_gcm_encrypt(data, key)

Taking the first 12 bytes of the existing IVs works too! That will fix my immediate issue. Thanks!

jeroen commented 6 years ago

OK so I just need to fix the default argument of IV to be 12 bytes? Sorry that I overlooked this. It seems like it was introduced by the PR here: https://github.com/jeroen/openssl/commit/d37e45c20eea6e71ad001720c7be63500877ecaa#diff-9d7743442ddaf9e73e05736d45a79a28 but the corresponding R code was not updated.

jeroen commented 6 years ago

Fixed default arg: https://github.com/jeroen/openssl/commit/9d95914ae51f7dab1161c5879021c43a79c85afd

jeroen commented 6 years ago

So you are certain you can decrypt the keys with openssl 0.9.7 just by taking the first 12 bytes of the IV? No need to remove the 12 byte restriction to get to your data?

dansmith01 commented 6 years ago

Leaving the restriction in there might break some existing code for others, but for my purposes truncating to just the first 12 IV bytes is all I need to do to get it working.

jeroen commented 6 years ago

OK that confirms my guess that when you were passing and IV of 16 bytes, only the first 12 bytes were actually used in the encryption. In that case it seems appropriate to leave the length-check as it is right now.

Thanks for reporting this! I have fixed the default IV to be 12 bytes so I'm closing the issue now. Feel free to open a new one if there turns out to be more to it!

dansmith01 commented 6 years ago

Nice! Thank you for the super-fast response!