Search code examples
pythonpython-3.xencryptionrsapublic-key-encryption

RSA decryption in Python how i can get a bytes array?


I am trying to use RSA with Python.

I do encryption from .net with the public key generated in Python. Everything going fine for encryption. When i decrypt my crypted sentence i am not able to bring back to the right value.

How can i convert back my value to a bytes array ? I am sure i am close ... but did not find nothing

I encrypt this bytes array with my public key, but when i decrypt i am not able to get it back

 [0]    3   byte
 [1]    180 byte
 [2]    214 byte
 [3]    196 byte
 [4]    37  byte
 [5]    120 byte
 [6]    213 byte
 [7]    71  byte
 [8]    143 byte
 [9]    64  byte
 [10]   168 byte
 [11]   245 byte
 [12]   172 byte
 [13]   178 byte
 [14]   120 byte
 [15]   114 byte

The public key i used is :

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwsfuJS3TFA5KmzBiFdpS
jl4gBG/oiQcd8JhB2hS2xi/3d/HnyQwzVFbnIuRFWxCSPbbO0M0IC2bE8g0ekWDj
b3YsW7POjVpz6xl/VfcTECIDq0/yGDj5O/FYWx8BGtaPTiTNHq7a5DUUANreYHuB
vzEYyr5lLzsSmZ9pG1BikR0dU5p01g64zJDNtYv6iHvIRseP/2T+Jv44XBLA0eBz
m7Q84dCIX/W8LjV6a6bp4kxBUJ4LYjG2BDslx7ZQMHz7gRFhauNQhyTGXTSLULY+
Q+fhUYhoL+RZjddlO/bn7fG1Evc6TiQi165/ZtfQuCJhkuet4q+Q5jUdUiLTUAfj
gwIDAQAB
-----END PUBLIC KEY-----

My private key is :

-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAwsfuJS3TFA5KmzBiFdpSjl4gBG/oiQcd8JhB2hS2xi/3d/Hn
yQwzVFbnIuRFWxCSPbbO0M0IC2bE8g0ekWDjb3YsW7POjVpz6xl/VfcTECIDq0/y
GDj5O/FYWx8BGtaPTiTNHq7a5DUUANreYHuBvzEYyr5lLzsSmZ9pG1BikR0dU5p0
1g64zJDNtYv6iHvIRseP/2T+Jv44XB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bUgjExfDfZJHxRH1IF0N4Osn5kpOSBsJ1LI2D07NOf4Zho/jhT01hl
gy56UyhvoGoUuXildDDoHkcgX8tux6qDDh41mgAufmVmHALgPcaTTIcsbD6kFr54
pBelSQKBgFXQSjj0XGHgDbe0ZRAcFgSuiKarnU2Ddms0Jc2eP+KnPFV+vPDOA8L0
Oo3RN9A8J9nUfbeiy/u/Vm8DcvdHxFIBPITcXTGDEz6ikI258QSCNFUaHwVICws7
598VcG9BkuTt0PJXQaTR1aWBBEBAhQ+iIig093Cb6ZZ/7pYz7WCj
-----END RSA PRIVATE KEY-----

The output i received is :

b"\x02-qf\xcc\xf8\x1c\xdc_bV\xa7\x84o\xc7K2k\xe6\xf0\xd4\x8e\x96\xef9\xbb\xe7%j\xa4h\xd5\xcd\xc1c\x0b\t\x98\x9d\xde\xd9\xe7\xe0druq\x90\xfc\xa5O\xd5\xd4\xb6\xec>\xbb($\x02u^\xb8\xe0\xd2W\x8bzL\x1f\xc0\x05\x1c\xf1\xea7\x99\x06\xd0\xa7ov\xa8A\xc3\x0b\x03\xf9\x1a\xac\x92Gn\xa7\xf0\x93v\xd0\xda\x89)G8\xc2e\xd4\xf5\te\x97\xcf a\x9e\xb5\xeei\xc4\xfci\xcd=/\xd3\xa5\x1fE\x0e\xcf\xaeD\x9fHA\x930\xa9EV\xee\x83\x17f\xe9\xc1\xb4\xc7s\xef%F\xb6!\xb4j\x14\xd4\xf1K\xa3r\x90\xbfI\xfd;\xca>zUcR\x16m\x82\x81iz\xb4C\xed\x1e\xdc\xa9\xfc\x0f\x87\xd7-\xde\x9f(l\x042^e\x84\x15\xb2k\x08\x82@\xd3m\x7f\x95\xabvM\xe6\x88\xb2;_\x0f'\xae\xdbvp\x83\xd6\xba\xc0F\x16\x87\xf1\xf0Y\x1fF~L\x18\x1d\x00\x03\xb4\xd6\xc4%x\xd5G\x8f@\xa8\xf5\xac\xb2xr"

