def sign_rsa(timestamp, address, recipient, amount, operation, openfield, key, public_key_hashed): from Cryptodome.Signature import PKCS1_v1_5 from Cryptodome.Hash import SHA if not key: raise BaseException( "The wallet is locked, you need to provide a decrypted key") transaction = (str(timestamp), str(address), str(recipient), '%.8f' % float(amount), str(operation), str(openfield) ) # this is signed, float kept for compatibility h = SHA.new(str(transaction).encode()) signer = PKCS1_v1_5.new(key) signature = signer.sign(h) signature_enc = base64.b64encode(signature) verifier = PKCS1_v1_5.new(key) if verifier.verify(h, signature): return_value = str(timestamp), str(address), str( recipient), '%.8f' % float(amount), str( signature_enc.decode("utf-8")), str( public_key_hashed.decode("utf-8")), str(operation), str( openfield) # float kept for compatibility else: return_value = False return return_value
def decrypt(key: str, enc: bytes) -> str: # decrypt a given base64 bytes object. returns a string enc = base64.b64decode(enc) nonce = enc[:16] tempkey = SHA.new(key + nonce).digest() cipher = ARC4.new(tempkey) return cipher.decrypt(enc[16:]).decode("utf-8")
def _sign(self, unsigned_string): """ 通过如下方法调试签名 方法1 key = rsa.PrivateKey.load_pkcs1(open(self._app_private_key_path).read()) sign = rsa.sign(unsigned_string.encode("utf8"), key, "SHA-1") # base64 编码,转换为unicode表示并移除回车 sign = base64.encodebytes(sign).decode("utf8").replace("\n", "") 方法2 key = RSA.importKey(open(self._app_private_key_path).read()) signer = PKCS1_v1_5.new(key) signature = signer.sign(SHA.new(unsigned_string.encode("utf8"))) # base64 编码,转换为unicode表示并移除回车 sign = base64.encodebytes(signature).decode("utf8").replace("\n", "") 方法3 echo "abc" | openssl sha1 -sign alipay.key | openssl base64 """ # 开始计算签名 key = self.app_private_key signer = PKCS1_v1_5.new(key) if self._sign_type == "RSA": signature = signer.sign(SHA.new(b(unsigned_string))) else: signature = signer.sign(SHA256.new(b(unsigned_string))) # base64 编码,转换为unicode表示并移除回车 sign = encodebytes(signature).decode("utf8").replace("\n", "") return sign
def _cipher(data): xorKey = io.BytesIO() digest = constants.msKey[:20] while xorKey.tell() < len(data): digest = SHA.new(digest + constants.msKey[20:40]).digest() xorKey.write(digest) return strxor(data, xorKey.getvalue()[:len(data)])
def apicall(self, method, data): params = { 'UUID': self.new_uuid(), 'Data': data, } params['Data']['Username'] = self.username params['Data']['Password'] = self.password tosign = method + params['UUID'] + self._serializestruct( params['Data']) sha1hash = SHA.new(tosign.encode('utf-8')) signature = self.signer.sign(sha1hash) params['Signature'] = base64.b64encode(signature).decode('utf8') p = { 'method': method, 'params': params, 'version': '1.1', } resp = requests.post(self.apibase, json=p) if resp.status_code != 200: raise TrustlyException("bad http response code {0}".format( resp.status_code)) r = resp.json() if 'error' in r: # XXX log and raise generic exception! raise TrustlyException(r['error']['message']) if r['result']['method'] != method: raise TrustlyException("bad method in response") # XXX: verify signature? But we made a https call... return r['result']
def decrypt(ciphertext, password, magic=None): "Decrypts a data stream" # decrypt data if len(ciphertext) % 8 != 0: raise base.FormatError key = SHA.new(password.encode()).digest() # nosec cipher = Blowfish.new(key, Blowfish.MODE_CBC, IV) # nosec plaintext = cipher.decrypt(ciphertext) # check magic string if magic != None: if plaintext[:len(magic)] != magic: raise base.PasswordError else: plaintext = plaintext[len(magic):] # remove padding padchar = plaintext[-1] npadchar = padchar if (npadchar > 0): if plaintext[-npadchar:] != bytes([padchar] * npadchar): raise base.FormatError plaintext = plaintext[:-npadchar] return plaintext
def decrypt(self, ciphertext, key, padding="pkcs1_padding"): if padding == "pkcs1_padding": cipher = PKCS1_v1_5.new(key) if self.with_digest: dsize = SHA.digest_size else: dsize = 0 sentinel = Random.new().read(32 + dsize) text = cipher.decrypt(ciphertext, sentinel) if dsize: _digest = text[-dsize:] _msg = text[:-dsize] digest = SHA.new(_msg).digest() if digest == _digest: text = _msg else: raise DecryptionFailed() else: if text == sentinel: raise DecryptionFailed() elif padding == "pkcs1_oaep_padding": cipher = PKCS1_OAEP.new(key) text = cipher.decrypt(ciphertext) else: raise Exception("Unsupported padding") return text
def sign_this(): h = SHA.new(input_text.get("1.0", END).encode("utf-8")) signer = PKCS1_v1_5.new(key) signature = signer.sign(h) signature_enc = base64.b64encode(signature) output_signature.delete('1.0', END) # remove previous output_signature.insert(INSERT, signature_enc)
def decryptBlock(self, data): if self.isFirstBlock: self._digest = self._key1 xorKey = io.BytesIO() while xorKey.tell() < len(data): self._digest = SHA.new(self._digest + self._key2).digest() xorKey.write(self._digest) return strxor(data, xorKey.getvalue())
def sign_transaction(self): """ Sign transaction with private key """ private_key = RSA.importKey(binascii.unhexlify(self.sender_private_key)) signer = PKCS1_v1_5.new(private_key) h = SHA.new(str(self.to_dict()).encode('utf8')) return binascii.hexlify(signer.sign(h)).decode('ascii')
def verify_transaction_signature(self, sender_public_key, signature, transaction): public_key = RSA.importKey(binascii.unhexlify(sender_public_key)) verifier = PKCS1_v1_5.new(public_key) h = SHA.new(str(transaction).encode('utf8')) try: verifier.verify(h, binascii.unhexlify(signature)) return True except ValueError: return False
def RSA_mKey_CheckSign(message, signature): with open('master-public.pem', 'rb') as f: key = f.read() rsakey = RSA.importKey(key) verifier = Signature_pkcs1_v1_5.new(rsakey) digest = SHA.new() # 注意内容编码和base64解码问题 digest.update(message.encode(encoding=encode_gbk_utf8)) is_verify = verifier.verify(digest, base64.b64decode(signature)) return is_verify
def verify_transaction_signature(transaction, actor_key, signature): """ Check that the provided signature corresponds to transaction signed by the public key (actor's public key) """ actor_key = actor_key public_key = RSA.importKey(binascii.unhexlify(actor_key)) verifier = PKCS1_v1_5.new(public_key) h = SHA.new(str(transaction).encode('utf8')) return verifier.verify(h, binascii.unhexlify(signature))
def _verify(self, raw_content, signature): # 开始计算签名 key = self.alipay_public_key signer = PKCS1_v1_5.new(key) if self._sign_type == "RSA": digest = SHA.new() else: digest = SHA256.new() digest.update(raw_content.encode()) return bool(signer.verify(digest, decodebytes(signature.encode())))
def verify_transaction_signature(self, sender_address, signature, transaction): """ Check that the provided signature corresponds to transaction signed by the public key (sender_address) """ public_key = RSA.importKey(binascii.unhexlify(sender_address)) verifier = PKCS1_v1_5.new(public_key) h = SHA.new(str(transaction).encode('utf8')) return verifier.verify(h, binascii.unhexlify(signature))
def _sign(self, unsigned_string): key = self._app_private_key signer = PKCS1_v1_5.new(key) if self._sign_type == "RSA": signature = signer.sign(SHA.new(unsigned_string.encode("utf-8"))) else: signature = signer.sign(SHA256.new(unsigned_string.encode("utf-8"))) # base64 编码,转换为unicode表示并移除回车 sign = encodebytes(signature).decode("utf8").replace("\n", "") return sign
def RSA_mKey_Sign(message): with open('master-private.pem', 'rb') as f: key = f.read() rsakey = RSA.importKey(key) signer = Signature_pkcs1_v1_5.new(rsakey) digest = SHA.new() digest.update(message.encode(encoding=encode_gbk_utf8)) sign = signer.sign(digest) signature = base64.b64encode(sign) # 对结果进行base64编码 return signature
def check_precinct(): text = request.args.get('text') id = ObjectId(request.args.get('id')) if session['rank'] == 'worker1': applic.update_one({'application': text}, { "$set": { "history": [session['username']], 'check': session['username'] } }) elif session['rank'] == 'worker2.1' or session[ 'rank'] == 'worker2.2' or session['rank'] == 'worker2.3': for line in applic.find({'application': text}): history = line['history'] applic.update_one({'application': text}, { "$set": { "history": history + [session['username']], 'check': session['username'], 'status': 'Open' } }) elif session['rank'] == 'worker3': privatekey = RSA.importKey( db.find_one({'rank': 'worker3'})['privatekey']) cipherrsa = PKCS1_OAEP.new(privatekey) print(applic.find_one({'_id': id})['sessionkey']) print(type(applic.find_one({'_id': id})['sessionkey'])) sessionkey = cipherrsa.decrypt( applic.find_one({'_id': id})['sessionkey']) ciphertext = applic.find_one({'_id': id})['application'] iv = ciphertext[:16] obj = AES.new(sessionkey, AES.MODE_CFB, iv) plaintext = obj.decrypt(ciphertext) plaintext = plaintext[16:] plaintext = bytes(plaintext) signature = applic.find_one({'_id': id})['signature'] sig = cipherrsa.decrypt(signature[:256]) sig = sig + cipherrsa.decrypt(signature[256:]) publickey = RSA.importKey(applic.find_one({'_id': id})['publickey1']) myhash = SHA.new(plaintext) signature = PKCS1_v1_5.new(publickey) test = signature.verify(myhash, sig) for line in applic.find({'_id': id}): history = line['history'] applic.update_one({'_id': id}, { "$set": { 'history': history + [session['username']], 'check': session['username'], 'status': 'Open', 'application': str(plaintext)[2:-1] } }) flash('You approved the application!') return redirect('/profile')
def encrypt(self, msg, key, padding="pkcs1_padding"): if padding == "pkcs1_padding": cipher = PKCS1_v1_5.new(key) if self.with_digest: # add a SHA digest to the message h = SHA.new(msg) msg += h.digest() elif padding == "pkcs1_oaep_padding": cipher = PKCS1_OAEP.new(key) else: raise Exception("Unsupported padding") return cipher.encrypt(msg)
def _verify(self, raw_content, signature): # 开始计算签名 key = self.alipay_public_key signer = PKCS1_v1_5.new(key) if self._sign_type == "RSA": digest = SHA.new() else: digest = SHA256.new() digest.update(raw_content.encode("utf8")) if signer.verify(digest, decodebytes(signature.encode("utf8"))): return True return False
def send_precinct(): id = ObjectId(request.args.get('id')) text = request.args.get('text') if session['rank'] == 'worker2.1' or session[ 'rank'] == 'worker2.2' or session['rank'] == 'worker2.3': privatekey = RSA.importKey( db.find_one({'username': session['username']})['privatekey']) myhash = SHA.new(bytes(text, encoding='ascii')) signature = PKCS1_v1_5.new(privatekey) signature = signature.sign(myhash) publickey = RSA.importKey( db.find_one({'rank': 'worker3'})['publickey']) cipherrsa = PKCS1_OAEP.new(publickey) sig = cipherrsa.encrypt(signature[:128]) sig = sig + cipherrsa.encrypt(signature[128:]) sig = bytes(sig) sessionkey = Random.new().read(32) iv = Random.new().read(16) obj = AES.new(sessionkey, AES.MODE_CFB, iv) ciphertext = iv + obj.encrypt(bytes(text, encoding='ascii')) ciphertext = bytes(ciphertext) sessionkey = cipherrsa.encrypt(sessionkey) sessionkey = bytes(sessionkey) applic.update_one({'application': text}, { "$set": { 'check': None, 'level': 'worker3', 'sessionkey': sessionkey, 'application': ciphertext, 'signature': sig, 'publickey1': db.find_one({'username': session['username']})['publickey'] } }) flash('You sent the application!') elif session['rank'] == 'worker3': applic.update_one( {'_id': id}, {"$set": { 'check': None, 'level': 'end', 'status': 'Finished' }}) flash('You finished this case!') return redirect('/profile')
def _verify(self, raw_content, signature): '''验证签名''' key = self.alipay_public_key signer = PKCS1_v1_5.new(key) if self._sign_type == "RSA2": digest = SHA256.new() else: digest = SHA.new() digest.update(raw_content.encode("utf8")) # 验证签名 if signer.verify(digest, decodebytes(signature.encode("utf8"))): return True return False
def parse_notification(self, notstr): struct = json.loads(notstr) tosign = struct['method'] + struct['params'][ 'uuid'] + self._serializestruct(struct['params']['data']) sha1hash = SHA.new(tosign.encode('utf-8')) if self.verifier.verify( sha1hash, base64.b64decode(struct['params']['signature'])): return (struct['params']['uuid'], struct['method'], struct['params']['data']) else: # Indicate that signature failed return (struct['params']['uuid'], struct['method'], None)
def pycrypto(): import Crypto from Crypto.Hash import MD2 from Crypto.Hash import MD4 from Crypto.Hash import MD5 from Crypto.Hash import SHA from Crypto.Hash import SHA224 from Crypto.Hash import SHA256 from Crypto.Hash import SHA384 from Crypto.Hash import SHA512 from Crypto.Hash import HMAC Crypto.Hash.MD2.new() # Noncompliant MD2.new() # Noncompliant MD4.new() # Noncompliant MD5.new() # Noncompliant SHA.new() # Noncompliant SHA224.new() # Noncompliant SHA256.new() # Noncompliant SHA384.new() # Noncompliant SHA512.new() # Noncompliant HMAC.new(b"\x00") # Noncompliant
def sign_message_with_key(message: str, key): # Sign with key - This is a helper function # Returns the b64 encoded sig as a string h = SHA.new(message.encode('utf-8')) signer = PKCS1_v1_5.new(key) signature = signer.sign(h) signature_enc = base64.b64encode(signature) verifier = PKCS1_v1_5.new(key) if verifier.verify(h, signature): # print("OK") return signature_enc.decode("utf-8") else: return False
def send(self, wallet, recipient, amount, openfield='', operation=0): if (len(wallet.pub_key)) != 271 and (len(wallet.pub_key)) != 799: raise ValueError("Invalid public key length: {}".format(len(wallet.pub_key))) public_key_hashed = base64.b64encode(wallet.pub_key.encode('utf-8')) print("Sending from address: {}".format(wallet.address)) # Pulled from essentials.py fee = Decimal("0.01") + (Decimal(len(openfield)) / Decimal("100000")) # 0.01 dust print("Paying Fee: {}".format(fee)) if float(amount) < 0: raise Exception("Cannot send negative amounts") if len(str(recipient)) != 56: raise Exception("Wrong address length") timestamp = '%.2f' % time.time() sig_dat = ( str(timestamp), str(wallet.address), str(recipient), '%.8f' % float(amount), str(operation), str(openfield)) sig_dat_hash = SHA.new(str(sig_dat).encode("utf-8")) signer = PKCS1_v1_5.new(wallet.key) signature = signer.sign(sig_dat_hash) signature_enc = base64.b64encode(signature) txid = signature_enc[:56] print("Encoded Signature: {}".format(signature_enc.decode("utf-8"))) print("Transaction ID: {}".format(txid.decode("utf-8"))) verifier = PKCS1_v1_5.new(wallet.key) if not verifier.verify(sig_dat_hash, signature): raise Exception("Invalid signature was generated") tx_submit = ( str(timestamp), str(wallet.address), str(recipient), '%.8f' % float (amount), str(signature_enc.decode("utf-8")), str(public_key_hashed.decode("utf-8")), str(operation), str(openfield)) reply = self.command("mpinsert", [tx_submit]) print("Node responded with: {}".format(reply))
def verify(message, signature, pub_key, hash="SHA256"): signer = PKCS1_v1_5.new(pub_key) if (hash == "SHA512"): digest = SHA512.new() elif (hash == "SHA384"): digest = SHA384.new() elif (hash == "SHA256"): digest = SHA256.new() elif (hash == "SHA1"): digest = SHA.new() else: digest = MD5.new() digest.update(message) return signer.verify(digest, signature)
def anonymize(tx_count, per_tx, remainder, anon_recipient, identifier, anon_sender): # return remainder to source! a.execute("SELECT * FROM transactions WHERE openfield = ?", (identifier,)) try: exists = a.fetchall()[0] except:#if payout didn't happen yet print(tx_count, per_tx, remainder, identifier) for tx in range(tx_count): #construct tx openfield = "mixer" operation = 0 fee = fee_calculate(openfield) timestamp = '%.2f' % time.time() transaction = (str(timestamp), str(address), str(anon_recipient), '%.8f' % float(per_tx - fee), str(operation), str(openfield)) # this is signed h = SHA.new(str(transaction).encode("utf-8")) signer = PKCS1_v1_5.new(key) signature = signer.sign(h) signature_enc = base64.b64encode(signature) print("Encoded Signature: {}".format(signature_enc.decode("utf-8"))) verifier = PKCS1_v1_5.new(key) if verifier.verify(h, signature): print("The signature is valid, proceeding to save transaction to mempool") #construct tx a.execute("INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?)", (str(timestamp), str(address), str(anon_recipient), '%.8f' % float(per_tx - fee), str(signature_enc.decode("utf-8")), str(public_key_hashed), str(operation), str(identifier))) anon.commit() m.execute("INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?)", (str(timestamp), str(address), str(anon_recipient), '%.8f' % float(per_tx - fee), str(signature_enc.decode("utf-8")), str(public_key_hashed), str(operation), str(openfield))) mempool.commit() if (remainder - fee) > 0: openfield = "mixer" operation = 0 fee = fee_calculate(openfield) timestamp = '%.2f' % time.time() transaction = (str(timestamp), str(address), str(anon_sender), '%.8f' % float(remainder - fee), str(operation), str(openfield)) # this is signed m.execute("INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?)", (str(timestamp), str(address), str(anon_sender), '%.8f' % float(remainder - fee), str(signature_enc.decode("utf-8")), str(public_key_hashed), str(operation), str(openfield))) mempool.commit() return
def checksum(self): """A hash of all the inner properties, used for test purposes atm""" check = SHA.new(bytes(self.block_height)) check.update(str(self.timestamp).encode('utf-8')) check.update(self.address.encode('utf-8')) check.update(self.recipient.encode('utf-8')) check.update(bytes(self.amount)) check.update(self.signature) check.update(self.public_key) check.update(self.block_hash) check.update(bytes(self.fee)) check.update(bytes(self.reward)) check.update(self.operation.encode('utf-8')) check.update(self.openfield.encode('utf-8')) return check.digest()
def sign(self, signed_part, base64_output=False): """ Sign a message or transaction with PKCS1_v1_5 :param signed_part: the message or transaction tuple to sign :param base64_output: if True, encodes the signature with b64 (default False) :return: String. The signature alone. """ key = RSA.importKey(self.privkey) h = SHA.new(str(signed_part).encode("utf-8")) signer = PKCS1_v1_5.new(key) signature = signer.sign(h) if base64_output: return base64.b64encode(signature) else: return signature
def sign_rsa(timestamp: float, address: str, recipient: str, amount: int, operation: str, openfield: str, key): # Sign with key - This is a helper function # Returns the encoded sig as a string as_string = stringify_transaction(timestamp, address, recipient, amount, operation, openfield) print("As String", as_string) h = SHA.new(as_string) signer = PKCS1_v1_5.new(key) signature = signer.sign(h) signature_enc = base64.b64encode(signature) verifier = PKCS1_v1_5.new(key) if verifier.verify(h, signature): return signature_enc.decode("utf-8") else: return False
from Crypto.Hash import MD4 as pycrypto_md4 from Crypto.Hash import MD5 as pycrypto_md5 from Crypto.Hash import SHA as pycrypto_sha from Cryptodome.Hash import MD2 as pycryptodomex_md2 from Cryptodome.Hash import MD4 as pycryptodomex_md4 from Cryptodome.Hash import MD5 as pycryptodomex_md5 from Cryptodome.Hash import SHA as pycryptodomex_sha import hashlib hashlib.md5(1) hashlib.md5(1).hexdigest() abc = str.replace(hashlib.md5("1"), "###") print(hashlib.md5("1")) hashlib.sha1(1) pycrypto_md2.new() pycrypto_md4.new() pycrypto_md5.new() pycrypto_sha.new() pycryptodomex_md2.new() pycryptodomex_md4.new() pycryptodomex_md5.new() pycryptodomex_sha.new() hashes.MD5() hashes.SHA1()