'Decrypt openssl string with Python crypted by asymetric key paired openssl R

I've used in R

crypted <- cyphr::encrypt_string("secret", key=cyphr::keypair_openssl("~/.ssh/id_rsa_given.pub","~/.ssh/id_rsa"))

and

decrypted <- cyphr::decrypt_string(crypted,cyphr::keypair_openssl("~/.ssh/id_rsa_given.pub","~/.ssh/id_rsa")

This works in R, both : crypt and decrypt.

But I don't find how to read this crypted string in Python.

REPREX

R

bash

ssh-keygen -t rsa -f mykeytest

ls -g -o mykeytest*
# -rw------- 1 2655 Mar  4 10:08 mykeytest
# -rw-r--r-- 1  577 Mar  4 10:08 mykeytest.pub
 

R without external file

crypted <- cyphr::encrypt_string("mysecret", key=cyphr::keypair_openssl("mykeytest.pub","mykeytest"))
decrypted <- cyphr::decrypt_string(crypted,cyphr::keypair_openssl("mykeytest.pub","mykeytest"))
decrypted
# [1] "mysecret"

R with external file

writeBin(cyphr::encrypt_string("mysecret", key=cyphr::keypair_openssl("mykeytest.pub","mykeytest") ), "mysecret.txt")
mydecrypted2<-cyphr::decrypt_string(readBin("mysecret.txt", base::raw(), file.size("mysecret.txt")), 
              cyphr::keypair_openssl("mykeytest.pub","mykeytest") 
)
mydecrypted2
# [1] "mysecret"

Python

Beginning of my POC Python

import sys
import sshpubkeys
import os

f_pub = open("mykeytest.pub", "r")
f_priv = open("mykeytest", "rb")
f_string_mysecret=  open("mysecret.txt", "rb")

key_pub=f_pub.read()
key_priv=f_priv.read()
input_string=f_string_mysecret.read()


# https://github.com/ojarva/python-sshpubkeys
ssh_pub=sshpubkeys.SSHKey(key_pub)
ssh_pub.parse()
ssh_pub.rsa

#  https://stackoverflow.com/questions/59029092/how-to-load-openssh-private-key-using-cryptography-python-module/69758595#69758595

from cryptography.hazmat.primitives.serialization import load_ssh_private_key
from hashlib import sha1

key_priv_b = load_ssh_private_key(key_priv,b'mypassword')



And after ?

That is the question ?

Have you a pure python answer to decrypt string from cyphr::encrypt_string() and cyphr::keypair_openssl()

Workaround with rpy2

import rpy2.robjects as R
myfct = R.r(r'''
  library(cyphr)
  function(myfile) {
    cyphr::decrypt_string(
      readBin(myfile, base::raw(), file.size(myfile)),
      cyphr::keypair_openssl("mykeytest.pub","mykeytest") )
  }
''')
myfct("mysecret.txt")
# <rpy2.robjects.vectors.StrVector object at 0x7f0512114100> [RTYPES.STRSXP]
# R classes: ('character',)
# ['mysecret']

# in string : 

myfct("mysecret.txt")[0]
# 'mysecret'

An it works for my real issue.

Path of the R source of cyphr::decrypt_string()

But is it so special to R ? There is not standard python implementation ?

Path of the R source and C Source if I have well understood

Links at the start of my question:



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source