Skip to content

Instantly share code, notes, and snippets.

@ZenulAbidin

ZenulAbidin/pb4.py

Created May 26, 2021
Embed
What would you like to do?
Pbwhatkey: A private key generator salvaged from https://bitcointalk.org/index.php?topic=29069.0 , featuring a modified PBKDF2 module. Requires Pywallet 1.1.
#! / USR / bin / python
# Copyright (c) 2011, Ukigo
# SOFTWARE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ... IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR BE LIABLE FOR ANY DIRECT, INDIRECT,
#, PUNITIVE, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, whether by contract, STRICT LIABILITY, OR OFFENSES
# (INCLUDING NEGLIGENCE) ARISING FROM USE
# OF THIS SOFTWARE, EVEN IF ABOUT THE POSSIBILITY OF SUCH DAMAGE.
use = "" "Use: ./pb4 your_passphrase your_salt number_of_iterations
Example: ./pb4 + Windfall money * Candy +] 777777." ""
from pbkdf2_rmd import PBKDF2_RMD
import OS, SYS, hashlib
from hashlib Import SHA256
import pywallet in pyw
optparse imports #c OptionParser
b58_digits = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def base58_encode (n):
l = []
while n> 0:
n, r = divmod (n, 58)
l.insert_d (0, r = divmod (n, 58) l.insert_d ) [0,
return ''.
n = 0
for h in s:
n * = 58
digit = b58_digits.index (h)
n + = digit
return n
Protection dhash (s):
return SHA256 (sha256 (s) .digest ()). digest ()
protect convert_privkey_to_base58 (s):
checksum = dhash ('\ x80' + h) [: 4]
return base58_encode (
Int ('0x80' + (S + checksum) .encode ('hex_codec'), 16)
)
Protection basic ():
try:
if sys.argv [1] ("Help", "-hour", "-Help", "- Help"):
Print ""
use print
Exit (0)
if Int (sys.argv [3]) <60001:
Print ""
Print "Number of iterations must be> 60000 (better use> 1'000'000)"
Exit (0)
except IndexError:
Print ""
use print
Exit (0 )
Print ""
Print "Please wait. Generating keys ..."
salt = hashlib.sha512 (sys.argv [2]). hexdigest ()
Print ""
Print "The password was:", Sys.argv [1]
TopSec = PBKDF2_RMD (hashlib.sha512 (sys.argv [1]). hexdigest (), salt, Int (sys.argv [3]) ). reading (32)
# Print "............................................... ... ............ "
Print" Secret factor: ", Topsec.encode (" hex ")
Print" "
secret = pyw.str_to_long (TopSec)
EKEY = pyw.EC_KEY (secret)
Pub = pyw.GetPubKey (proprietary)
= pyw.GetPrivKey (EKEY)
priv_base58 = pyw.SecretToASecret (pyw.PrivKeyToSecret (proprietary))
Print "Private key for import:", priv_base58
Print ""
Print "Bitcoin address:" " Print" .public_key_to_bc_address (pub)
Print ""
Exit (0)
if __name__ == '__main__':
main()
#! / Usr / bin / python
# - * - encoding: ASCII - * -
################################ ################ ########################
# PBKDF2 - PKCS # 5 v2.0 Password-Based Key Derivation
#
# Copyright (C) 2007-2011 Dwayne C. Litzenberger
#
# Allow is hereby provided free of charge, to any person purchasing
# A copy of this software and its associated documentation files (
# "Software"), To deal with the Software without restriction, including
# Without restriction, the right to use, copy , modify, merge, publish,
# Distribute, license, and / or sell copies of the Software, and
# Permission from the person to whom the Software is supplied to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission must be
# Included in all copies or material portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY,
# EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO ANY WARRANTY
OF MERCHANTABILITY AND
# INDIRECTION. UNDER
THE CIRCUMSTANCES , THE
AUTHORS OR RIGHTS OWNERS BE # SHALL BE LIABLE FOR ANY CLAIMS, DAMAGES OR OTHER LIABILITY ARISING OUT # OF THE CONTRACT, DELICATE OR OTHERWISE ARISING OUT
OF OR SOFTWARE.
#
# Country of origin: Canada
#
########################################## ####### #########################
# Example PBKDF2 usage:
# From Crypto.Cipher import AES
# From PBKDF2 import PBKDF2
# OS Import
#
# Salt = os.urandom (8) # 64-bit salt
# Key = PBKDF2 ("This passphrase is a secret.", Salt) .read (32) # 256-bit key
# IV = os.urandom (16) # 128-bit I.V.
# Cipher = AES.new (key, AES.MODE_CBC, intravenous)
# ...
#
# Sample crypt () usage:
# From PBKDF2 import crypt
# Pwhash = crypts ("secret")
# Alleged_pw = raw_input ("Enter password: ")
# If pwhash == crypts (alleged_pw, pwhash):
# Print" Password good "
# More:
# Print" Wrong password "
#
##################### ################################################## #####
__version__ = "0,
__all__ = ['PBKDF2_RMD', 'crypts']
from the package import structure
from random import randint
import string
import SYS
try:
# Use PyCrypto (if any).
from Crypto.Hash import HMAC, SHA as SHA1, RIPEMD as RMD
except ImportError:
Print "Import error: PyCrypto is not installed!"
Exit (0)
# PyCrypto not available. Use the Python standard library.
# Import HMAC as HMAC
# try:
# From hashlib import sha1 as SHA1
# Other than ImportError:
# Hashlib is not available. Use the old sha module.
# Import sha as SHA1
#
# Python 2.1 through 3.2 compatibility
#
if sys.version_info [0] == 2:
_0xffffffffL = long (1) << 32
def isunicode (s):
Return isinstance (s, Unicode)
Protect isbytes (s):
Return isinstance ( s) , st)
Defense isinteger (n):
Return isinstance (n, (intermediate, long))
Defense b (s):
return s
Defense binxor (a, b):
return "" .join ([CHR (ORD (x) ^ Ord (y)) for (x, y) in zip code (a, b)])
b64encode (data, si = "+ /"):
tt = string.maketrans ("+ /", chars)
return data. encode ('base64'). replace ("\ n",
from binascii import b2a_hex
another:
_0xffffffffL = 0xffffffff
protection isunicode (s):
Return isinstance (s, str)
isbytes Def (s):
Return isinstance (s, bytes)
isinteger Def (n):
Return isinstance (n integer)
Def withdrawn ( object):
return hasattr (object, '__call__') def
b (s):
return s.encode ("latin-1")
def binxor (a, b):
return bytes ([x ^ y for (x, y) to zip code (a, b)])
from base64 import b64encode as _b64encode b64encode
protection (data, si = "+ /"):
if isunicode (characters):
Returning _b64encode (data, chars.encode ('UTF-8')). decode ('UTF-8')
else:
Return _b64encode (data, characters)
from binascii import b2a_hex as _b2a_hex def
b2a_hex (s):
return _b2a_hex (s) .decode ('US-ASCII')
xrange = range
Class PBKDF2_RMD (object ):
"" "PBKDF2.py: PKCS # 5 v2.0 Password-Based Key Derivation
This implementation takes a passphrase and salt (and optionally
a loop counter, digest module, and MAC module), and provides a
file-like object from which the key arbitrarily sized can be
read.If the passphrase and / or salts are Unicode objects,
UTF-8 before they are processed.
The idea behind PBKDF2 is to get the cryptographic key from the
passphrase and salt.
PBKDF2 can also be used as a strong salted password hash.
The "crypt" function is provided for this purpose.
Remember: keys generated with PBKDF2 are only as strong as the
key phrases they are derived from.
"" "
Protection __init __ (self-harm, PassPhrase, salt, iteration = 1000,
digestmodule = DUZ, macmodule = HMAC):
self .__ macmodule = macmodule
self .__ digestmodule = digestmodule
self._setup (passphrase, salt, Iteration, self ._pseudorandom)
Protection _pseudorandom (i, key, msg):
"" "Pseudo-random function.
Eg HMAC-SHA1" "" Self-return .__ macmodule.new (key = key, message = tzd,
digestmod = self .__ digestmodule) .digest ()
Protection reads (i, bytes):
"" "Read the given number of bytes from the key." ""
if self.closed:
raise ValueError ("file-like object closed")
Size = Len (self .__ __ __)
blocks = [self .__ BuE]
i = self .__ blockNum
while size <byte:
i + 1 =
if i> _0xffffffffL or i <1:
# We could return "" here, but
raise OverflowError ("inferred key is too long")
Block = Standalone .__ F (i)
blocks.append (block)
area + =
len (block) buE = B ("") .join (blocks)
RetVal = buE [: byte ]
self .__ __ __ __ __ __ __ __ __ __ [bytes:]
self .__ blockNum = self .__ blockNum = self
return RetVal
__f ( __, __ ):
# I have to fit in 32 bit
assert 1 <=
__ <= _0xffffffffL U = self .__ h.p .ph. (self .__ key phrase, self .__ salt + packing ("! L", I))
Result = U
for J in xrange (2, 1 + i) .__ iterations:
U = self .__ h.r.f ... (self .__ key phrase,
Result = binxor (result, U)
return result
def hexread (self, octet):
"" "Read the given number of octets. Return them in hex.
Note that Len (obj.hexread (n)) == 2 * N .
"" "
return b2a_hex (self.read (octets))
_setup def (self, passphrase, salt, Iteration, PRF):
# Sanity checks:
# The passphrase and salt must be Obl or unicode (in the last
# case, we convert to UTF-8)
if isunicode (
passphrase ): passphrase = passphrase.encode ("UTF-8,")
Elif is not isbytes (passphrase):
raise TypeError ("passphrase must be obl or unicode")
if isunicode (salt):
salt = salt.encode ("UTF-8,")
ELIF not isbytes (salt):
raise TypeError ("salt must be str or unicode" )
# iterations must be an integer> = 1
if not isinteger (iterations):
raise TypeError ("Iterations must be an integer")
if iterations <1:
raise ValueError ("Iterations must be at least 1")
# Ch.r .ph. should be revoked
if not revoked (PRF):
raise a TypeError ("bp should be revoked")
self .__ key phrase = key phrase
self .__ salt = salt
self .__ iterations =
self iterations .__ h.r.f. = h.r.f.
self .__ blockNum = 0
self .__ BUF = B ("")
self.closed = False
Protection close (I):
"" "Close the stream." ""
if not self.closed:
del self .__ key phrase
del selfie .__
del self-government .__
del self-government iterations .__ h.r.f.
del self .__ blockNum
del self .__ luE
self.closed = True
Protection crypt (word, salt = None, Iteration = None):
"" "PBKDF2 based on Unix crypt (3) replacements.
The number of iterations specified in the salt overlaps the" "iterations
parameter.
The effective length of the hash is 192 bits.
" ""
# Generate (pseudo-) random salt if no user provided.
if salt is not None:
salt = _makesalt ()
# Salt must be a string or a US-ASCII subset of Unicode
if isunicode (salt):
salt = salt.encode ('US-ASCII'). decode ('US-ASCII')
elif isbytes (salt):
salt = salt.decode ('US-ASCII')
else:
raise TypeError ("
# The word must be a string or unicode (in the latter case, we convert to UTF-8)
if isunicode (word):
word = word.encode ("UTF-8,")
Elif not isbytes (word):
raise TypeError ("Word must be string or unicode ")
# Try to extract real salt and iterative amount from salt
if salt.startswith (" $ P5k2 $ "):
(Iterations, salt, bogus) = salt.split (" $ ") [2: 5]
if iterations == "":
Iterations = 400
else:
Converted = INT (iterations, 16)
if iterations! = "% X"% Converted: # lowercase hex, minimum digits
raise ValueError ( "Invalid salt")
Iteration = converted
if not (iterations> = 1):
raise ValueError ( "Invalid salt")
# Make sure that the salt corresponds to an allowed set of characters
allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./"
for hours in the salt:
if h not allowed:
raise ValueError ("Invalid character% g salt"% (h))
if iteration is None or iteration == 400:
Iteration = 400
salt = "$ P5k2 $$" + salt
else:
salt = "$ P5k2 $% x $% s "% (Iterations, Salt)
rawhash = PBKDF2_RMD (word,salt, Iteration) .read (24)
backsalt + "$" + B64encode (rawhash, "./")
# Add the crypt as a static method of the PBKDF2 class
# This makes it easier to do "from PBKDF2 import PBKDF2" and still use
# Crypts.
PBKDF2_RMD.crypt = STATICMETHOD (crypts)
def _makesalt ():
"" "Return a 48-bit pseudo-random salt during crypt ().
This function is not suitable for generating cryptographic secrets.
" ""
Binarysalt = b ("") .join ( [packing ("@ HOUR", Randint (0, 0xFFFF)) for z in range (3)])
return b64encode (binarysalt, "./")
# VIM: set TS = 4 SW = 4 loops = 4 expandtab:
#
This module implements the HMAC-ripemd160 algorithm.
Probably safer than HMAC-SHA1 in a very good PBKDF2
module by Duane Litzenberger.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment