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.