2

I'm trying to run two simple functions that I wrote for PyCrypto with PyCryptodome. Here are the functions with the related class member definitions:

import Crypto.PublicKey.RSA as RSA

class MyRSA():    
    n = "123..." # these are actually very long string...
    p = "345..."
    u = "567..."
    q = "789..."
    e = long(65537)
    t = (long(n), e, long(d), long(p), long(q), long(u))
    key = RSA.construct(t)

    def DecryptText(self, text):            
        chunk_size = 128
        enc_vec = [text[i:i+chunk_size] for i in range(0, len(text), 
                                                       chunk_size)]
        plain_text = ''
        for x in enc_vec:
            plain_text +=  MyRSA.key.decrypt(x)        
        return plain_text

    def EncryptText(self, text):
        chunk_size = 128
        text_vec = [text[i:i+chunk_size] for i in range(0, len(text), 
                                                        chunk_size)]
        enc_text = ''
        for x in text_vec:
            enc_text += MyRSA.key.encrypt(x, '')[0]            
        return enc_text

The two functions EncryptText and DecryptText use the PyCrypto methods encrypt and decrypt which are no longer mantained in PyCryptodome (a NotImplemented error is raised when they are called by external code). Can anyone help me to convert them to code which is compliant with PyCryptodome? Thanks in advance!

Gad82
  • 91
  • 8

2 Answers2

2

This isn't the question you asked, but please be aware there is a significant cryptographic weakness in your EncryptText. You split up your messages into chunks and encrypt each one. This method is roughly the same as symmetric encryptions's ECB mode, and so it shares the same weakness:

a) An attacker is able to reorder the chunks of a message, or swap them between different encryptions.

b) Chunks that are repeated are visible, giving the attacker clues as to how to decrypt the message.

Alex Gaynor
  • 14,353
  • 9
  • 63
  • 113
1

A fundamental component of RSA encryption is padding. Pycrypto used to expose the raw decrypt and encrypt methods for an RSA key object (the ones you use), but that is wrong and insecure, because they don't implement any padding.

Instead, you should use the module Crypto.Cipher.PKCS1_OAEP (the only option in pycryptodome), which securely takes care of the padding.

  • 1
    Will this allow me to decrypt old encrypted data? if yes, is there any resource to guide me to perform the migration? – Gad82 Mar 04 '19 at 22:01