There is my code

I get a CryptoHelper.py

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Util import number

import base64

class CryptoHelper:
    PrivateKeySize = 2048 
    def CreateRSA_CSP(self):       
        csp = RSA.generate(self.PrivateKeySize)           
        return csp
    def GetRSA_PublicKey(self, csp):
        return str(csp.publickey().exportKey(format='PEM'),"utf-8")
    def RSAEncrypt(self,publicKEY,byteArray):
        csp =  RSA.importKey(publicKEY);
        encrypted = csp.encrypt(byteArray)
        return base64.standard_b64encode(encrypted)
    def RSADecrypt(self,csp, byteArray):
        return csp.decrypt(byteArray)

That is my HandShakeHelper.py

import json
import requests
import base64
import uuid
from Helpers import CryptoHelper

class HandShakeHelper:
    CSP = None
    CryptoHelper = None

    def __init__(self,serial,endPoint):
        self.Serial = serial
        self.EndPoint = endPoint    
    def GenerateHandShakeKey(self):        
        self.CryptoHelper = CryptoHelper.CryptoHelper()
        self.CSP = self.CryptoHelper.CreateRSA_CSP()
        self.InitializeHandShake()
    def InitializeHandShake(self):
        print(str(self.CSP.exportKey(format='PEM'),"utf-8"))
        print(self.CryptoHelper.GetRSA_PublicKey(self.CSP))
        headers = { "Content-Type" : "application/json" }
        args = '{ args : { "Publickey" : "' + self.CryptoHelper.GetRSA_PublicKey(self.CSP) + '", "Serial" : "' + self.Serial + '" }}'
        answer = requests.post(url = self.EndPoint +"/InitializeHandShake", headers=headers, data = args)
        se_answer_raw = json.loads(answer.text)
        se_answer = se_answer_raw["d"]
        if(se_answer["Status"]==200):           
            cryptedBase64HandShakeId = base64.standard_b64decode(se_answer["CryptedHandShakeID"])  

            decryptedBytes = self.CSP.decrypt(cryptedBase64HandShakeId)
            print(decryptedBytes)

The handshakehelper call a webservice. Send the public key to the server, and the server return encrypted with the public key a CryptedToken that I try to decrypt.

That is my Test.py

from Helpers import HandShakeHelper, CryptoHelper 



handShake = HandShakeHelper.HandShakeHelper("8047771c-b1b0-408d-91ad-eacbc03ae6ca","http://www.localhost.com/webservice.asmx")
handShake.GenerateHandShakeKey()

The .net part is this

CryptoHelper.EncryptRSAContent(clientPublicKey, MyGuid.ToByteArray(), false)

public static byte[] EncryptRSAContent(string publicKey, byte[] content, bool fOAEP)
    {
      byte[] cryptedData = null;
      using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
      {
        if (publicKey.StartsWith("<RSAKeyValue>"))
        {
          RSA.FromXmlString(publicKey);
        }
        else
        {

          PEMCrypto.ImportPublicKey(publicKey, RSA);
        }

        cryptedData = RSA.Encrypt(content, fOAEP);
      }
      return cryptedData;
    }

Solution

  • Thanks to @t.m.adaam it's working fine

    I correct my CryptoHelper.py with that version

    from Crypto.PublicKey import RSA
    from Crypto.Cipher import PKCS1_v1_5
    from Crypto.Util import number
    from Crypto import Random
    
    import base64
    
    class CryptoHelper:
        PrivateKeySize = 2048     
        def CreateRSA_CSP(self):       
            csp = RSA.generate(self.PrivateKeySize)
            return csp
        def GetRSA_PublicKey(self, csp):
            return str(csp.publickey().exportKey(format='PEM'),"utf-8")
        def RSAEncrypt(self,publicKEY,byteArray):
            csp =  RSA.importKey(publicKEY);
            rsa_csp = PKCS1_v1_5.new(csp)
            return base64.standard_b64encode(rsa_csp.encrypt(byteArray))
        def RSADecrypt(self,csp, byteArray):
            sentinel = Random.new().read(256)
            rsa_csp = PKCS1_v1_5.new(csp)
            return rsa_csp.decrypt(byteArray,sentinel)