Understanding an AttributeError in python and how to solve it - python

I am getting the error :
data = cipher.encrypt(data)
File "/usr/lib/python2.7/dist-packages/Crypto/Cipher/PKCS1_OAEP.py", line 133, in encrypt
randFunc = self._key._randfunc
AttributeError: 'str' object has no attribute '_randfunc'
in my console for the following section of code:
cipher = PKCS1_OAEP.new(PK_ID)
data = cipher.encrypt(data)
both the PK_ID and data are both of Str
what does the error message mean and how can i solve it for this code?

The PKCS1_OAEP.new() function takes an RSA key object, which you can get from the Crypto.PublicKey.RSA module, it doesn't take a str.

Related

How to parse headers as a string from raw text in email via imap?

I'm trying to parse the Subject line, To, From and the body text as a string via imaplib and email module. I'm getting an error message saying AttributeError: 'tuple' object has no attribute 'decode' when I try to parse the raw message. Please assist.
import imaplib
import email
Mymail = imaplib.IMAP4_SSL('imap.gmail.com')
password = input()
abcxyz123
Mymail.login('xxx#gmail.com', password)
('OK', [b'xxx#gmail.com authenticated (Success)'])
Mymail.select('INBOX', readonly = True)
('OK', [b'1'])
UIDs = Mymail.search(None, '(SINCE "20-Aug-2019")')
UIDs
('OK', [b'1'])
rawMessage = Mymail.fetch('1', '(BODY[] FLAGS)')
rawHeader = Mymail.fetch('1', "(BODY[HEADER.FIELDS (FROM)])")
rawHeader2 = Mymail.fetch('1', "(BODY[HEADER.FIELDS (TO)])")
rawHeader3 = Mymail.fetch('1', "(BODY[HEADER.FIELDS (SUBJECT)])")
rawHeader4 = Mymail.fetch('1', "(BODY[TEXT])")
**msg = email.message_from_bytes(rawMessage)**
I get the following error message when I try to parse the raw message:
*Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
msg = email.message_from_bytes(rawMessage)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/email/__init__.py", line 46, in message_from_bytes
return BytesParser(*args, **kws).parsebytes(s)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/email/parser.py", line 122, in parsebytes
text = text.decode('ASCII', errors='surrogateescape')
AttributeError: 'tuple' object has no attribute 'decode'*
Answer:
You are attempting to parse a tuple object to a method which attempts to decode bytes.
More Information:
imaplib.IMAP4_SSL().fetch() returns a tuple and email.message_from_bytes() expects a bytes-like object.
You have mismatching data types. Tuples are not bytes-like objects that have a method to decode them. You will need to handle this accordingly before calling email.message_from_bytes() or use another method such as message_from_string().
Remember that if you do this, though, tuple != string and you will still need to make a data type conversion.
References:
IMAP4.fetch() - imaplib - IMAP4 protocol
Python tuples - w3schools
bytes-like object - Gloassary Python 3.8.6

Python protobuf decode base64 string

I am trying to get JSON data from encrypted base64 string. I have created my proto file like below
syntax = "proto2";
message ArtifactList {
repeated Artifact artifacts = 1;
}
message Artifact {
required string id = 1;
required uint64 type_id = 2;
required string uri = 3;
}
After that, I have generated python files using the proto command. I am trying to decrypt the base64 string like below.
import message_pb2
import base64
data = base64.b64decode("AAAAAA8KDQgTEBUgBCjln62lxS6AAAAAD2dycGMtc3RhdHVzOjANCg==")
s = str(data)
message_pb2.ArtifactList.ParseFromString(s)
But I am getting the below error.
Traceback (most recent call last):
File "app.py", line 7, in <module>
message_pb2.ArtifactList.ParseFromString(s)
TypeError: descriptor 'ParseFromString' requires a 'google.protobuf.pyext._message.CMessage' object but received a 'str'
I am a newbie for protobuf. I couldn't find a solution to fix this issue.
Could anyone help to fix this problem?
Thanks in advance.
There are two issues.
ParseFromString is a method of an ArtifactList instance
ParseFromString takes a byte-like object, not str, as parameter
>>>import message_pb2
>>>import base64
>>>data = base64.b64decode("AAAAAA8KDQgTEBUgBCjln62lxS6AAAAAD2dycGMtc3RhdHVzOjANCg==")
>>>m=message_pb2.ArtifactList()
>>>m.ParseFromString(data)
>>>m.artifacts
<google.protobuf.pyext._message.RepeatedCompositeContainer object at 0x7fd09a937d68>
ParseFromString is a method on an protobuf Message instance.
Try:
message = message_pb2.ArtifactList()
message.ParseFromString(s)

Botometer keeps returning TypeError

I have used this function before and it worked perfectly. However, I may have accidentally changed something and it now returns the error:
TypeError: 'module' object is not callable
For the line:
bom = botometer.botometer(wait_on_ratelimit=True,rapidapi_key=rapidapi_key,**twitter_app_auth)
The full code I use is:
def bot_detector(account,lang='universal'):
consumer_secret = deleter(open('consumer_sxcrxt.txt','r').rxad(),'\n')
consumer_key = deleter(open('api.txt','r').read(),'\n')
twitter_app_auth = {'consumer_key': consumer_key,'consumer_secret': consumer_secret}
rapidapi_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxx'
bom = botometer.botometer(wait_on_ratelimit=True,rapidapi_key=rapidapi_key,**twitter_app_auth)
result = bom.check_account(account)
score = result['cap'][lang]
return score
print(bot_detector(1.25948029617448E+018))
Notes:
'deleter' is just a way for me to remove the line separator on the files containing my api keys.
I just checked and my twitter api keys are working.
If I put botometer.Botometer as it says on the documentation, I get the error:
AttributeError: module 'botometer' has no attribute 'Botometer'
(I think they made a typo on the documentation.)
Documentation:
https://libraries.io/pypi/botometer
I named my file 'botometer.py' and thus python was looking in the wrong place.

AttributeError: 'bytes' object has no attribute '__dict__'

I totally new in Python and stuck with this error:
I am trying to encode an image and then convert it to json to upload into a no-sql db. But when I am trying to convert it to json I am getting this error:
"AttributeError: 'bytes' object has no attribute 'dict'"
Below is my python code:
import base64
import json
def jsonDefault(object):
return object.__dict__
with open("img123.png", "rb") as imageFile:
str = base64.b64encode(imageFile.read())
print(str)
json_str = {'file_name':'img123','img_str':str}
pytojson = json.dumps(json_str, default=jsonDefault)
print(pytojson)
That happens because you are trying to access a property that a bytes object doesn't have (__dict__). I understand that you need to return a format that can be serialized to JSON.
This works for me, but I don't know if it's the decoding you desire:
def jsonDefault(o):
return o.decode('utf-8')
See TypeError: b'1' is not JSON serializable as well.

Getting error 'Endpoint' object has no attribute ctrl_transfer when trying to get string descriptor using pyusb

I am attempting to get the string descriptor of the Endpoint attribute bmAttributes. I am able to get the value using pyusb but not the string descriptor for it. When i do i get that error.
dev = usb.core.find(idVendor = 0x0126)
dev.set_configuration()
cfg = dev.get_active_configuration()
intf = cfg[(0,0)]
ep = intf[0]
bmattrib = usb.util.get_string(ep, ep.bmAttributes) <--Where error is
I can get the value but not the string. Anyone know how to get this to work?

Categories