NameError while calling module, declaring default values in a class function - python-3.x

I'm trying to understand Public Key encryption so I wrote this little module using PyCryptodome and the RSA/PKCS1_OAEP module on Python 3 to help me along. However, I keep getting an error:
NameError: name 'aesenc' is not defined
This is a two part question:
In standalone code (outside a class) the arg = default_val code will work, but I'm pretty sure this code will throw an error (assuming I fix question #2). I also know I can't use self.default_val as that needs an object to be created first. How do I assign a default value (in this case, the private/public key of the object?)
With regard to the error message, a vgrep reveals that the suite has been declared before its been called but I still get the NameError. Can someone please take a look and let me know what I'm doing wrong?
Modules: (Breaking into parts as SO keeps jumbling the code)
from passlib.context import CryptContext
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.PublicKey import RSA
from Crypto import Random
from Crypto.Random import get_random_bytes
The Class:
class statEnc:
pubcipher = None
privcipher = None
pubkeystr = None
privkeystr = None
sessionkey = None
def __init__(self, pubkeystr = None, privkeystr = None, sessionkey = None):
self.pubkeystr = pubkeystr
self.privkeystr = privkeystr
self.sessionkey = sessionkey
if pubkeystr == None or privkeystr == None: #if blank, generate keys
self.random_generator = Random.new().read
self.keys = RSA.generate(1024, self.random_generator)
self.pubkey = self.keys.publickey()
self.pubkeystr = self.pubkey.exportKey(format='PEM',
passphrase=None,
pkcs=1)
self.pubcipher = PKCS1_OAEP.new(self.pubkey)
self.privcipher = PKCS1_OAEP.new(self.keys)
self.privkeystr = self.keys.exportKey(format='PEM',
passphrase=None,
pkcs=1)
self.privkey = self.keys.exportKey()
else: #import the keys
self.pubkey = RSA.importKey(pubkeystr)
self.pubcipher = PKCS1_OAEP.new(pubkey)
self.privkey = RSA.importKey(privkeystr)
self.pubcipher = PKCS1_OAEP.new(privkey)
if sessionkey == None:
sessionkey = get_random_bytes(16)
else:
self.sessionkey = sessionkey
def encrypt_val(self, session_key, cipher = pubcipher):
# a little ditty to hep encrypt the AES session key
try:
session_key = session_key.encode('utf8')
except:
pass
ciphertext = cipher.encrypt(session_key)
return ciphertext
def decrypt_val(self, ciphertext, cipher = privcipher):
# a little ditty to hep decrypt the AES session key
session_key = cipher.decrypt(ciphertext)
try:
session_key = session_key.decode('utf8')
except:
pass
return session_key
def aesenc(self, data, *args):
#encrypt the payload using AES
key = ''
if args:
if 'str' in str(type(args[0])):
try:
key = int(args[0])
except:
key = get_random_bytes(16)
else:
key = get_random_bytes(16)
try:
data = data.encode('utf8')
except:
pass
cipher = AES.new(key, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(data)
aesencdict = {
'ciphertext' : ciphertext,
'tag' : tag,
'nonce' : cipher.nonce ,
'key' : key
}
return(aesencdict)
def aesdec(self, aesdict):
#decrypt the AES encrypted payload
cipher = AES.new(aesdict['key'], AES.MODE_EAX, aesdict['nonce'])
data = cipher.decrypt_and_verify(aesdict['ciphertext'], aesdict['tag'])
try:
data = data.decode('utf8')
except:
pass
return data
def end2enc(self, val, cipher = pubcipher):
# a master function to first encrypt the payload
val = str(val)
encval = aesenc(val)
# and then PK encrypt the key
encval['key'] = encrypt_val(encval['key'], cipher)
return encval
def end2dec(self, encval, cipher = privcipher):
encval['key'] = decrypt_val(encval['key'], cipher)
outval = aesdec(encval['aesdict'], encval['key'])
return outval
Test function and main:
def test():
val = { 'test' : "hello"}
keypair = statEnc()
print(str(type(keypair)))
encval = keypair.end2enc(val, keypair.pubcipher)
outval = keypair.end2dec(encval, keypair.privcipher)
print(val, outval)
if val == eval(outval):
return(val)
else:
return False
if __name__ == '__main__':
test()
[UPDATE]
The Traceback is as follows:
[guha#katana stat]$ python statenc.py
<class '__main__.statEnc'>
Traceback (most recent call last):
File "statenc.py", line 124, in <module>
test()
File "statenc.py", line 115, in test
encval = keypair.end2enc(val, keypair.pubcipher)
File "statenc.py", line 100, in end2enc
encval = aesenc(val)
NameError: name 'aesenc' is not defined

Slept over my question and woke up with a fresh mind, and voila! the answer presented itself.
The answer to the second question is as follows:
2. putting a simple 'self.' solves the problem - i was calling 'aesenc(params)' instead of 'self.aesenc(params)'. Stupid of me, really.
Question 1 is answered in this SO question.

Related

Implementing Laravel crypt and decrypt functions in python

I was able to find the decrypt function with a few researches, and now
I am trying to write laravel encrypt function using python.
I can decrypt using it:
class decrypter:
def __init__(cls, key):
cls.key = key
def decrypt(cls, text):
decoded_text = json.loads(base64.b64decode(text))
iv = base64.b64decode(decoded_text['iv'])
crypt_object = AES.new(key=cls.key, mode=AES.MODE_CBC, IV=iv)
decoded = base64.b64decode(decoded_text['value'])
decrypted = crypt_object.decrypt(decoded)
return unpad(decrypted, 16).decode('utf-8')
def decrypt_string(str):
try:
key = b"xxxx+xxxxxx+x+xxxx+xxxxx"
key = base64.b64decode(key)
msg = str
obj = decrypter(key)
decrypted = obj.decrypt(msg)
return decrypted
except Exception as e:
logla.logla(e, "decrypt_string")
print(e)
But I couldn't find a source for the encrypt method. There is a source I could find, but I couldn't run it.
enter link description here
For encryption, proceed in the opposite direction:
Create an IV
Pad plaintext
Save IV and ciphertext to JSON
Encode JSON with Base64
For encryption as in the linked code, additionally the MAC has to be generated and the PHP serialization has to be used:
import json
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
from Crypto.Hash import HMAC, SHA256
from phpserialize import loads, dumps
class encrypter:
def __init__(cls, key):
cls.key = key
def encrypt(cls, text):
text = dumps(text)
msg = pad(text, 16)
iv = get_random_bytes(16) # b'0123456789012345'
crypt_object = AES.new(key=cls.key, mode=AES.MODE_CBC, IV=iv)
encrypted = crypt_object.encrypt(msg)
ivB64 = base64.b64encode(iv)
encryptedB64 = base64.b64encode(encrypted)
mac = HMAC.new(cls.key, digestmod=SHA256).update(ivB64+encryptedB64).hexdigest()
json_string = json.dumps({'iv': ivB64.decode(), 'value': encryptedB64.decode(), 'mac': mac})
return base64.b64encode(json_string.encode())
def encrypt_string(str, key):
try:
msg = str.encode()
obj = encrypter(key)
encrypted = obj.encrypt(msg)
return encrypted
except Exception as e:
print(e)
# Test
keyB64 = b'MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE='
key = base64.b64decode(keyB64)
plaintext= 'This is a test plaintext'
encrypted = encrypt_string(plaintext, key)
decrypted = decrypt_string(encrypted, key)
print(encrypted)
print(base64.b64decode(encrypted))
For the test-IV b'0123456789012345' the output is:
b'eyJpdiI6ICJNREV5TXpRMU5qYzRPVEF4TWpNME5RPT0iLCAidmFsdWUiOiAiTlE1djFpaWU1QnFoTWNwRlhNdUFSZ2N3YVlrNG5CZlJyYmRKUGRna3FDcUN6NEZ6ZDhSOHhIUy95N1N3TWlQTyIsICJtYWMiOiAiYmYwNGJjMWEyN2NhNWUzMGFlYTdjZTI4Y2FkYTBlZGVjOGEwMzc3NWZhODVhMDc2MGRhODUzNDc1OTBmYmNmZCJ9'
b'{"iv": "MDEyMzQ1Njc4OTAxMjM0NQ==", "value": "NQ5v1iie5BqhMcpFXMuARgcwaYk4nBfRrbdJPdgkqCqCz4Fzd8R8xHS/y7SwMiPO", "mac": "bf04bc1a27ca5e30aea7ce28cada0edec8a03775fa85a0760da85347590fbcfd"}'
The linked code produces the same output using the same plaintext, key, and test-IV.

mocking boto3 client for exceptions

I have successfully mocked boto3 client to test the positive case but unable to mock the same client for exceptions here is the code that i tried to mock the get_secret_value method of boto3 client to raise a ClientError.
class SecretsManager:
def __init__(self):
self.session = boto3.session.Session()
self.client = self.session.client(service_name='secretsmanager', region_name='region-name')
self.get_secrets()
def get_secrets(self): # no-pragma
try:
get_secret_value_response = self.client.get_secret_value(
SecretId=self.secret_name)
except ClientError as e:
if e.response['Error']['Code'] == 'DecryptionFailureException':
raise e
else:
if 'SecretString' in get_secret_value_response:
secret = get_secret_value_response['SecretString']
self.secrets_dict = json.loads(secret)
else:
decoded_binary_secret = base64.b64decode(
get_secret_value_response['SecretBinary'])
Tests:
class TestSecretsManager:
#mock.patch("boto3.session.Session")
def test_get_secrets(self, mock_session):
# Arrange
mock_session_object = mock.Mock()
mock_client = mock.Mock()
mock_client.get_secret_value.return_value = {"SecretString": '{"my-secret1": "val1"}'}
mock_session_object.client.return_value = mock_client
mock_session.return_value = mock_session_object
secrets = SecretsManager()
assert secrets is not None
assert len(secrets.secrets_dict) == 1
assert secrets.secrets_dict['my-secret1'] == 'val1'
#mock.patch("boto3.session.Session")
def test_get_secrets_exception(self, mock_session):
# Arrange
mock_session.client.get_secret_value.side_effect = ClientError(error_response={"Error": {"Code": "DecryptionFailureException"}}, operation_name='Test')
with pytest.raises(Exception) as err:
secrets = SecretsManager()
assert err['Error']['Code'] == 'DecryptionFailureException'
test 1 is passing but, test 2 is not raising ClientError. Can somebody help me where am going wrong?

Receiving a continuation character Syntax Error

Does anyone know why am I receiving this syntax error?
def softmax(self,x):
return 1/(1+np.exp(-x))
def encrypt(self,pubkey,scaling_factor=1000):
if(not self.encrypted):
self.pubkey = pubkey
self.scaling_factor = float(scaling_factor)
self.encrypted_weights = list()
for weight in model.weights:
self.encrypted_weights.append(self.pubkey.encrypt(\\
int(min(weight,self.maxweight) * self.scaling_factor)))
self.encrypted = True
self.weights = None
return self
File "<ipython-input-33-9ca6863eb9a3>", line 11
self.encrypted_weights.append(self.pubkey.encrypt(\\
^
SyntaxError: unexpected character after line continuation character
Well, I think you forgot to put the keyword self before model.weight, and import np from numpy. Try this:
import np
def softmax(self,x):
return 1/(1+np.exp(-x))
def encrypt(self,pubkey,scaling_factor=1000):
if(not self.encrypted):
self.pubkey = pubkey
self.scaling_factor = float(scaling_factor)
self.encrypted_weights = list()
for weight in self.model.weights:
self.encrypted_weights.append(self.pubkey.encrypt(int(min(weight, self.maxweight) * self.scaling_factor)))
self.encrypted = True
self.weights = None
return self

error while importing images to odoo 11 using python script

I am trying to import images to odoo 11 using a python script. Earlier I used to work on a laptop with windows 7 installed and this script was working fine. But now, I have upgraded my laptop to windows 10 and I tried to run this same script but I am facing few errors.
Here is my script,
import csv
from pprint import pprint
import xmlrpc.client as xmlrpclib
class OpenERPXMLRPC():
#def __init__(self, host="0.0.0.0", port="8088", db="demo",
# user="admin",
# password="admin"):
def __init__(self, host="205.147.98.219", port="", db="BUILDSTATION_ROMFORD",
user="tina.santhosh#gmail.com",
password="buildstation1234*"):
common_url = "http://%s:%s/xmlrpc/common" % (host, port)
object_url = "http://%s:%s/xmlrpc/object" % (host, port)
com_sock = xmlrpclib.ServerProxy(common_url)
uid = com_sock.login(db, user, password)
if uid:
self.uid = uid
self.password = password
self.db = db
else:
print("Error in Authentication")
self.sock = xmlrpclib.ServerProxy(object_url)
def execute(self, model, method, *args):
res = self.sock.execute(self.db, self.uid, self.password, model,
method, *args)
return res
oe = OpenERPXMLRPC(db="BUILDSTATION_ROMFORD")
application = csv.reader(open('C:\\Users\\Asus\\Desktop\\test1.csv'))
for rec in application:
fields = rec
break
all_datas = []
count = 1
for rec in application:
all_datas.append(rec)
count = 0
all_error = []
for rec in all_datas:
count += 1
print(rec)
product_id = oe.execute(
'product.template',
'search',
[('name','=', rec[0])])
print("product_name--", product_id)
with open(rec[1], 'rb') as image:
image_base64 = image.read().encode("base64")
vals = {
'name': rec[0],
'image_medium': image_base64
}
oe.execute(
'product.template',
'write',
product_id,
vals)
I have created a separate file called test1.csv where I have uploaded only the product name and image location.
Here is the error that I am getting,
C:\Users\Asus>python c:\users\asus\desktop\final_import.py
['Airbrick Black', 'E:\\compressed images for odoo\\building materials\\airblocks\\ti0014.jpg']
product_name-- [4071]
Traceback (most recent call last):
File "c:\users\asus\desktop\final_import.py", line 55, in <module>
image_base64 = image.read().encode("base64")
AttributeError: 'bytes' object has no attribute 'encode'
any help here would be much appreciated.
Thanks,
Tina

ValueError: Ciphertext with incorrect length using Python

Can some please help me I tried googling this error but could not understand why it is being raised. Can you point out the problem in my code I am fairly new to encryption this is my first time trying to use it.
session_key = cipher_rsa.decrypt(enc_session_key)
, ValueError("Ciphertext with incorrect length."),
ValueError: Ciphertext with incorrect length.
Encryption code
from Crypto.PublicKey import RSA
from Crypto import Random
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.Random import get_random_bytes
random_generator = Random.new().read
print (random_generator,"HI")
key = RSA.generate(1024, random_generator)
print(key)
code = 'totalyundetectable' #******************important ****************
encrypted_key = key.exportKey(format='PEM', passphrase=code, pkcs=8,
protection="scryptAndAES128-CBC")
with open('C:/Users/Arnav/Documents/Project/my_private_key.bin', 'wb') as f:
f.write(encrypted_key)
with open('C:/Users/Arnav/Documents/Project/my_rsa_public.pem', 'wb') as f:
f.write(key.publickey().exportKey())
with open('C:/Users/Arnav/Documents/Project/encrypted_data.bin', 'wb') as out_file:
recipient_key = RSA.import_key(
open('C:/Users/Arnav/Documents/Project/my_rsa_public.pem').read())
session_key = get_random_bytes(16)
cipher_rsa = PKCS1_OAEP.new(recipient_key)
out_file.write(cipher_rsa.encrypt(session_key))
cipher_aes = AES.new(session_key, AES.MODE_EAX)
data = b'blah blah bl'
ciphertext, tag = cipher_aes.encrypt_and_digest(data)
out_file.write(cipher_aes.nonce)
out_file.write(tag)
out_file.write(ciphertext)
code = 'totalyundetectable'
Decryption code
with open('C:/Users/Arnav/Documents/Project/encrypted_data.bin', 'rb') as fobj:
private_key = RSA.import_key(
open('C:/Users/Arnav/Documents/Project/my_private_key.bin','rb').read(),
passphrase=code)
enc_session_key, nonce, tag, ciphertext = [fobj.read(x)
for x in (private_key.size_in_bytes(),
16, 16, -1)]
cipher_rsa = PKCS1_OAEP.new(private_key)
session_key = cipher_rsa.decrypt(enc_session_key)
cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
data = cipher_aes.decrypt_and_verify(ciphertext, tag)
print(data)
In your case it looks like wrong white spaces/tabs. Because if I write like:
from Crypto.PublicKey import RSA
from Crypto import Random
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.Random import get_random_bytes
random_generator = Random.new().read
print (random_generator,"HI")
key = RSA.generate(1024, random_generator)
print(key)
code = 'totalyundetectable' #******************important ****************
encrypted_key = key.exportKey(format='PEM', passphrase=code, pkcs=8,
protection="scryptAndAES128-CBC")
with open('my_private_key.bin', 'wb') as f:
f.write(encrypted_key)
with open('my_rsa_public.pem', 'wb') as f:
f.write(key.publickey().exportKey())
with open('encrypted_data.bin', 'wb') as out_file:
recipient_key = RSA.import_key(
open('my_rsa_public.pem').read())
session_key = get_random_bytes(16)
cipher_rsa = PKCS1_OAEP.new(recipient_key)
out_file.write(cipher_rsa.encrypt(session_key))
cipher_aes = AES.new(session_key, AES.MODE_EAX)
data = b'blah blah bl'
ciphertext, tag = cipher_aes.encrypt_and_digest(data)
out_file.write(cipher_aes.nonce)
out_file.write(tag)
out_file.write(ciphertext)
code = 'totalyundetectable'
with open('encrypted_data.bin', 'rb') as fobj:
private_key = RSA.import_key(
open('my_private_key.bin','rb').read(),
passphrase=code)
enc_session_key, nonce, tag, ciphertext = [fobj.read(x)
for x in (private_key.size_in_bytes(),
16, 16, -1)]
cipher_rsa = PKCS1_OAEP.new(private_key)
session_key = cipher_rsa.decrypt(enc_session_key)
cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
data = cipher_aes.decrypt_and_verify(ciphertext, tag)
print(data)
I'm getting as result:
<bound method _UrandomRNG.read of <Crypto.Random._UrandomRNG object at 0x000001696F4B8700>> HI
Private RSA key at 0x1696FB5CE20
b'blah blah bl'
Also, be careful, if you're using the construction in code without with statement, you need to close file at the end.
E.g. in this case will be the error ValueError: Ciphertext with incorrect length:
#...
out_file = open("encrypted_data.bin", "wb")
recipient_key = RSA.import_key(
open('my_rsa_public.pem').read())
session_key = get_random_bytes(16)
cipher_rsa = PKCS1_OAEP.new(recipient_key)
out_file.write(cipher_rsa.encrypt(session_key))
cipher_aes = AES.new(session_key, AES.MODE_EAX)
data = b'blah blah bl'
ciphertext, tag = cipher_aes.encrypt_and_digest(data)
out_file.write(cipher_aes.nonce)
out_file.write(tag)
out_file.write(ciphertext)
#...
To solve it you need to write like:
#...
out_file = open("encrypted_data.bin", "wb")
recipient_key = RSA.import_key(
open('my_rsa_public.pem').read())
session_key = get_random_bytes(16)
cipher_rsa = PKCS1_OAEP.new(recipient_key)
out_file.write(cipher_rsa.encrypt(session_key))
cipher_aes = AES.new(session_key, AES.MODE_EAX)
data = b'blah blah bl'
ciphertext, tag = cipher_aes.encrypt_and_digest(data)
out_file.write(cipher_aes.nonce)
out_file.write(tag)
out_file.write(ciphertext)
out_file.close() # important to add at the end
#...
Alternatively, you can do:
#...
with open('encrypted_data.bin', 'wb') as out_file:
recipient_key = RSA.import_key(
open('my_rsa_public.pem').read())
session_key = get_random_bytes(16)
cipher_rsa = PKCS1_OAEP.new(recipient_key)
out_file.write(cipher_rsa.encrypt(session_key))
cipher_aes = AES.new(session_key, AES.MODE_EAX)
data = b'blah blah bl'
ciphertext, tag = cipher_aes.encrypt_and_digest(data)
out_file.write(cipher_aes.nonce)
out_file.write(tag)
out_file.write(ciphertext)
#...

Resources