2

I have an R script that invokes a system call passing sensitive data as arguments to a Python script. I want to use RSA to encrypt these arguments before passing them. Then decrypt them in the Python script.

Following suggestions here and here

R:

# main.R
library(PKI)

key <- PKI.genRSAkey(2048L)
PKI.save.key(key, target = "privkey.pem")
msg <- charToRaw("password")
msg.e <- PKI.encrypt(msg, key)

result = system2("python", args = c("dostuff.py", msg.e), stdout = TRUE)
print(result)

Python:

# dostuff.py
import Crypto
from Crypto.PublicKey import RSA
import ast, sys

key = RSA.importKey(open('privkey.pem').read())

encrypted = sys.argv[1]
decrypted = key.decrypt(ast.literal_eval(str(encrypted)))
print("Decryption returned:", decrypted)  # decrypted != "password" :(

When I try this, I get a long string of digits (not "password"), or it errors out when I try b64decode (binascii.Error: Incorrect padding). I get a lot of different errors usually due to improperly reading and decoding binary, hex, and their string representations.

The fact that PKI.encrypt requires raw input is part of the problem. I'm not sure how Python is reading this, how I should convert it, and interpret the result when it returns to R.

Wassadamo
  • 1,176
  • 12
  • 32
  • `charToRaw` converts a length-one character string to raw bytes, so your R code is failing even before encryption. Furthermore, you may be forgetting to explicitly convert the output of `decrypt` to a string by performing character decoding. – Maarten Bodewes Oct 19 '19 at 23:42
  • `charToRaw` returns raw bytes *for each* character in the string. And `PKI.encrypt` needs raw input, so I see nothing wrong there. When I try doing `key.decrypt(encrypted).decode()` I get "OverflowError: cannot fit 'int' into an index-sized integer" – Wassadamo Oct 20 '19 at 03:38
  • I'm also confused because the encrypted message appears to be different every time I run this, even if I `set.seed(100)` – Wassadamo Oct 20 '19 at 03:40
  • OK, I was quoting the actual API there, although I forgot about the quotation marks. RSA (which I presume is RSA using PKCS#1 v1.5 compatible padding) uses random padding, so the generation of different ciphertext is actually expected and even required (otherwise you would leak data if you encrypt the same message multiple times, after all). – Maarten Bodewes Oct 20 '19 at 03:45

0 Answers0