def DecryptECIES(curve_name, R, enc, t, pwd): '''Performs ECIES decryption.''' # Setup for Decryption E = PredefinedCurves(curve_name) # Get secret key s hashpwd = SHA512.new(pwd).hexdigest() + RIPEMD.new(pwd).hexdigest() s = int(str(int(hashpwd,16))[0: len(str(E.N))]) % E.N if s < 2: s = E.N/2 # Begin Decryption Z = E.multPoint(s,R) RZ = str(R)+str(Z) H1 = SHA512.new(RZ).hexdigest() k1 = H1[0:32] k2 = H1[32:128] H2 = RIPEMD.new(enc+k2).digest() # If the hashes don't match, stop if base64.b64decode(t) != H2: return "Error: Hashes don't match! Your public key password is most likely incorrect. It is also possible, though improbable, that you selected the wrong encrypted image." cipher = AES.new(k1) message = cipher.decrypt(base64.b64decode(enc)) return message
def key_to_fingerprint(key): """ Fingerprint is used to uniquely identify an entity without exposing extra information. :param key: the public key :return: """ #assert len(key) == 32 sha256 = hashlib.sha256() sha256.update(key) key_hash = sha256.digest() #print('%r' % key_hash) #assert len(key_hash) == 32 ripemd = RIPEMD.new(key_hash) key_hash = ripemd.digest() #assert len(key_hash) == 20 sha256 = hashlib.sha256() sha256.update(FINGER_PREFIX) sha256.update(key_hash) checksum = sha256.digest() result = FINGER_PREFIX + key_hash + checksum[:4] return base58.b58encode(result)
def sign(wfi, trx, raw=True): pri = get_private_ket_by_wif(wfi) if not raw: trx = hashlib.sha256(trx).digest() privkey = PrivateKey(bytes(pri), raw=True) count = 0 i = 0 for j in range(0, 10, 1): count += 1 sig2, rec_id = privkey.ecdsa_sign(trx, raw=True, count=count) dsig = privkey.ecdsa_serialize(sig2) lenR = dsig[3] lenS = dsig[5 + lenR] if (lenR == 32 and lenS == 32): i = rec_id[0] i += 4 # compressed i += 27 # compact // 24 or 27 :( forcing odd-y 2nd key candidate) break R = dsig[4:36] S = dsig[38:] data = bytes([i]) + R + S + b'K1' h = RIPEMD.new() h.update(data) p = h.digest() checksum = p[0:4] data = bytes([i]) + R + S + checksum return "SIG_K1_" + base58.b58encode(data)
def hash_160(public_key): if 'ANDROID_DATA' in os.environ: from Crypto.Hash import RIPEMD md = RIPEMD.new() else: md = hashlib.new('ripemd') md.update(sha256(public_key)) return md.digest()
def hash160(data): """sha256 + ripemd160""" h1 = SHA256.new() h1.update(data) h2 = RIPEMD.new() h2.update(h1.digest()) rst = h2.hexdigest() return rst
def hash_160(public_key): try: md = hashlib.new('ripemd160') except: #FIXME: figure out why openssl lacks ripemd support from Crypto.Hash import RIPEMD md = RIPEMD.new('ripemd160') md.update(sha256(public_key)) return md.digest()
def btc_address(pub): """generate a bitcoin address from a public key pub: a public key to generate the bitcoin address with Return: the bitcoin address derived from the public key""" h = RIPEMD.new(data=pub) prefix = '00' hexstr = prefix + h.hexdigest() return b58encode(bytes(bytearray.fromhex(hexstr)))
def encode_coin_address(pub_key, coind_type): # ハッシュ値を計算する ripemd160 = RIPEMD.new() ripemd160.update(sha256(pub_key).digest()) binary = address_prefix(coind_type) + ripemd160.digest() # チェックサムを計算する cksum = sha256(sha256(binary).digest()).digest() # 最後に Base58 エンコードして完成 return b58encode(binary + cksum[0:4])
def key_to_peer_id(key): sha256 = hashlib.sha256() sha256.update(key) key_hash = sha256.digest() #print('%r' % key_hash) #assert len(key_hash) == 32 ripemd = RIPEMD.new(key_hash) return ripemd.digest()
def pub_key_fmt(prefix, keyhx): # generate V1 Address format # see: https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses # hash key - sha256 then ripemd160 h = RIPEMD.new(sha256(unhexlify(keyhx)).digest()) # add header prefix h_hashkey = prefix + hexlify(h.digest()).decode('utf-8') # calc checksum cksum = sha256(sha256(unhexlify(h_hashkey)).digest()).hexdigest()[:8] # encode base58 return b58encode(unhexlify(h_hashkey + cksum))
def wifaddress(publickey): ''' return public key hash in Wallet Import Format (WIF) ''' try: hashed = hashlib.new('ripemd160', sha256(publickey)).digest() except ValueError: # assume "unsupported hash type" from Crypto.Hash import RIPEMD hashed = RIPEMD.new(sha256(publickey)).digest() logging.debug('hashed: %r', hashed) return wifkey(hashed, b'\x00')
def get_pubkey(wfi): pri = get_private_ket_by_wif(wfi) privkey = PrivateKey(bytes(pri), raw=True) pubkey = privkey.pubkey.serialize() h = RIPEMD.new() h.update(pubkey) p = h.digest() checksum = p[0:4] return "EOS" + base58.b58encode(pubkey + checksum)
def PublicKeyECIES(curve_name, pwd, im): '''Create ECIES public key, create the associated binary string, and pass to the image encoder.''' # -------------------------- # ECIES Public Key Creation # -------------------------- E = PredefinedCurves(curve_name) # Generate secret key s via a password hashing. # Use a concatonation of two hash functions to make sure we have enough characters to get a full strength secret key. # For full strenth we need: number of digits of integer version of hash >= numbber of digits of the prime we're working over. hashpwd = SHA512.new(pwd).hexdigest() + RIPEMD.new(pwd).hexdigest() # Convert from hex to int, make hashpwd the same length as the order of the point we're using, then take it modulo order. s = int(str(int(hashpwd,16))[0: len(str(E.N))]) % E.N # If s = 0 or s = 1 (very unlikely), we want to use a different value. if s < 2: s = E.N/2 # Use the secret key s to generate the public key. B = E.multPoint(s, E.A) # ------------------------------------------------------------- # Create a binary string from the given public key information # ------------------------------------------------------------- # # Create a binary string with public key info separated by 2's. # End the string with consecutive 2's. # # The information is encoded in the following order: # # 0. Initial check string. # 1. Length of curve name. # 2. x-coordinate of ellipitc curve point B. # 3. y-coordinate of ellipitc curve point B. # 4. Curve name. # ------------------------------------------------------------- # Change curve name to binary, each character separated by a 2. curve_name_bin = '2'.join([bin(ord(ch)).lstrip('0b') for ch in curve_name]) # Initialize our string as "111111" so we have a quick check that our file is valid when decoding. bit_string = '1111112' # Now append on the binary public key information with a '2' separating each entry. # Note: curve_name_bin already ends in 2 so we only need to add one 2 at the final step. bit_string += bin(len(curve_name)).lstrip('0b') + '2' bit_string += bin(B[0]).lstrip('0b') + '2' bit_string += bin(B[1]).lstrip('0b') + '2' bit_string += curve_name_bin + '2' return EncodeImageInfo(bit_string, im)
def pub_2_address(pub_key): """ public key-(SHA256)-(RIPEMD160)->public key hash-(base58 encoding)->address :param pub_key: :return: str, address """ ripemd = RIPEMD.new() sha = get_hash(pub_key) ripemd.update(sha.encode()) pub_key_hash = ripemd.hexdigest() # TODO base58 encoding return pub_key_hash
def serialize_pubkey_compressed(self): if self.P is None: return None # generate V1 Address format # see: https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses # hash key - sha256 then ripemd160 h = RIPEMD.new(sha256(unhexlify(self.P.compress())).digest()) # add header prefix h_hashkey = WalletPubkey.network['pub'] + hexlify(h.digest()) # calc checksum cksum = sha256(sha256(unhexlify(h_hashkey)).digest()).hexdigest()[:8] # encode base58 return b58encode(unhexlify(h_hashkey + cksum.encode())).encode()
def bf(h, dictionary): f = open(dictionary, 'r') lines = f.readlines() print('\033[1;34m[*]\033[0m Starting Brute Force - hash = ' + h) for i in lines: ripehasher = RIPEMD.new() ripehasher.update(i[:-1]) h2 = ripehasher.hexdigest() if h == h2: print('\033[1;32m[+]\033[0m Hash Cracked! - Password = ' + i)
def ripemd_160(self): """Get RIPEMD-160 hash RIPEMD (RACE Integrity Primitives Evaluation Message Digest) is a family of cryptographic hash functions developed in Leuven, Belgium, by Hans Dobbertin, Antoon Bosselaers and Bart Preneel at the COSIC research group at the Katholieke Universiteit Leuven, and first published in 1996.<br><br>RIPEMD was based upon the design principles used in MD4, and is similar in performance to the more popular SHA-1. Returns: Chepy: The Chepy object. """ h = RIPEMD.new() h.update(self._convert_to_bytes()) self.state = h.hexdigest() return self
def md_sha_hash(flag, text): hash_text = None if flag == 'MD2': h = MD2.new() h.update(text) hash_text = h.hexdigest() elif flag == 'MD4': h = MD4.new() h.update(text) hash_text = h.hexdigest() elif flag == 'MD5': h = MD5.new() h.update(text) hash_text = h.hexdigest() elif flag == 'SHA1': h = SHA1.new() h.update(text) hash_text = h.hexdigest() elif flag == 'SHA224': h = SHA224.new() h.update(text) hash_text = h.hexdigest() elif flag == 'SHA256': h = SHA256.new() h.update(text) hash_text = h.hexdigest() elif flag == 'SHA384': h = SHA384.new() h.update(text) hash_text = h.hexdigest() elif flag == 'SHA512': h = SHA512.new() h.update(text) hash_text = h.hexdigest() elif flag == 'RIPEMD': h = RIPEMD.new() h.update(text) hash_text = h.hexdigest() elif flag == 'RIPEMD160': h = RIPEMD160.new() h.update(text) hash_text = h.hexdigest() else: return {'error': False, 'msg': u'未知hash算法!'} return {'error': True, 'msg': hash_text}
def pub_key_fmt_C(prefix, keyhx): # generate V1 Address format # see: https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses # hash key - sha256 then ripemd160 keyval = keyhx keybin = int(keyhx,16) if keyhx[:2] == '04': keyval = ('03' if (keybin % 2) else '02') + keyhx[2:66] elif (keyhx[:2] != '02') and (keyhx[:2] != '03'): raise ValueError('input is not ECC point format') print('keyval = ' + keyval) h = RIPEMD.new(sha256(unhexlify(keyval)).digest()) # add header prefix h_hashkey = prefix + hexlify(h.digest()).decode('utf-8') # calc checksum cksum = sha256(sha256(unhexlify(h_hashkey)).digest()).hexdigest()[:8] # encode base58 return b58encode(unhexlify(h_hashkey + cksum))
def pub_key_fmt_C(prefix, keyhx): # generate V1 Address format # see: https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses # hash key - sha256 then ripemd160 keyval = keyhx keybin = int(keyhx, 16) if keyhx[:2] == '04': keyval = ('03' if (keybin % 2) else '02') + keyhx[2:66] elif (keyhx[:2] != '02') and (keyhx[:2] != '03'): raise ValueError('input is not ECC point format') print('keyval = ' + keyval) h = RIPEMD.new(sha256(unhexlify(keyval)).digest()) # add header prefix h_hashkey = prefix + hexlify(h.digest()).decode('utf-8') # calc checksum cksum = sha256(sha256(unhexlify(h_hashkey)).digest()).hexdigest()[:8] # encode base58 return b58encode(unhexlify(h_hashkey + cksum))
def calculateAdresse(number): #Calculer le hash SHA 256 puis RIPEMD160 (voir librairies dans le cours), on appelle ce résultat hash160 sha256 = SHA256.new() number_in_bytes = number.to_bytes(2, byteorder='big') sha256.update(number_in_bytes) hash160 = RIPEMD.new(sha256.digest()) #print(hash160.digest()) #4 premiers octets du sha256(sha256(0x00 + hash160)) sha256_2 = SHA256.new() sha256_3 = SHA256.new() #0x00+hash160 sha256_2.update(bytes(1) + hash160.digest()) sha256_3.update(sha256_2.digest()) #4 premiers octets #print(sha256_3.digest()[:4]) #Convertir le nombre en base 58 return encode58(bytes(1) + hash160.digest() + sha256_3.digest()[:4])
def get_hash_instance(type_): """Given a hash type code, returns a new hash instance for that type. """ if type_ == 1: return MD5.new() elif type_ == 2: return SHA.new() elif type_ == 3: return RIPEMD.new() elif type_ == 8: return SHA256.new() elif type_ == 9: return SHA384.new() elif type_ == 10: return SHA512.new() elif type_ == 11: return SHA224.new() else: raise UnsupportedDigestAlgorithm(type_)
def identify_hash(self, hash2use): """ Identify type of cryptographic hashing to use for processing. :param hash2use: Value indicating type of hashing desired based upon user's input :return: No explicit value returned. Variables set for further processing. """ if hash2use == 1: self.h = RIPEMD.new() self.hstr = 'ripemd160' elif hash2use == 2: self.h = SHA224.new() self.hstr = 'sha224' elif hash2use == 3: self.h = SHA256.new() self.hstr = 'sha256' elif hash2use == 4: self.h = SHA384.new() self.hstr = 'sha384' elif hash2use == 5: self.h = SHA512.new() self.hstr = 'sha512'
def return_alg(k): """ @type k: str, unicode @return: @raise: """ if k == 'HMAC': return HMAC.new("kjhfsd") elif k == 'MD4': return MD4.new() elif k == 'MD5': return MD5.new() elif k == 'RIPEMD': return RIPEMD.new() elif k == 'SHA': return SHA.new() elif k == 'SHA224': return SHA224.new() elif k == 'SHA256': return SHA256.new() elif k == 'SHA384': return SHA384.new() elif k == 'SHA512': return SHA512.new()
def new(data=None): """Create a new RIPEMD-160 hash object data = initial input (raw string) to the hashing object if present, the method call update(arg) is made EXAMPLE: ========= >>> from CryptoPlus.Hash import RIPEMD >>> message = "abc" >>> hasher = RIPEMD.new() >>> hasher.update(message) >>> hasher.hexdigest() '8eb208f7e05d987a9b044a8e98c6b087f15a0bfc' >>> message = "message digest" >>> hasher = RIPEMD.new() >>> hasher.update(message) >>> hasher.hexdigest() '5d0689ef49d2fae572b881b123a85ffa21595f36' """ return RIPEMD.new(data)
def get_address(public_key: str) -> str: ''' 通过公钥计算得到交易的地址 :param public_key: 公钥,以字符串的形式传输,对应 Account.pu_s :return: 交易的地址 ''' # SHA256 h = SHA256.new() h.update(public_key[2:].encode('utf-8')) address = h.hexdigest() # RIPEMD h = RIPEMD.new() h.update(address.encode('utf-8')) address = h.hexdigest() address = '00' + address # Double SHA256 checksum = double_sha256(address)[:8] # base58 address = address + checksum address = base58.b58encode_int(int(address, 16)) return address.decode('utf-8')
from Crypto.Protocol import KDF parser = argparse.ArgumentParser(description='ANSI x9.17 DRBG') parser.add_argument('-b','--binary', help='Raw binary output.', action="store_true") parser.add_argument('-k','--key', help='SHA-256 key.') parser.add_argument('-s','--seed', help='Starting seed.') parser.add_argument('-n','--numbers', help='Quantity of random numbers.') args = parser.parse_args() def sxor(s1, s2): return ''.join(chr(ord(a)^ord(b)) for a,b in zip(s1,s2)) with open('/proc/interrupts','r') as f: data = f.read().replace('\n','') d = RIPEMD.new(data) ripemd = d.hexdigest() d = SHA.new(data) sha = d.hexdigest() salt = sxor(sha, ripemd) key = KDF.PBKDF2(sha, salt, 16, 0) seed = KDF.PBKDF2(ripemd, salt, 16, 0) number = 1 if args.key: key = KDF.PBKDF2(bytes(args.key), salt, 32, 0) if args.seed: seed = KDF.PBKDF2(bytes(args.seed), salt, 32, 0) if args.numbers:
def hash_160(public_key): if not have_crypto: return '' h1 = SHA256.new(public_key).digest() h2 = RIPEMD160.new(h1).digest() return h2
# Register your models here. from Crypto.Hash import HMAC from Crypto.Hash import MD2 from Crypto.Hash import MD4 from Crypto.Hash import MD5 from Crypto.Hash import RIPEMD from Crypto.Hash import SHA224 from Crypto.Hash import SHA256 from Crypto.Hash import SHA384 from Crypto.Hash import SHA512 print("HMAC encryption", HMAC.new('abc').hexdigest()) print("MD2 encryption", MD2.new('abc').hexdigest()) print("MD4 encryption", MD4.new('abc').hexdigest()) print("MD5 encryption", MD5.new('abc').hexdigest()) print("RIPEMD encryption", RIPEMD.new('abc').hexdigest()) print("SHA224 encryption", SHA224.new('abc').hexdigest()) print("SHA256 encryption", SHA256.new('abc').hexdigest()) print("SHA384 encryption", SHA384.new('abc').hexdigest()) print("SHA512 encryption", SHA512.new('abc').hexdigest()) #################3 from Crypto.Cipher import DES des = DES.new('01234567', DES.MODE_ECB) text = 'abcdefgh' cipher_text = des.encrypt(text) text = des.decrypt(cipher_text) print(cipher_text, text)
def hash_RIPEMD(self, key, salt): h = RIPEMD.new() h.update(key+salt) return h.hexdigest()
def myrmd160(fname): hash_rmd160=RIPEMD.new() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_rmd160.update(chunk) return hash_rmd160.hexdigest()
def _hashdigest(data): return RIPEMD.RIPEMD160Hash(data).digest()
def pubkey_to_hash(pubkey): return RIPEMD160.new(SHA256.new(pubkey).digest()).digest()
def EncryptECIES(curve_name, B, msg, im): '''Perform ECIES encryption, create the associated binary string, and pass to the image encoder.''' E = PredefinedCurves(curve_name) # Make sure the length is correct, otherwise add white space. For AES message length must be multiple of 16. while len(msg) % 16 != 0: msg += ' ' # Begin ECIES Encryption. k = random.randint(2, E.N-1) R = E.multPoint(k, E.A) Z = E.multPoint(k, B) RZ = str(R)+str(Z) H1 = SHA512.new() H1.update(RZ) k1 = H1.hexdigest()[0:32] k2 = H1.hexdigest()[32:128] cipher = AES.new(k1) enc = base64.b64encode(cipher.encrypt(msg)) H2 = RIPEMD.new() H2.update(enc+k2) t = base64.b64encode(H2.digest()) # --------------------------------------------------------------- # Create a binary string from the given encrypted msg information # --------------------------------------------------------------- # # Create a binary string with encrypted msg info separated by 2's. # End the string with consecutive 2's. # # The information is encoded in the following order: # # 1. Initial check string. # 2. Length of curve name. # 3. Length of the encrypted message. # 4. x-coordinate of ellipitc curve point R. # 5. y-coordinate of ellipitc curve point R. # 6. t, the authentication hash value # 7. Curve name. # 8. Encrypted message. # --------------------------------------------------------------- # Convert each character in t, curve_name, and enc to binary with 2's separating each character. t_bin = '2'.join([bin(ord(ch)).lstrip('0b') for ch in t]) curve_name_bin = '2'.join([bin(ord(ch)).lstrip('0b') for ch in curve_name]) enc_bin = '2'.join([bin(ord(ch)).lstrip('0b') for ch in enc]) # Initialize our string as "110011" so we have a quick check that our file is valid when decoding. bit_string = "1100112" # Now append on the binary public key information with a "2" separating each entry. bit_string += bin(len(curve_name)).lstrip('0b') + '2' bit_string += bin(len(enc)).lstrip('0b') + '2' bit_string += bin(R[0]).lstrip('0b') + '2' bit_string += bin(R[1]).lstrip('0b') + '2' bit_string += t_bin + '2' bit_string += curve_name_bin + '2' bit_string += enc_bin + '22' return EncodeImageInfo(bit_string, im)
def Hash4(key): key = key + str(HASH4_RAND) h = RIPEMD.new() h.update(key) v = number.bytes_to_long(h.digest()) return v
# dec_run.append(dec_trial.repeat(RUN_COUNT, 1)) # algo_run.append(dec_run) # set_run.append(algo_run) lib_run.append(set_run) # BEGIN HASHING OPERATIONS set_run = ['hash'] setup = """\ from __main__ import digest_prime, message digest = digest_prime.copy() """ algo_run = ['RIPEMD160'] digest_prime = RIPEMD.new() trial = Timer("digest.update(message)", setup) algo_run.append(trial.repeat(RUN_COUNT, 1)) set_run.append(algo_run) algo_run = ['SHA512'] digest_prime = SHA512.new() trial = Timer("digest.update(message)", setup) algo_run.append(trial.repeat(RUN_COUNT, 1)) set_run.append(algo_run) algo_run = ['MD5'] digest_prime = MD5.new() trial = Timer("digest.update(message)", setup) algo_run.append(trial.repeat(RUN_COUNT, 1)) set_run.append(algo_run)
# msg = "이 문서의 Hash Value를 계산한다." msg = "이 문서의 Hash Value를 계산한다?" print("\nMessgae : ", msg) msg = msg.encode() # MD5 h = MD5.new() h.update(msg) hv = h.hexdigest() print("\nMD5 (%d bit) : %s" % (len(hv) * 4, hv)) # RIPEMD160 h = RIPEMD.new() h.update(msg) hv = h.hexdigest() print("RIPEMD (%d bit) : %s" % (len(hv) * 4, hv)) # SHA h = SHA.new() h.update(msg) hv = h.hexdigest() print("SHA (%d bit) : %s" % (len(hv) * 4, hv)) # SHA-256 h = SHA256.new() h.update(msg)
""" secret = b'B3mB4m' h = HMAC.new(secret) h.update(word) print "HMAC = " + h.hexdigest() h2 = MD2.new() h2.update(word) print "MD2 = " + h2.hexdigest() h3 = MD4.new() h3.update(word) print "MD4 = " + h3.hexdigest() h4 = MD5.new() h4.update(word) print "MD5 = " + h3.hexdigest() h5 = RIPEMD.new() h5.update(word) print "RIPEMD = " + h5.hexdigest() h6 = SHA.new() h6.update(word) print "SHA = " + h6.hexdigest() h7 = SHA.new() h7.update(word) print "SHA256 = " + h7.hexdigest()
def any_rmd160(self, s, e, t): from Crypto.Hash import RIPEMD return self.rstr2any(RIPEMD.new(s).digest(), e, t)
def gen_address(self, pubkey: bytes): log.info( f'Generating Wallet address for public key {pubkey.hex()[:4]}...') pub_ripemd = RIPEMD.new(SHA256.new(pubkey).digest()) pub_b58 = b58encode(pub_ripemd.digest()) return pub_b58
def any_rmd160(self, inp, trim=True): """RMD160 function wrapper""" return self.rstr2any(RIPEMD.new(inp).digest(), trim)