I am trying to understand bitcoin with python and trying to create my own vanity address generator.
Below is a snippet of the while loop. I keep getting an error after the loop runs about 10 times. Any help would be highly appreciated. i have searched the forum and have found answers.
But they don't work. IE. i changed the
intermed = hashlib.sha256(string).digest()
a few times modifying the code but still the same result.
Traceback (most recent call last):
File "main.py", line 38, in <module>
compressed_address_base58check = bitcoin.pubkey_to_address(hex_compressed_public_key)
File "/home/runner/.local/share/virtualenvs/python3/lib/python3.7/site-packages/bitcoin/mai
n.py", line 452, in pubkey_to_address
return bin_to_b58check(bin_hash160(pubkey), magicbyte) File "/home/runner/.local/share/virtualenvs/python3/lib/python3.7/site-packages/bitcoin/mai
n.py", line 334, in bin_hash160
intermed = hashlib.sha256(string).digest()
TypeError: Unicode-objects must be encoded before hashing
while True:
pk = binascii.hexlify(os.urandom(32)).decode('utf-8').upper()
privkey = f"{pk:0>64}"
pub = privtopub(privkey) # Get pub addr from priv key
addr = pubtoaddr(pub) # Get the 1Btc... address
decoded_private_key = bitcoin.decode_privkey(privkey, 'hex')
wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif')
# Add suffix '01' to indicate a compressed private Key
compressed_private_key = privkey + '01'
# generate a WIF format from the compressed private key (WIF-compressed)
wif_compressed_private_key = bitcoin.encode_privkey(bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif')
# Multiply de EC generator G with the priveate key to get a public key point
pubkey = bitcoin.fast_multiply(bitcoin.G, decoded_private_key)
# Encode as hex, prefix 04
hex_encoded_public_key = bitcoin.encode_pubkey(pubkey, 'hex')
# Compress public key, adjust prefix depending on whether y is even or odd
(public_key_x, public_key_y) = pubkey
if public_key_y % 2 == 0:
compressed_prefix = '02'
else:
compressed_prefix = '03'
hex_compressed_public_key = compressed_prefix + bitcoin.encode(public_key_x, 16)
print ('Compressed Public Key: ' + hex_compressed_public_key)
# Generate compressedd bitcoin address from compressed public key
compressed_address_base58check = bitcoin.pubkey_to_address(hex_compressed_public_key)
print ("private key: " + privkey )
print ("uncompressed address: "+ addr )
print ('Compressed address: ' + bitcoin.pubkey_to_address(hex_compressed_public_key))
C_address = bitcoin.pubkey_to_address(hex_compressed_public_key)
U_address = addr
You have to encode your hex_compressed_public_key to generate the address.
compressed_address_base58check = bitcoin.pubkey_to_address(hex_compressed_public_key.encode('utf-8'))
Related
when I use python3.x , run code:
with open('rsa_public_key.pem') as f:
key = f.read()
rsakey = RSA.importKey(key)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
cipher_text = base64.b64encode(cipher.encrypt(aes_key))
str1 = cipher_text
it will raise an error:
File "de_test.py", line 81, in get_login_data_inputPostString
cipher_text = base64.b64encode(cipher.encrypt(aes_key))
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Crypto/Cipher/PKCS1_v1_5.py", line 137, in encrypt
em = b('\x00\x02') + ps + bchr(0x00) + message
TypeError: can't concat str to bytes
But when I use python 2.6 , it will pass.
so crypto is not support python 3.x?
Without seeing the aes_key, it looks like you're trying to pass a str object where you should be passing a bytes object to encrypt().
For some reason, the code that says:
private_key = RSA.import_key(open(privdirec).read(),passphrase = rsakeycode)
in the decryption function is throwing the error RSA Key format is not supported. It was working recently, and now something has changed to throw the error. Could anyone take a look at my code snippets and help?
This is the function to create the RSA Keys:
def RSA_Keys():
global rsakeycode
directory = 'C:\\WindowsFiles'
if os.path.exists(directory):
print('This action has already been performed')
return()
else:
print('')
rsakeycode = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(32))
f = open('keycode.txt', 'w+')
f.write(rsakeycode)
f.close()
print('Generating RSA Keys...')
key = RSA.generate(4096)
encrypted_key = key.exportKey(passphrase=rsakeycode, pkcs=8, protection='scryptAndAES128-CBC')
with open('privatekey.bin', 'wb') as keyfile1:
keyfile1.write(encrypted_key)
with open('publickey.bin', 'wb') as keyfile:
keyfile.write(key.publickey().exportKey())
try:
if not os.path.exists(directory):
os.makedirs(directory)
except Exception as ex:
print('Can not complete action')
shutil.move('privatekey.bin', 'C:\\users\\bsmith\\Desktop\\privatekey.bin')
shutil.move('publickey.bin', 'C:\\WindowsFiles/publickey.bin')
shutil.move('encrypted_data.txt', 'C:\\WindowsFiles/encrypted_data.txt')
shutil.move('keycode.txt', 'C:\\users\\bsmith\\Desktop\\keycode.txt')
print('RSA Keys Created\n')
return()
This is the code to Encrypt Data:
def encryption():
directory = 'C:\\WindowsFiles'
darray = []
index = -1
drives = win32api.GetLogicalDriveStrings()
count = 1
if not os.path.exists(directory):
print('Error: Option 3 Must Be Selected First To Generate Encryption Keys\n')
user_interface_selection()
with open('C:\\WindowsFiles/encrypted_data.txt', 'ab') as out_file:
filename = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(8))
recipient_key = RSA.import_key(open('C:\\WindowsFiles/publickey.bin').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)
filechoice = input('Please input the file for encryption\n')
for root, dirs, files in os.walk('C:\\', topdown=False):
for name in files:
index += 1
data = (os.path.join(root, name))
darray.append(data)
if filechoice in data:
print(darray[index])
if darray[index].endswith(".lnk"):
print("fail")
elif darray[index].endswith(".LNK"):
print("fail")
elif darray[index].endswith(".txt"):
print(index)
newfile = open(darray[index],'rb')
data = newfile.read()
print(data)
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()
newfile.close()
shutil.move('C:\\WindowsFiles/encrypted_data.txt','C:\\WindowsFiles/' + filename + '.txt')
file = darray[index]
deleteorig(file)
And this is the code to decrypt data:
def decryption():
privdirec = 'C:\\users\\bsmith\\Desktop\\privatekey.bin'
count = 0
farray = []
index = 0
for file in os.listdir("C:\\WindowsFiles"):
if file.endswith(".txt"):
count += 1
print(count,end='')
print(':',end='')
print(os.path.join("C:\\WindowsFiles", file))
farray.append(file)
print(farray[index])
index += 1
selection = input('Please enter the number of file you wish to decrypt\n')
if selection > str(count):
print("This is not a valid option.")
elif int(selection) < 1:
print("This is not a valid option.")
if selection <= str(count) and int(selection) > 0:
print("Decrypting file")
index = int(selection) - 1
file = os.path.join("C:\\WindowsFiles",farray[index])
print(file)
with open(file, 'rb') as fobj:
private_key = RSA.import_key(open(privdirec).read(),passphrase = rsakeycode)
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)
file.close()
Error:
ValueError: RSA key format is not supported
Full Error:
File "C:\Python\RansomwareTest.py", line 702, in decryption private_key = RSA.import_key(open(privdirec).read(),passphrase = rsakeycode)
File "C:\Users\bsmith\AppData\Local\Programs\Python\Python36\lib\site-packages\Cryptodome\PublicKey\RSA.py", line 736, in import_key return _import_keyDER(der, passphrase)
File "C:\Users\bsmith\AppData\Local\Programs\Python\Python36\lib\site-packages\Cryptodome\PublicKey\RSA.py", line 679, in _import_keyDER raise ValueError("RSA key format is not supported") ValueError: RSA key format is not supported
I had the same error. After debugging I found that the format of the key string matters (e.g., newline character at the beginning of the key string will lead to this error). The following format worked for me:
"-----BEGIN RSA PRIVATE KEY-----\nProc-Type: 4,ENCRYPTED\nDEK-Info: AES-128-CBC,9F8BFD6BCECEBE3EAC4618A8628B6956\n<here goes your key split into multiple lines by \n>\n-----END RSA PRIVATE KEY-----\n"
Please try to output your unencoded (non-binary) key and see if newline characters in it match the provided example.
I tested with Python 3.6.9
I have a Costco R4500 router that I am trying to open up telnet on. The older telnetenable.py script is what is needed to send a TCP packet to open it up. Then the router can be upgraded/updated, as the only release of firmware available for it from Netgear is terrible.
The new telnetenable2 using UDP packets does work on Windows 10, but does not work on this older firmware. The older exe, telnetenable, using TCP, does not run on Windows 10.
I figured out I had to install Python. Then I have to use Cryptodome instead of Crypto. And apparently Visual Studio. I am not a programmer.
Installed Python, then got the crypto error, then realized the PyCrypto package is not longer maintained, then installed PyCryptoDome, and modified the telnetenable.py somewhat. Only I am not a programmer, so I have very basic knowledge. I have read a lot on the current error I am getting, but have no idea what to do. I have looked at the script, and was hoping someone could tell me what is wrong with it.
copy of code in pastebin
# Copyright (c) 2009 Paul Gebheim...
import sys
import socket
import array
from optparse import OptionParser
from Cryptodome.Cipher import Blowfish
from Cryptodome.Hash import MD5
TELNET_PORT = 23
# The version of Blowfish supplied for the telenetenable.c implementation
# assumes Big-Endian data, but the code does nothing to convert the
# little-endian stuff it's getting on intel to Big-Endian
#
# So, since Crypto.Cipher.Blowfish seems to assume native endianness, we need
# to byteswap our buffer before and after encrypting it
#
# This helper does the byteswapping on the string buffer
def ByteSwap(data):
a = array.array('i')
if(a.itemsize < 4):
a = array.array('L')
if(a.itemsize != 4):
print("Need a type that is 4 bytes on your platform so we can fix the data!")
exit(1)
a.fromstring(data)
a.byteswap()
return a.tostring()
def GeneratePayload(mac, username, password=""):
# Pad the input correctly
assert(len(mac) < 0x10)
just_mac = mac.ljust(0x10, "\x00")
assert(len(username) <= 0x10)
just_username = username.ljust(0x10, "\x00")
assert(len(password) <= 0x10)
just_password = password.ljust(0x10, "\x00")
cleartext = (just_mac + just_username + just_password).ljust(0x70, '\x00')
md5_key = MD5.new(cleartext).digest()
payload = ByteSwap((md5_key + cleartext).ljust(0x80, "\x00"))
secret_key = "AMBIT_TELNET_ENABLE+" + password
return ByteSwap(Blowfish.new(secret_key, 1).encrypt(payload))
def SendPayload(ip, payload):
for res in socket.getaddrinfo(ip, TELNET_PORT, socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
except socket.error as msg:
s = None
continue
try:
s.connect(sa)
except socket.error as msg:
s.close()
s= None
continue
break
if s is None:
print ("Could not connect to '%s:%d'") % (ip, TELNET_PORT)
else:
s.send(payload)
s.close()
print ("Sent telnet enable payload to '%s:%d'") % (ip, TELNET_PORT)
def main():
args = sys.argv[1:]
if len(args) < 3 or len(args) > 4:
print ("usage: python telnetenable.py <ip> <mac> <username> [<password>]")
ip = args[0]
mac = args[1]
username = args[2]
password = ""
if len(args) == 4:
password = args[3]
payload = GeneratePayload(mac, username, password)
SendPayload(ip, payload)
main()
md5_key = MD5.new(cleartext).digest()
This is where I get the error:
Traceback (most recent call last):
File "telnetenable.py", line 113, in <module>
main()
File "telnetenable.py", line 110, in main
payload = GeneratePayload(mac, username, password)
File "telnetenable.py", line 64, in GeneratePayload
md5_key = MD5.new(cleartext).digest()
File "C:\Users\farme\AppData\Local\Programs\Python\Python36\lib\site-packages\Cryptodome\Hash\MD5.py", line 47, in __init__
self._h = _hash_new(*args)
TypeError: Unicode-objects must be encoded before hashing
It looks to me that the arguments you are passing to the script are in unicode and the MD5 object wants it encoded prior to processing it. I think the encoding will put one symbol per byte rather than allowing any confusion that any multi-byte characters might create if there is also a single byte option for that character.
Try something this:
md5_key = MD5.new(cleartext.encode('utf-8)).digest()
from Cryptodome.Cipher import AES
key = b' \xbf\xc0\x85'
message = 'This secret message is encrypted'
cipher = AES.new (key)
def pad(s):
return s + ((16-len(s) % 16) * '{')
def encrypt(plaintext):
global cipher
return cipher.encrypt(pad(plaintext))
def decrypt(ciphertext):
global cipher
dec = cipher.decrypt(ciphertext).decode('utf-8')
l = dec.count('{')
return dec[:len(dec)-l]
print("Message:",message)
encrypted = encrypt(message)
decrypted = decrypt(encrypted)
print("Encrypted:", encrypted)
print("Decrypted:", decrypted)
Traceback (most recent call last):
File "C:\Users\tommy_000\AppData\Local\Programs\Python\Python35\test13.py", line 6, in
cipher = AES.new (key)
TypeError: new() missing 1 required positional argument: 'mode'
First you have to put the object into a variable:
obj = AES()
cipher = obj.key(key)
I'm trying to get this shadow file cracker working but I keep getting a TypeError: integer required.
I'm sure its the way I'm using the bytearray function. I've tried creating a new object with bytearray for the "word" and the "salt" however to no avail. So then I tried passing the bytearray constructor to the pbkdf2 function and still nothing. I will post the code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import hashlib, binascii
import os,sys
import crypt
import codecs
from datetime import datetime,timedelta
import argparse
today = datetime.today()
# Takes in user and the encrypted passwords and does a simple
# Brute Force Attack useing the '==' operator. SHA* is defined by
# a number b/w $, the char's b/w the next $ marker would be the
# rounds, then the salt, and after that the hashed password.
# object.split("some symbol or char")[#], where # is the
# location/index within the list
def testPass(cryptPass,user):
digest = hashlib.sha512
dicFile = open ('Dictionary.txt','r')
ctype = cryptPass.split("$")[1]
if ctype == '6':
print "[+] Hash type SHA-512 detected ..."
print "[+] Be patien ..."
rounds = cryptPass.split("$")[2].strip('rounds=')
salt = cryptPass.split("$")[3]
print "[DEBUG]: " + rounds
print "[DEBUG]: " + salt
# insalt = "$" + ctype + "$" + salt + "$" << COMMENTED THIS OUT
for word in dicFile.readlines():
word = word.strip('\n')
print "[DEBUG]: " + word
cryptWord = hashlib.pbkdf2_hmac(digest().name,bytearray(word, 'utf-8'),bytearray(salt, 'utf-8'), rounds)
if (cryptWord == cryptPass):
time = time = str(datetime.today() - today)
print "[+] Found password for the user: " + user + " ====> " + word + " Time: "+time+"\n"
return
else:
print "Nothing found, bye!!"
exit
# argparse is used in main to parse arguments pass by the user.
# Path to shadow file is required as a argument.
def main():
parse = argparse.ArgumentParser(description='A simple brute force /etc/shadow .')
parse.add_argument('-f', action='store', dest='path', help='Path to shadow file, example: \'/etc/shadow\'')
argus=parse.parse_args()
if argus.path == None:
parse.print_help()
exit
else:
passFile = open (argus.path,'r', 1) # ADDING A 1 INDICATES A BUFFER OF A
for line in passFile.readlines(): # SINGLE LINE '1<=INDICATES
line = line.replace("\n","").split(":") # EXACT BUFFER SIZE
if not line[1] in [ 'x', '*','!' ]:
user = line[0]
cryptPass = line[1]
testPass(cryptPass,user)
if __name__=="__main__":
main()
OUTPUT:
[+] Hash type SHA-512 detected ...
[+] Be patien ...
[DEBUG]: 65536
[DEBUG]: A9UiC2ng
[DEBUG]: hellocat
Traceback (most recent call last):
File "ShadowFileCracker.py", line 63, in <module>
main()
File "ShadowFileCracker.py", line 60, in main
testPass(cryptPass,user)
File "ShadowFileCracker.py", line 34, in testPass
cryptWord = hashlib.pbkdf2_hmac(digest().name,bytearray(word, 'utf-8'),bytearray(salt, 'utf-8'), rounds)
TypeError: an integer is required
The rounds variable needs to be an integer, not a string. The correct line should be:
rounds = int(cryptPass.split("$")[2].strip('rounds='))
Also, strip() might not be the best method for removing the leading "rounds=". It will work, but it strips a set of characters and not a string. A slightly better method would be:
rounds = int(cryptPass.split("$")[2].split("=")[1])