I want to hash some 4 digit numbers
but it gives me (object supporting the buffer API required) error
here's my code
import hashlib
import itertools as it
number=[0,1,2,3,4,5,6,7,8,9]
code = hashlib.sha256()
passwords = list(it.permutations(number, 4))
#hpass is hash password
for hpass in passwords :
code.update(passwords)
print(hpass)
and the output is
Traceback (most recent call last):
File "c:\Users\Parsa\Desktop\project\Untitled-2.py", line 11, in <module>
code.update(passwords)
TypeError: object supporting the buffer API required
the update function of hashlib.sha256 instance require the bytes-like object
Update the hash object with the bytes-like object.
https://docs.python.org/3/library/hashlib.html
and also it seems input passwords list at update
It is hard to know the intention of your code.
but I guess you wanna get a set of hashes by 4 digit numbers
if it is right try this.
import hashlib
import itertools as it
number=[0,1,2,3,4,5,6,7,8,9]
passwords = list(it.permutations(number, 4))
# hpass is hash password
for hpass in passwords :
encoded_hpass = ''.join(map(str, hpass)).encode('ascii')
code = hashlib.sha256()
code.update(encoded_hpass)
print(encoded_hpass)
print(code.digest())
Output
b'0123'
b'\x1b\xe2\xe4R\xb4mz\r\x96V\xbb\xb1\xf7h\xe8$\x8e\xba\x1bu\xba\xede\xf5\xd9\x9e\xaf\xa9H\x89\x9aj'
b'0124'
b'\x91\xb1\xe2#\xed\x10?)\x1c\x16v\\\xb2\x01\xa9\xe4\xf2\xc2?\xf4\x05pP\xb9\xfdxW\x1f7:\xce='
b'0125'
b'\x17\x9f\x91-Q]\xdb\x97\xa0\x8f\xee\xb4\xe3v\x99aH\xda;\xb7\xcb]\x97K\x81<\x8a\xfb\xdcaf+'
b'0126'
b'\x9d\xa4\x84d|\xdd\xd7\x98]\x9e\xf5\x06\xf9\xbd\x15\x80\xf5\xa8\xdc\x06R8\xdbp\x1b\xc5~\x08\xa3<\\\xa9'
b'0127'
b'h|\xdf<\xae\xaa\x88\x8b\x00\x0e\xdfJ\x01\xd1(\xe3\xb3 &\xb0O\xe2H\xaa0\xab/\xab\xa6\xd3#3'
b'0128'
b'\xee\xb9\xff>\xa6X,\xe2\xbf\x03\xb9\xbb\xff\x95\x88"\x90\xb8\xa8\xe5(\xa3\x91\xbc5i\x17\x92\x8fr\x1c\x06'
b'0129'
b'-\x90|u\xaa\xb2$\x85\x0bkv\xd1^/\xd4q$\x8e\xdfq]\xe8\xf7\x9d\xc8L-A\x1ff?\x88'
b'0132'
b"\xa7H\x02\x8b\x05\x18\xda\x98\xd8\xd2F\xe6\x1a8\x96\xa6w\x05\x97^'\xc3\xa0B\xb1E\r\xa9\\\xe3\x9bU"
b'0134'
....
Related
I have the following code running on AWS lambda, but getting the following error.
Error
[ERROR] AttributeError: 'str' object has no attribute 'source_instructions'
Traceback (most recent call last):
File "/var/task/gremlin_python/driver/driver_remote_connection.py", line 56, in submit
result_set = self._client.submit(bytecode, request_options=self._extract_request_options(bytecode))
File "/var/task/gremlin_python/driver/driver_remote_connection.py", line 81, in _extract_request_options
options_strategy = next((x for x in bytecode.source_instructionsEND RequestId: 4ee8073c-e941-43b3-8014-8717893b3188
Source code
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
def test_neptune(host):
remoteConn = DriverRemoteConnection('wss://{}:8182/gremlin','g'.format(host))
query = "g.V().groupCount().by(label).unfold().project('label','count').by(keys).by(values)"
response = remoteConn.submit(query)
print("response-> {}" .format(response))
# iterate repsonse
# go thru label
for set_item in response:
for item in set_item:
print("item-> item: {}".format(item))
remoteConn.close()
test_neptune()
Your DriverRemoteConnection call is wrong. You have:
remoteConn = DriverRemoteConnection('wss://{}:8182/gremlin','g'.format(host))
So you are sending {} as the hostname, and passing 'g' as a second parameter, which is probably where the error comes from. I don't know what you intended the 'g' for, but you probably want:
remoteConn = DriverRemoteConnection('wss://{}:8182/gremlin'.format(host))
If you send the query as a text string you need to create the Client object differently or write the query as in-line Python. There are two examples at (1) and (2) that show each option. The error you are seeing is because the server is trying to find Gremlin bytecode in the packet sent but only found a string (which does not have a source_instructions method).
Using a DriverRemoteConnection you can use a Python line of code such as:
result = (g.V().groupCount().
by(label).
unfold().
project('label','count').
by(keys).
by(values).
next())
If you actually want/need to send the query as a string instead of bytecode, please see my answer to this question
https://github.com/krlawrence/graph/blob/master/sample-code/basic-client.py
https://github.com/krlawrence/graph/blob/master/sample-code/glv-client.py
I am trying to get the list of local user my windows have.
I figured it out i can get the list in a form of a dictionary using win32net.NetUserEnum, however, since i just need the username, i'm trying to fetch that information from the dict and i've managed to do it already.
But i still have a problem, the script it's returning this message:
Administrator Traceback (most recent call last): Guest File
"D:/QUIZ/OCRLAB/orissupportaut.py", line 9, in DefaultAccount
for user in listausers[i]: userjohn TypeError: 'int' object is not iterable teste UtilityAccount
Anyway knows why this is happening?
Thanks
import win32api
import win32net
import win32netcon
listausers = win32net.NetUserEnum(None,2)
utilizadores= []
for i in range(len(listausers)):
for user in listausers[i]:
if type(user) == int:
pass
else:
print(user.get("name"))
Does this meet your requirements? Using isinstance instead of checking value of type. You're getting this error because NetUserEnum returns a list consisting of the users dict, and a few extra values (ints) as described here.
import win32api
import win32net
import win32netcon
listausers = win32net.NetUserEnum(None,2)
utilizadores= []
for i, users in enumerate(listausers):
if not isinstance(users, int):
for user in users:
if isinstance(user, int):
pass
else:
print(user.get("name"))
You could also just look at the dictionary itself by slicing the list.
for user in listausers[0]:
print(user.get("name"))
Building on CDJB's answer, I would compact everything to simply:
import win32api
import win32net
import win32netcon
listausers = win32net.NetUserEnum(None, 2)[0] # 0 to ignore the extra returned values.
utilizadores = [user.get("name") for user in listausers]
I have the following JSON object which represents an RSA256 JWK which obtained from a website:
jwk = {
'e': 'AQAB',
'n': 'sAlE_mzYz-2jf_YpxulSJXv_2CGIquflNZWhXUaU1SkJm9P0riLAuzwK7WT5p0Ko3zmQHho70_7D9nqB01rA4ExrMIDKpprE0Qa7NAJN-kgZhd_A25HsdSfpOfpaLvR-mf9fuOTDPLRQCd5HnrjoQKjs3D_XfPmPnT_Ny5erviiky90GSfN9j2DP_5yeDprzWKF-EQ3EDdIWt3snr7AW8rzBcZ1ojyWxckLAeSKDerMXP-zVBUFJE9Kn60HZoGNvmATKaw8LwEbf8DGfrllgSLvhg7mDRMLlbcooQoWAFSfN7t7kFbPSOcvjrpx3Yw_KrEwBZXeUP3260ukmFOx8RQ',
}
Below is the Perl code showing how a public-key object from the Crypt library can be constructed from the above jwk:
use Crypt::OpenSSL::RSA;
use Crypt::OpenSSL::Bignum;
use MIME::Base64 qw/decode_base64url/;
sub public_key {
my $rsa = Crypt::OpenSSL::RSA->new_key_from_parameters(
Crypt::OpenSSL::Bignum->new_from_bin(decode_base64url($jwk->{n})),
Crypt::OpenSSL::Bignum->new_from_bin(decode_base64url($jwk->{e})),
);
return $rsa->get_public_key_x509_string;
}
Two Questions:
How can I translate the above code into Python? The code below failed.
Once I have the public key object in python, how can I use it to verify a JWT signed by the corresponding private key? Please post a snippet showing exactly how it can be done.
>>> from Crypto.PublicKey import RSA
>>> import base64
>>> public_key = RSA.construct((base64.b64decode(jwk['n']), base64.b64decode(jwk['e'])))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "my-virtual-env/lib/python2.7/site-packages/Crypto/PublicKey/RSA.py", line 539, in construct
key = self._math.rsa_construct(*tup)
File "my-virtual-env/lib/python2.7/site-packages/Crypto/PublicKey/_slowmath.py", line 84, in rsa_construct
assert isinstance(n, long)
AssertionError
The error is raised because the RSA contructor is expecting 2 long integers and you are using two strings.
The solution is to convert the base64 decoded string into an hexadecimal integer.
from Crypto.PublicKey import RSA
import base64
n = int(base64.b64decode(jwk['n']).encode('hex'),16)
e = int(base64.b64decode(jwk['e']).encode('hex'),16)
e = long(e)
public_key = RSA.construct((n, e))
print(public_key)
Regarding the second question maybe you can use this method to verify the validity of an RSA signature.
I want to store the Public and Private keys in pgsql database and then when required want to retrieve them back.
I tried converting it ,storing and retrieving it from database but this results in error:
TypeError: Odd-length string
python testenc.py "TEST"
"5b69ecf0fb808693e6fdf6514fd8f1eca20b96e407ec78681269b24463d2cc0"
"3d4b091ff086660c8adfd3318d43563a2befb85619bb4422161a4e9ae0837131"
Input Message is : TEST
Traceback (most recent call last):
File "testenc.py", line 31, in <module>
skbob = pickle.loads(binascii.unhexlify(sys.argv[2]))
TypeError: Odd-length string
This can be done as follows:
1) use library pickle for this.
2) Use a socket communication and after receiving data on socket use pickle.load(received string) to maintain the key intact.
3) While sending data on socket "use pickle.dump(string)" so that data/Key remains intact.
I am trying to create a hashing function with user interaction.
The idea is that the user chooses which hash he/she wants (i.e. md5, sha1 and so forth) and the program does the rest.
My code:
hashstring = "hashlib" + finalHash
filePath = open(chosenFile, 'rb')
data = filePath.read(8192)
if not data:
return
hashstring.update(data) # The line that causes error
return hashstring.hexdigest()
finalHash is from a dictionary containing (lets say md5 is chosen) '.md5()' so the string from hashstring is 'hashlib.md5().
I get the error: AttributeError: 'str' object has no attribute 'update', the error points me to the obvious: hashstring is a string (as i declared it), my question goes: How do i convert or in other way make it useable as it is intended?
You could use getattr:
import hashlib
chosenFile = '/etc/passwd'
finalHash = input('Which hash function?') # raw_input in Python 2
assert finalHash in ['md5', 'sha1'] # Optional
h = getattr(hashlib, finalHash)
h.update(open(chosenFile, 'rb').read())
print(h.hexdigest())
Note that the input must not contain dots or parentheses. If you want to allow the user to input md5() or so, you'll have to strip the parentheses first.