Generate HmacSHA256 based on groovy code into Python [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I was given some code in groovy and asked to convert it to Python.
def generateHmac(String data){
String secretKey = '123445667777'
byte[] digest
Mac mac = Mac.getInstance("HmacSHA256")
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256")
mac.init(secretKeySpec)
digest = mac.doFinal(data.getBytes())
//we use hex encoding for our tokens.
String token = digest.encodeHex().toString()
return token
}
I have tried many times but failed:
def generateHmac(String data):
data = "my_url"
secret_key = b"123445667777"
h = SHA256.new()
h.update(secret_key)
h.update(b"data")
print(h.hexdigest())

An hmac is not the same thing as a digest. HmacSHA26 uses SHA256, it isn't the same thing as SHA256. You need to use the hmac library to get the correct result.
hmac.digest(secretKey, message, "Sha256")
should give you what you want, with the secretKey and message being bytes.
The above is equivalent to the longer form:
hmac.new(secretKey, message, "Sha256").digest()
but once you have the hmac object, you can other things like update() with more text or hexdigest() to get a text-like digest.

Related

Syntax to use combination of two hash algorithm [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 months ago.
Improve this question
I would like to know how to write in a single line the combination of two hash algorithms in Python. I want to use MD5 and sha256 in one line. Here is my function:
def calcHash(self):
block_string = json.dumps({"nonce":self.nonce, "tstamp":self.tstamp, "output":self.output, "prevhash":self.prevhash}, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
I tried return md5.hashlib(hashlib.sha256(block_string).hexdigest()) but it doesn't work.
Can someone help?
The problem could just be that .hexdigest() produces a string, not a bytes, so you need to encode it again
>>> import hashlib, json
>>> j = json.dumps({"foo":"bar","baz":2022})
>>> hashlib.sha256(j.encode()).hexdigest()
'44ce0f46288befab7f32e9acd68d36b2a9997e801fb129422ddc35610323c627'
>>> hashlib.md5(hashlib.sha256(j.encode()).hexdigest().encode()).hexdigest()
'f7c6be48b7d34bcd278257dd73038f67'
Alternatively, you could directly use .digest() to get bytes from the hash, rather than intermediately converting it to a hex string (though note the output is different)
>>> hashlib.md5(hashlib.sha256(j.encode()).digest()).hexdigest()
'12ac82f5a1c0cb3751619f6d0ae0c2ee'
If you have a great many algorithms in some order, you may find .new() useful to iteratively produce a result from some list of hashes.
BEWARE
md5 is broken from a security perspective and I cannot recommend using it unless it's a required input to a legacy system!

Encrypt string with the python standard libraries [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Some Info:
While this question is repeated multiple times on StackOverflow and, when googled, brings up many answers; neither of these were fully the answer I was looking for. I have seen answers which use libraries like PyCrypto etc. but none of that helped.
The question:
I am looking for a simple way to encrypt a string in python3 using only the default libraries. I was thinking of, for example, making python replace all the letters in the string with a number or a different letter. Below is what I was thinking of, except it's not actual python code. If someone could make it work in python (and possibly shrink it a little) I would be very grateful.
The Code (Not really):
def encrypt():
for letter in string:
if letter = 'a':
letter.change_to('123')
if letter = 'b':
letter.change_to('133')
if letter = 'c':
letter.change_to('124')
if letter = 'd':
letter.change_to('143')
# And so on... #
NOTE: I would also appreciate if you included a way to decrypt the string if you use a different method to the one above because I am still learning and might not understand how your method works.
-Thank you all in advance :)
EDIT: I was asked to write why I don't want to use any external libraries. It is because I want to encrypt data I send from a client program to a server program. The client will likely run on multiple machines and I do not want to install the required libraries (or make my users do it) on all the machines.
Ok, here's a version of what you want using the chr() and ord() functions, which are related to a topic called ASCII. (A good thing to learn about)
def encrypt(originalString):
encryptedString = ""
for letter in originalString:
encryptedString += str(ord(letter))+"*"
return encryptedString[:-1]
def decrypt(encryptedString):
decryptedString = ""
for codeNumber in encryptedString.split("*"):
decryptedString += chr(int(codeNumber))
return decryptedString
s = "The crow flies at midnight"
t = encrypt(s)
u = decrypt(t)
print(s)
print(t)
print(u)
Output:
The crow flies at midnight
84*104*101*32*99*114*111*119*32*102*108*105*101*115*32*97*116*32*109*105*100*110*105*103*104*116
The crow flies at midnight

Calculate checksum bitcoin on lost bitcoin private key [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
This is my story:
Several years ago I splitted my bitcoin private key to keep it safe in different places. I lost one part and think I lost my mined bitcoin forever.
Suddenly (I think you understand why) I decided to start searching for any parts and I found 3 of 6!!!!
So for now I have the start(Lets say "5Lagt") and the end("Bh3u2YHU2ntQAFTruAYGhJ1xacPJXr3l6k") so I need to find just 10 alfanumeric chars between.
I am pretty new to programming, but have some basics in Python and C from university.
I have read that the last symbols in WIF compressed private key is a checksum.
So as I understand in pseudo code I need to do following stuff
Decode the private key to hex format (this 08+..........+checksum)
exclude 08 and the checksum
generate the lost part (encode or decode it somehow??)
compare the first bytes (what bytes?) with the checksum
I partly understand it theoretically but not practically.
I would love to give 10% of bitcoins on the wallet if I get it back!
Take that quick sketch of checksum checking, hope it'll guide you in a right direction:
import base58
import hashlib
def check_wif(wif):
"""WIF checksum checking.
Install base58 before use: `pip install base58`
>>> check_wif('5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbTLvyTJ')
True
"""
try:
wif_bytes = base58.b58decode(wif)
if wif_bytes[0] != 128:
return False
wif_bytes_no_chksum, chksum = wif_bytes[:-4], wif_bytes[-4:]
wif_bytes_sha256_1 = hashlib.sha256(wif_bytes_no_chksum)
wif_bytes_sha256_2 = hashlib.sha256(wif_bytes_sha256_1.digest())
if wif_bytes_sha256_2.digest()[:4] == chksum:
return True
else:
return False
except ValueError:
return False
In general python is too slow for that kind of task as I can tell.

Code to accept 32byte hex password [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm doing some experiment with the following code:
import hashlib
password = 16
n = 2 #counter
hash = hashlib.sha256(str(password) + str(n)).hexdigest() #will read the password as string and hash
print hash
What should be the proper code so it can accept a 32byte hex like 000000...0002?
A hex in Python is just a fancy way of writing an integer. So simply set password to your hex value:
password = 0x00000000000000000000000000000002

Converting Hex To dec in python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to convert this RFID Tag number got from this code;
import serial
ser = serial.Serial()
ser.port = "COM1"
ser.baudrate = 9600
ser.timeout = 3
ser.open()
if ser.open is True:
print "Port Not open"
while ser.isOpen():
#ser.timeout = 7
response = ser.read(17)
response = response.encode('hex')
print response
I am getting this 0000000000000000000213780510015dff which is a hexadecimal number, but I want to convert it to decimal or string. When I try to do that, I am getting a token error. How can I fix that?
You say you want to "convert… to string".
You can use unhexlify to do that, or decode('hex').
However, in your case, the only reason you have hex in the first place is that you called encode('hex'), so just… don't do that.
If you want to decode it to an int or a Decimal or something, you can do that by using the appropriate constructor, as Maxime's answer shows. However, rather than converting to hex just to decode as an int, you might want to just decode it directly. Or maybe you want to decode the hex string into a decimal string? Or maybe this is some UUID-style structure, and you want to use struct.unpack to decode it into pieces? Or…? Without knowing exactly what you're trying to do, it's hard to give an exact answer…
You can use int to convert a hexadecimal number into an integer.
>>> int("0000000000000000000213780510015dff", 16)
149595175772052991

Categories