jeroen / openssl

OpenSSL bindings for R
Other
65 stars 23 forks source link

Error when trying to decrypt encrypted message. #106

Closed jcrodriguez1989 closed 1 year ago

jcrodriguez1989 commented 1 year ago

Am I doing something wrong here?

With this message to_encrypt I get an error:

> library(openssl)
> keys <- rsa_keygen()
> to_encrypt <- "some_message_to_encrypt"
> encrypted_msg <- base64_decode(to_encrypt) |> 
+   rsa_encrypt(keys$pubkey) |> 
+   base64_encode()
> base64_decode(encrypted_msg) |> 
+   rsa_decrypt(keys) |> 
+   base64_encode()
Error: OpenSSL error in (null): (null)

With this message I get a different decrypted message:

> library(openssl)
> keys <- rsa_keygen()
> to_encrypt <- "aaaaa" # five 'a's.
> encrypted_msg <- base64_decode(to_encrypt) |> 
+   rsa_encrypt(keys$pubkey) |> 
+   base64_encode()
> decrypted <- base64_decode(encrypted_msg) |> 
+   rsa_decrypt(keys) |> 
+   base64_encode()
> decrypted
[1] "aaaa"
> to_encrypt == decrypted
[1] FALSE
jeroen commented 1 year ago

It makes no sense to use base64_decode(to_encrypt), you should only use base64_decode to decode a string in base64 format, which you have previously encoded with base64_encode(). What are you trying to do? This works:

library(openssl)
keys <- rsa_keygen()
to_encrypt <- "some_message_to_encrypt"
encrypted_msg <- charToRaw(to_encrypt) |> 
   rsa_encrypt(keys$pubkey) |> 
   base64_encode()
base64_decode(encrypted_msg) |> 
   rsa_decrypt(keys) |>
  rawToChar()
jcrodriguez1989 commented 1 year ago

Awesome! Thanks @jeroen , I thought that, in openssl, we used base64_decode/base64_encode instead of charToRaw/rawToChar. It is completely clear now. Thanks!