I have following python lambda function
lambda_function.py
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad,unpad
import base64
#CBC with Fix IV
data = 'random text to be encrypted decrypted'
key = 'xxx' #16 char for AES128
#FIX IV
iv = 'yyy'.encode('utf-8') #16 char for AES128
def encrypt(data,key,iv):
data= pad(data.encode(),16)
cipher = AES.new(key.encode('utf-8'),AES.MODE_CBC,iv)
return base64.b64encode(cipher.encrypt(data))
def decrypt(enc,key,iv):
enc = base64.b64decode(enc)
cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv)
return unpad(cipher.decrypt(enc),16)
encrypted = encrypt(data,key,iv)
print('encrypted CBC base64 : ',encrypted.decode("utf-8", "ignore"))
decrypted = decrypt(encrypted,key,iv)
print('decrypted data: ', decrypted.decode("utf-8", "ignore"))
def lambda_handler(event, context):
encrypt(data, key, iv)
I created a lambda function using runtime python 3.12 and created a layer called custom_encrypt_decrypt
and added this layer to the lambda as shown below,
When I try to execute the lambda, it throws error,
"Unable to import module ‘lambda_function’: No module named ‘Crypto’"
Firstly, I found that I have to use pycryptodome python library.
How I uploaded this library to lambda
-
in my local computer I added the library,
pip install pycryptodome
It added these two folders in my local
- I selected both the folders and created a .zip folder.
- uploaded zip folder to
custom_encrypt_decrypt
layer (and layer is already attached to lambda) – Note: pointing to right layer version. - Executed lambda again and getting the same error again n again.
NOTE: If I run this python code locally, it works using same pycryptodome library!
2
Answers
If the the zip file wasn’t packed with the correct structure, AWS won’t find your libraries. The structure has to be created as following:
You can check full desciption in link below:
https://docs.aws.amazon.com/lambda/latest/dg/packaging-layers.html#packaging-layers-paths
I was facing the same issue after some troubleshooting, I was able to fix the issue.
Create Zip file in below mentioned path:
Make sure the ZIP file is created for all folder available in python folder Don’t miss out any files or folders it may be our main package may be dependent on it.