Calculate checksum bitcoin on lost bitcoin private key [closed] - python

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.

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!

Efficient way to generate all possibilities of string from characters [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
I am trying to randomly generate a string of n length from 5 characters ('ATGC '). I am currently using itertools.product, but it is incredibly slow. I switched to itertools.combinations_with_replacement, but it skips some values. Is there a faster way of doing this? For my application order does matter.
for error in itertools.product('ATGC ', repeat=len(errorPos)):
print(error)
for ps in error:
for pos in errorPos:
if ps == " ":
fseqL[pos] = ""
else:
fseqL[pos] = ps
If you just want a random single sequence:
import random
def generate_DNA(N):
possible_bases ='ACGT'
return ''.join(random.choice(possible_bases) for i in range(N))
one_hundred_bp_sequence = generate_DNA(100)
That was posted before post clarified spaces need; you can change possible_sequences to include a space if you need spaces allowed.
If you want all combinations that allow a space, too, a solution adapted from this answer, which I learned of from Biostars post 'all possible sequences from consensus':
from itertools import product
def all_possibilities_w_space(seq):
"""return list of all possible sequences given a completely ambiguous DNA input. Allow spaces"""
d = {"N":"ACGT "}
return list(map("".join, product(*map(d.get, seq))))
all_possibilities_w_space("N"*2) # example of length two
The idea being N can be any of "ACGT " and the multiple specifies the length. The map should specify C is used to make it faster according to the answer I adapted it from.

Need Help to program in python. Desperate Python newbie here :-} [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
The community is reviewing whether to reopen this question as of 11 months ago.
Improve this question
Hy,I am newbie in python programming.I am trying to improve my programming skills.I recently joined a code learning platform called code wars for improving my coding skills. The platform is great. I am having trouble reading some code there as I am not a experienced programmer.
Write a function that adds the digits of an integer. For example, the input receives a number: 10023. The result should be - 6 (1 + 0 + 0 + 2 + 3)
For example I found the answer that is rated higher for the above question.
def sum_digits_of(n:int) -> int:
return sum(map(int, str(n)))
SumDigitsOf = sum_digits_of
For the above solution I did not understand '(n:int) -> int' and 'map(int, str(n))'
It's not that I don't know programming but I can't understand the code like above.I know simpler methods for solving this. But how to write and understand much more efficient code. It would be great help if any of you guys suggest how will I get better or is it wise to post the code which I don't understand here [ already tried googling :) ], Cheers!
The code you show “casts” an int to a str, then takes it digit by digit (map applies a function to something iterable, simply put), “casts” each digit back to int and finally sums the digits. (And it is indented incorrectly.)
The final assignment merely creates an alias name for the function, it doens’t “do” anything.
In any case, strings (str) do not have to be necessarily involved:
def sum_digits_of(n, base=10):
result = 0
while n:
result += n % base
n //= base
return result
print(sum_digits_of(123456))

Why is there a traceback and indexerror in my code? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Currently I am learning Python from the book 'The Coders Apprentice' and I have stumbled upon an exercise which I have the feeling that I have nearly solved, but I get an error when I execute the program.
This is the exercise:
Write a program that takes a string and produces a new string that contains the exact characters that the first string contains, but in order of their ASCII-codes.
For instance, the string "Hello, world!" should be turned into " !,Hdellloorw". This is
relatively easy to do with list functions, which will be introduced in a future chapter, but for now try to do it with string manipulation functions alone.
I have added the code below and the error message as a picture.
from pcinput import getString
entString=getString("Enter your string here: ")
yourString=entString.strip()
def positioner(oldPosition):
newPosition=0
x=0
while x<len(yourString):
if ord(yourString[oldPosition])>ord(yourString[x]):
newPosition+=1
x+=1
return newPosition
i=0
y=0
newString=""
while y<len(yourString):
if positioner(i)==y:
newString+=yourString[i]
y+=1
elif positioner(i)<y:
newString+=yourString[i]
if i<len(yourString):
i+=1
else:
i=0
print(newString)
What have I done wrong? I am new to programming.
You are getting an index error because the line if positioner(i)==y: is being called with a value of i equal to the length of yourString. yourString[oldPosition] is then accessing an index which doesn't exist.
This is happening because the loop condition (y<len(yourString)) isn't doing any checking on the value of i, which is the one causing problems.
Some other quick comments:
You can use yourString = input("Enter your string here: ") to replace the first four lines, as I'm not sure what pcinput is - and couldn't find any packages of the same name.
Instead of using the while/x+=1 construct, you could instead use a for x in range(len(yourString)), which is a little neater.

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

Categories