3

I install pip install pycryptodome on Python 3.7.2. I'm getting above exception for obj = AES.new(key, AES.MODE_CBC, iv) line. my code is:

from Crypto import Random
from Crypto.Cipher import AES
import random

def get_encryption():
    try:
        str = "This is input string"

        key = b'abcdefghijklmnop'  
        iv = Random.new().read(AES.block_size)

        obj = AES.new(key, AES.MODE_CBC, iv)
        encrypted = obj.encrypt(str)
        print(encrypted)
    except Exception as e:
        print(e)

I tried to all the way but not getting how to solve it.

Anil Jagtap
  • 1,740
  • 4
  • 27
  • 44

3 Answers3

3

After tried all the way I got solution. I converted key string into bytes. code is:

from Crypto import Random
from Crypto.Cipher import AES
import random

def get_encryption():
    try:
        strmsg = "This is input string"

        key = 'abcdefghijklmnop'  
        key1 = str.encode(key)

        iv = Random.new().read(AES.block_size)

        obj = AES.new(key1, AES.MODE_CBC, iv)
        encrypted = obj.encrypt(str.encode(strmsg))
        print(encrypted)
    except Exception as e:
        print(e)
Anil Jagtap
  • 1,740
  • 4
  • 27
  • 44
1

//First pip install pycryptodome -- (pycrypto is obsolete and gives issues) // pip install pkcs7

from Crypto import Random
from Crypto.Cipher import AES
import base64
from pkcs7 import PKCS7Encoder
from app_settings.views import retrieve_settings # my custom settings

app_secrets = retrieve_settings(file_name='secrets');


def encrypt_data(text_data):
                    #limit to 32 bytes because my encryption key was too long
                    #yours could just be 'abcdefghwhatever' 
    encryption_key = app_secrets['ENCRYPTION_KEY'][:32]; 

    #convert to bytes. same as bytes(encryption_key, 'utf-8')
    encryption_key = str.encode(encryption_key); 
    
    #pad
    encoder = PKCS7Encoder();
    raw = encoder.encode(text_data) # Padding
    iv = Random.new().read(AES.block_size )

                                 # no need to set segment_size=BLAH
    cipher = AES.new( encryption_key, AES.MODE_CBC, iv ) 
    encrypted_text = base64.b64encode( iv + cipher.encrypt( str.encode(raw) ) ) 
    return encrypted_text;
Growyn
  • 31
  • 3
0

The easiest way to convert the string to bytes is using the binascii lib:

from binascii import unhexlify, hexlify

def aes_encript(key, msg):
    c = unhexlify(key)
    m = unhexlify(msg)
    cipher = AES.new(c, AES.MODE_ECB)
    msg_en = cipher.encrypt(m)
    return hexlify(msg_en)
Ohads
  • 63
  • 1
  • 1
  • 6