def testSignAndVerify(self): msg = b'1231232131' keyPair = CryptoUtil.genKeyPair() privKey = CryptoUtil.getPrivateKey(keyPair) pubKey = CryptoUtil.getPublicKey(keyPair) sig = CryptoUtil.signMessage(privKey, msg) self.assertTrue(CryptoUtil.verifySignature(pubKey, msg, sig), 'correct signature not verified')
def reencrypt_and_resign_purchase_message_to_department( department_connection, customer_signature, purchase_message, department_public_key): # Resend customer signature to deparmtent NetworkUtil.send_message(department_connection, customer_signature) # Re-encrypt purchase message using the department's public key, generate our own signature and send both to # the department encrypted_purchase_message = CryptoUtil.encrypt(purchase_message.encode(), department_public_key) supervisor_signature = CryptoUtil.sign(purchase_message.encode(), keypair) NetworkUtil.send_message(department_connection, encrypted_purchase_message) NetworkUtil.send_message(department_connection, supervisor_signature)
def send_purchase_to_supervisor(supervisor_connection, purchase_message, keypair, supervisor_public_key): # Encrypt purchase message with supervisor's public key encrypted_purchase_message = CryptoUtil.encrypt(purchase_message.encode(), supervisor_public_key) # Sign purchase message with our private key signature = CryptoUtil.sign(purchase_message.encode(), keypair) NetworkUtil.send_message(supervisor_connection, encrypted_purchase_message) NetworkUtil.send_message(supervisor_connection, signature) confirmation = NetworkUtil.receive_message(supervisor_connection) return encrypted_purchase_message, signature, confirmation
def main(args): if len(args) != 4 or args[1] not in ['dec', 'enc']: print 'Usage: crypt.py enc <plaintext> <passphrase>' print ' crypt.py dec <encrypted> <passphrase>' return op = args[1] key = args[3] if op == 'enc': plain = args[2] try: print CryptoUtil.encrypt(plain, key) except KeyLengthError, ex: print ex
def handle_supervisor_purchase_message(supervisor_connection, keypair, customer_public_key, supervisor_public_key): customer_signature = NetworkUtil.receive_message(supervisor_connection) encrypted_purchase_message = NetworkUtil.receive_message( supervisor_connection) supervisor_signature = NetworkUtil.receive_message(supervisor_connection) purchase_message = CryptoUtil.decrypt(encrypted_purchase_message, keypair).decode() print(f"Purchase message is: {purchase_message}") CryptoUtil.verify(purchase_message.encode(), customer_public_key, customer_signature) CryptoUtil.verify(purchase_message.encode(), supervisor_public_key, supervisor_signature) return encrypted_purchase_message, supervisor_signature, purchase_message
def handle_customer_purchase_message_and_confirm(customer_connection, keypair, customer_public_key): encrypted_purchase_message = NetworkUtil.receive_message( customer_connection) customer_signature = NetworkUtil.receive_message(customer_connection) purchase_message = CryptoUtil.decrypt(encrypted_purchase_message, keypair).decode() print(f"Purchase message is: {purchase_message}") CryptoUtil.verify(purchase_message.encode(), customer_public_key, customer_signature) timestamp = purchase_message.split("|")[0] item = purchase_message.split("|")[1] print(f"Customer would like to purchase {item} at {timestamp}.") confirmation = input(f"Confirm the above purchase? (y/n) ") return confirmation, customer_signature, purchase_message, encrypted_purchase_message
def exchange_public_keys(connection): keypair = CryptoUtil.generate_keypair() # Send department public key to supervisor NetworkUtil.send_message(connection, keypair.public_key().exportKey()) # Receive public key from supervisor supervisor_public_key = RSA.importKey( NetworkUtil.receive_message(connection)) return keypair, supervisor_public_key
def testBadSignature(self): msg = b'1231232131' keyPair = CryptoUtil.genKeyPair() privKey = CryptoUtil.getPrivateKey(keyPair) sig = CryptoUtil.signMessage(privKey, msg) keyPair2 = CryptoUtil.genKeyPair() pubKey2 = CryptoUtil.getPublicKey(keyPair2) self.assertFalse(CryptoUtil.verifySignature(pubKey2, msg, sig), 'incorrect signature was verified as correct')
def main(args): if len(args) != 2 or args[1] not in ['decrypt','encrypt','enc','dec']: usage() op = args[1] if op in ['enc', 'encrypt']: key = getpass.getpass('Please enter the encryption key: ') plaintext = getpass.getpass('Please enter the plaintext you wish to encrypt: ') try: encrypted_value = CryptoUtil.encrypt(plaintext, key) print "Encrypted Value: " + encrypted_value except KeyLengthError, ex: print ex
def main(args): if len(args) != 2 or args[1] not in ['decrypt', 'encrypt', 'enc', 'dec']: usage() op = args[1] if op in ['enc', 'encrypt']: key = getpass.getpass('Please enter the encryption key: ') plaintext = getpass.getpass( 'Please enter the plaintext you wish to encrypt: ') try: encrypted_value = CryptoUtil.encrypt(plaintext, key) print "Encrypted Value: " + encrypted_value except KeyLengthError, ex: print ex
def testTransactionMultipleInsAndOuts(self): expectedHash = b'\xfa\xc7t\x1f\xf0\xa3\xf5a\xdd\x9e\x0c\x96\x97\xd0\xdb\xa8L\xd9\x0cH\xca\xee\xd4g\x19 \xac\x84\xdd2\x11\xdb' self.assertEqual(tx2in2out.getHash(), expectedHash, 'incorrect hash') self.assertEqual(tx2in2out.numInputs(), 2, 'incorrect number of inputs') self.assertEqual(tx2in2out.numOutputs(), 2, 'incorrect number of outputs') self.assertEqual(tx2in2out.getInput(0).prevTxHash, genesis.hash, 'incorrect prevTxHash for input 0') self.assertEqual(tx2in2out.getInput(1).index, 1, 'incorrect index for input 1') self.assertEqual(tx2in2out.getInput(0).signature, sig0, 'incorrect signature for input 0') self.assertEqual(tx2in2out.getOutput(0).value, 10.0, 'incorrect value for output 0') self.assertEqual(tx2in2out.getOutput(1).address, scroogePubK, 'incorrect address for output 1') self.assertEqual(tx2in2out.getInputs()[1], tx2in2out.getInput(1), 'getInputs failure') self.assertEqual(tx2in2out.getOutputs()[0], tx2in2out.getOutput(0), 'getOutputs failure') self.assertIsNone(tx2in2out.getInput(tx2in2out.numInputs()), 'getInput failed to recognize out of bounds') self.assertIsNone(tx2in2out.getOutput(tx2in2out.numOutputs()), 'getOutput failed to recognize out of bounds') self.assertTrue(CryptoUtil.verifySignature(scroogePubK, tx2in2out.getRawDataToSign(0), tx2in2out.getInput(0).signature), \ 'signature on input 0 does not verify')
def exchange_public_keys(department_connection, customer_connection): keypair = CryptoUtil.generate_keypair() # Send Supervisor Public key to Department and Customer NetworkUtil.send_message(department_connection, keypair.public_key().exportKey()) # Department NetworkUtil.send_message(customer_connection, keypair.public_key().exportKey()) # Customer # Gather Public Keys from Department and Customer department_public_key = RSA.importKey( NetworkUtil.receive_message(department_connection)) customer_public_key = RSA.importKey( NetworkUtil.receive_message(customer_connection)) # Send Customer Public key to Department NetworkUtil.send_message(department_connection, customer_public_key.exportKey()) return keypair, department_public_key, customer_public_key
import CryptoUtil import sys from CryptoUtil import KeyLengthError __author__ = 'bryce' def main(args): if len(args) != 4 or args[1] not in ['dec', 'enc']: print 'Usage: crypt.py enc <plaintext> <passphrase>' print ' crypt.py dec <encrypted> <passphrase>' return op = args[1] key = args[3] if op == 'enc': plain = args[2] try: print CryptoUtil.encrypt(plain, key) except KeyLengthError, ex: print ex elif op == 'dec': encrypted = args[2] try: print CryptoUtil.decrypt(encrypted, key) except KeyLengthError, ex: print ex if __name__ == "__main__": main(sys.argv)
def main(args): if len(args) != 2 or args[1] not in ['decrypt', 'encrypt', 'enc', 'dec']: usage() op = args[1] if op in ['enc', 'encrypt']: key = getpass.getpass('Please enter the encryption key: ') plaintext = getpass.getpass( 'Please enter the plaintext you wish to encrypt: ') try: encrypted_value = CryptoUtil.encrypt(plaintext, key) print "Encrypted Value: " + encrypted_value except KeyLengthError, ex: print ex if op in ['dec', 'decrypt']: key = getpass.getpass('Please enter the encryption key: ') encrypted_value = getpass.getpass( 'Please enter the encrypted string you wish to decrypt: ') try: decrypted_value = CryptoUtil.decrypt(encrypted_value, key) print "Plaintext Value: " + decrypted_value except KeyLengthError, ex: print ex if __name__ == "__main__": main(sys.argv)
import unittest import CryptoUtil from Block import Block from Block import COINBASE from BlockChain import CUT_OFF_AGE from BlockChain import BlockChain from Transaction import Transaction from BlockHandler import BlockHandler scroogeKeyPair = CryptoUtil.genKeyPair() scroogePriKey = CryptoUtil.getPrivateKey(scroogeKeyPair) scroogePubKey = CryptoUtil.getPublicKey(scroogeKeyPair) def signInput(tx, priKey, index): tx.addSignature(CryptoUtil.signMessage(priKey, tx.getRawDataToSign(index)), index) class BlockChainTest(unittest.TestCase): def testMethods(self): genesis = Block(b'', scroogePubKey) genesis.finalize() blockChain = BlockChain(genesis) blockHandler = BlockHandler(blockChain) # Genesis block test self.assertEqual(genesis.getHash(), blockChain.getMaxHeightBlock().getHash(), \ 'genesis should be max height block') self.assertEqual(blockChain.getMaxHeightBlock(), genesis, \ 'genesis should be max height block')
print exit() def main(args): if len(args) != 2 or args[1] not in ['decrypt','encrypt','enc','dec']: usage() op = args[1] if op in ['enc', 'encrypt']: key = getpass.getpass('Please enter the encryption key: ') plaintext = getpass.getpass('Please enter the plaintext you wish to encrypt: ') try: encrypted_value = CryptoUtil.encrypt(plaintext, key) print "Encrypted Value: " + encrypted_value except KeyLengthError, ex: print ex if op in ['dec', 'decrypt']: key = getpass.getpass('Please enter the encryption key: ') encrypted_value = getpass.getpass('Please enter the encrypted string you wish to decrypt: ') try: decrypted_value = CryptoUtil.decrypt(encrypted_value, key) print "Plaintext Value: " + decrypted_value except KeyLengthError, ex: print ex if __name__ == "__main__": main(sys.argv)
def signInput(tx, privKey, index): tx.addSignature(CryptoUtil.signMessage(privKey, tx.getRawDataToSign(index)), index)
def finalize(self): ''' Compute and add the hash to this transaction. ''' self.hash = CryptoUtil.digest(self.getRawTx())
if __name__ == "__main__": # Connect to department and customer department_connection, customer_connection = listen_for_department_and_customer( ) # Generate our key pair and and get the public keys of others keypair, department_public_key, customer_public_key = exchange_public_keys( department_connection, customer_connection) while True: confirmation, customer_signature, purchase_message, encrypted_purchase_message = handle_customer_purchase_message_and_confirm( customer_connection, keypair, customer_public_key) if confirmation == 'y': # Tell customer that order is confirmed confirmation_msg = CryptoUtil.encrypt( "Order was confirmed".encode(), customer_public_key) NetworkUtil.send_message(customer_connection, confirmation_msg) reencrypt_and_resign_purchase_message_to_department( department_connection, customer_signature, purchase_message, department_public_key) else: # Rejected order confirmation_msg = CryptoUtil.encrypt( "Order was rejected".encode(), customer_public_key) NetworkUtil.send_message(customer_connection, confirmation_msg) # Show all the received messages (encrypted) presentation = input( "Show the all sending and receiving messages? (y/n)") if (presentation == 'y'):
return encrypted_purchase_message, signature, confirmation if __name__ == "__main__": # Connect to supervisor supervisor_connection = ClientNetworkUtil.connect_to_supervisor() # Generate our key pair and get the supervisor's public key keypair, supervisor_public_key = ClientNetworkUtil.exchange_public_keys( supervisor_connection) while True: # Ask the user for an item to purchase and get the purchase message purchase_message = ask_user_for_purchase_message() print(f"Purchase message is: {purchase_message}") # Send purchase to supervisor (encrypted_purchase_message, signature, confirmation) = send_purchase_to_supervisor(supervisor_connection, purchase_message, keypair, supervisor_public_key) confirmation_msg = CryptoUtil.decrypt(confirmation, keypair).decode() print(confirmation_msg) # Show all the received messages (encrypted) presentation = input("Show the all receiving messages? (y/n)") if (presentation == 'y'): print(f"\nSupervisor's public key: {supervisor_public_key}", ) print(f"\nEncrypted order Message: {encrypted_purchase_message}") print(f"\nConfirmation message from supervisor: {confirmation}")
# Use a fixed Scrooge key for the testing. exportedKey = b'-----BEGIN RSA PRIVATE KEY-----\nMIICXAIBAAKBgQCyvh9t+A9qWzUZL2fPuh' + \ b'//LhAdnuRtnaG8slkrXo3AaTufedCH\nO+1kbz8csCeo0iQl0y4mQVW3Z3I3VWl/CGRFE9eSNw3gh' + \ b'doIYRB6dfo46kDY7GVf\ncYnSR7fR/LEBcKQ48HpxX8S8dMy/zkbfIFEB9tVsZz9wOvleJmib2igEY' + \ b'wIDAQAB\nAoGAUohRUODKlWx57yAhihxCK/zj+hllFmxDwzKC0/C7+U1d93wy2k7EhayMcr2w\nAlb' + \ b'N1B1X4NgoMSB177DjnoGMckX1r8A4jrvSDDqymyqQxsBHvYrMuzdLmNql8uHW\nSPp1HnKYyaOJGEW' + \ b'aevQmv2Hb0uu53gxWEvAEQUYJt0QFNKECQQC9KQfwM9FamgQR\niPAQLOCEAGIEr9a/zHjR9IkVfzT' + \ b'88zyMUNnnn8xBM96kDfpVKR5ge/Ahja179i9G\nG1jCFNGRAkEA8ea9mCOGIo4osriiM6/pRZn+zmD' + \ b'cQDhV9s0CTMtlJvxykVO18EQs\nWlHJpmWQqAmn4d8TM1xxJrf7acOcdwO8swJATsgq/TinpeNldGQ' + \ b'jD6mRLIj4Sdlu\nSF2BqHf/LAvZ5svrWMlHp/de230d6hfEPfmtJCQaQ+885NcIo1s6YULIcQJBAMd' + \ b't\noXUiJF2ssaTWTvMp3blCAi4G8M4JI+X6kiDZtqTzj0h8qQxSR/aWYxbJuP6wJzYy\nANRhK+/t0' + \ b'loZqI7+B70CQH2LLsccb1MHAkAGRqDZjtAfFAt7p7IaNeEp0jo4TcvK\ny50t2C9i5aa5tY6TFp4pQ' + \ b'3Vfk6l+21J6e5BKari9wfY=\n-----END RSA PRIVATE KEY-----' scroogePrivK = Crypto.PublicKey.RSA.importKey(exportedKey) scroogePubK = CryptoUtil.getPublicKey(scroogePrivK) keyPair = CryptoUtil.genKeyPair() alicePrivK = CryptoUtil.getPrivateKey(keyPair) alicePubK = CryptoUtil.getPublicKey(keyPair) # Make a genesis transaction genesis = Transaction() genesisValue = 25.0 genesis.addOutput(genesisValue, scroogePubK) genesis.finalize() # Make an initial pool initialPool = UTXOPool() utxo = UTXO(genesis.getHash(), 0) initialPool.addUTXO(utxo, genesis.getOutput(0))
def testDigest(self): msg = b'1231232131' expected = b'\x9f\xb7&l\xd3{p\xc8j[\xcb\x89\xef\x19K9b\xc8\xaf\xbc\xca\x1d\x99\xf2\xeb\x89 \x1f\xb7\xe1\xd9\xf6' self.assertEqual(CryptoUtil.digest(msg), expected, 'incorrect digest')