def splitSecret(secret, threshold, splits): #Formatting key inorder to convert bytes of string using base64 secret = base64.b64encode(secret).decode('utf-8') shares = PlaintextToHexSecretSharer.split_secret(secret, threshold, splits) for i in range(splits): shares[i] = base64.b64encode(shares[i].encode('utf-8')).decode('utf-8') return shares
def split(args): keyfile = args.keyfile min = args.min max = args.max print("Keep or send one or more subkey securely.\n") with open(keyfile, 'r') as filehandle: key = filehandle.read() shares = PlaintextToHexSecretSharer.split_secret(key, min, max) for share in shares: print(share)
def encrypt_and_split(data, threshold_number, total): """ Encrypt the data with a symmetric encryption scheme using a random key. Then split the key using Shamir's secret sharing scheme into total number of subkeys. The key can be recreated using threshold_number of the subkeys generated. Return the subkeys along with the encrypted data. """ key, encrypted_data = encrypt(data) shares = shamir.split_secret(key.decode(), threshold_number, total) return (shares, encrypted_data)
def main(): global scale, threshold # Select number of shares numofShares = int(input("How many Shares do you want? ")) # Select revealing threshold if numofShares > 2: min_threshold = 2 max_threshold = numofShares thresholds = [x for x in range(min_threshold, max_threshold + 1) ] #shows the choices print(["Threshold limit is: ", thresholds]) threshold = int( input( "How many shares should be enough to decrypt? (Most secure is: " + str(max_threshold) + ")\n")) # Select type of shares output format = input( "Select the format of the output images\n-png\n-svg\n-terminal\n") # Select size of shares output if format != 'terminal': scale = input("Size of the output\nS\nM\nL\n") if scale == 'S': scale = 2 elif scale == 'M': scale = 4 elif scale == 'L': scale = 8 secret = input('Enter your message: ') # Secret-share the message using Shamir's secret sharing scheme. shares = PlaintextToHexSecretSharer.split_secret(secret, threshold, numofShares) print(shares) for share in shares: # Create png for each share img = pyqrcode.create(share) if format == 'png': img.png(share[0] + '.png', scale=scale) elif format == 'svg': img.svg(share[0] + '.svg', scale=scale) elif format == 'terminal': print(img.terminal())
def split_secret(key): s = "".join([ random.choice(string.ascii_letters + string.digits) for i in range(20) ]) split_s = PlaintextToHexSecretSharer.split_secret(s, 51, 100) h = SHA256.new(s.encode("utf-8")).digest() IV = h[0:16] ekey = h[16:32] mode = AES.MODE_CBC encryptor = AES.new(ekey, mode, IV=IV) ciphertext = encryptor.encrypt(text) binPrivKey = key.exportKey('DER') p_text = b64encode(binPrivKey).decode('utf-8') while len(p_text) % 16 != 0: p_text += ' ' ciphertext = encryptor.encrypt(p_text) return { "ciphertext": ciphertext, "splits": split_s, }
def encrypt_run(path): # aes加密 tmpkey = random.sample(string.ascii_letters + string.digits, 16) tmpoffset = random.sample(string.ascii_letters + string.digits, 16) key = ''.join(tmpkey) offset = ''.join(tmpoffset) # print(key,offset) name, suffix = os.path.splitext(path) pc = PrpCrypt(key, offset) with open(path, 'rb') as file_object: contents = file_object.read() e = pc.encrypt(contents) with open(name + '.copyright', 'wb') as file_object: file_object.write((suffix + '\n').encode()) file_object.write(e) # 分割 shares = PlaintextToHexSecretSharer.split_secret(key + offset, 3, 5) # sharesstr = ','.join(shares) # print('分割',sharesstr) encrypt_list = [] public_list = [ '0xc31656b66cf4e8d8584e35f7318d3e7cc2d7820768b7683b2057b714e383e2678108126f29ce42aa6a7010ef6d60581431972010ff517f571a21c8b74f42857c', '0x8a3d49ede094a68158d8f2be4d5eb816e9a20280f45ca7a3b5205fefc6475b8cc34014524fe78e71636bb26fdc47dc44da548538e43d0ea790a9fd0f5d558483', '0x1eba8ab60e0a7b99e0bdfb67ddbea8bb8b5a5d37e339b3210c2ce320e05d8000023bc6a8027de24b4cf80d1cc7ba28a71fcb6a06bb69ee4019d418f342c71f79', '0x0cb1b0db1af57669e8b5506daa7b5c873ab51165aef47836717ec6f439086fd118a07fafd35c1b75b4050fdf6d0bae911d10722f6dbe24dfe340a43fa6bf3cee', '0xdbe48fe7fa695231e6bdbb09ed6d9eb4431554c85f846223414890e2fdd1ab0f761b58039f5a2ea4a16d1c235d11a69ffd107533fae63139e1159c5c58c89081' ] for public, share in zip(public_list, shares): encrypt_list.append(b2a_hex(encrypt(public, share.encode())).decode()) # print(encrypt_list) encrypt_str = ','.join(encrypt_list) # print(encrypt_str) with open(name + '.key', 'wb') as f: f.write(encrypt_str.encode()) return (True, name)
def sharekey(key): n = -1 p = 0 while p > n: n = int(input("Number of members of the commission: ")) p = int(input("Number of people needed to recover the secret: ")) if p > n: print("Invalid input!") # every member of the commission is given a part of secret for every line of the key. # lines have to be reconstructed separately and put together to form the final key shares = [] i = 0 no_of_chars = [] for l in key: no_of_chars.append(len(l)) shares.append(PlaintextToHexSecretSharer.split_secret(l, p, n)) for j in range(n): name = "share" + str(j) + "_" + str(i) + ".txt" dir = "shares" + str(j) + "/" if not os.path.exists(dir): os.makedirs(dir) with open(dir + name, 'w') as f: f.write(shares[i][j]) i += 1 with open("lines.txt", 'w') as lines: lines.write(str(p) + "\n") lines.write(str(i) + "\n") for line in no_of_chars: lines.write(str(line) + "\n") print("Files share_i_j.txt are produced, " "where i is an ID " "and j is the number of line of the key they are used for." "Shares are stored in directories according to their IDs." "Give exactly one directory to every member of the commission.")
def create_test_scenario(): secret_low = secret.lower() secret_pieces = PlaintextToHexSecretSharer.split_secret(secret_low, k, n) # create encryption object based on shared secret aes_cipher = AESCipher(secret_low) beneficiaries = [] personal_keys = [] enc_messages = [] doub_enc_messages = [] for i in range(n): wallet_i = Wallet(addresses[i]) # creates a wallet with random address wallet_i.save() personal_keys.append(Fernet.generate_key()) cipher_suite = Fernet(personal_keys[i]) enc_messages.append(cipher_suite.encrypt(secret_messages[i])) doub_enc_messages.append(aes_cipher.encrypt(enc_messages[i])) message_url_i = store_file_in_ipfs(doub_enc_messages[i], message_files[i]) funds_share_i = share_of_funds[i] beneficiaries.append({ 'wallet_address': wallet_i.address, 'message_url': message_url_i, 'funds_share': funds_share_i, 'secret_piece_hash': sha256(secret_pieces[i]).hexdigest() }) user_contract = LegacyUserContract(k, n, t_PoL, init_balance, beneficiaries, owner, contract_name) user_contract.save(contract_name) contract_state = hash(user_contract) return contract_state, secret_pieces, enc_messages, doub_enc_messages, personal_keys, beneficiaries
def slice(data, min, max): return PlaintextToHexSecretSharer.split_secret(data, min, max)
class IndyProxyServer(web.Application): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.add_routes([ web.post('/create_identity', self._create_identity), web.post('/secret_sharding', self._secret_sharding), web.post('/secret_recovery', self._secret_recovery), ]) self._wallet_handle = None self._secret_sharer = PlaintextToHexSecretSharer() async def _create_identity(self, request): try: logging.debug('Creating identity wallet') await wallet.create_wallet(POOL_NAME, WALLET_NAME, None, None, None) logging.debug('Opening identity wallet') self._wallet_handle = await wallet.open_wallet( WALLET_NAME, None, None) logging.debug('Generating DID and Verkey') new_did, new_verkey = await did.create_and_store_my_did( self._wallet_handle, "{}") except IndyError as e: logging.error(f'Error while creating identity. Exception: {e}') return web.Response(status=500) response = { 'did': new_did, 'verkey': new_verkey, } return web.Response(body=json.dumps(response)) async def _secret_sharding(self, request): try: request_data = await request.json() verkey = request_data['verkey'] logging.debug('Getting signing key') signingkey = await did.get_signing_key(self._wallet_handle, verkey) shards = self._secret_sharer.split_secret(signingkey, 2, 3) except Exception as e: logging.error(f'Error while sharding secret. Exception: {e}') return web.Response(status=500) response = { 'shards': shards, } return web.Response(body=json.dumps(response)) async def _secret_recovery(self, request): try: request_data = await request.json() # shards = [shard.encode() for shard in request_data['shards']] shards = request_data['shards'] logging.debug('Recovering secret') secret = self._secret_sharer.recover_secret(shards) except Exception as e: logging.error(f'Error while recovering secret. Exception: {e}') return web.Response(status=500) response = { 'secret': secret, } return web.Response(body=json.dumps(response))
from secretsharing import PlaintextToHexSecretSharer shares = PlaintextToHexSecretSharer.split_secret("{'address':'Sainte Catherine' , 'telephone': 524-857-9127}", 2, 3) print('shares:', shares) print('Recover information from 1 and 2:' + PlaintextToHexSecretSharer.recover_secret(shares[0:2])) print('Recover information from 1 and 3:' + PlaintextToHexSecretSharer.recover_secret([shares[0],shares[2]])) print('Recover information from 2 and 3:' + PlaintextToHexSecretSharer.recover_secret(shares[1:3])) try: print('Recover of information from 2:' + PlaintextToHexSecretSharer.recover_secret(shares[1])) except: print('Not enough available information')
def vote(): os.system('clear') print("---- TEST POLL BOOTH ----") #Get voter ticket voter_ticket = raw_input("Enter ticket: ") #Check ticket is legit with open('tickets.csv', 'rb') as database: rows = csv.reader(database, delimiter=',') arows = [row for row in rows if voter_ticket in row] database.close() if len(arows) <= 0: print("!== Ticket does not exits ==!") exit(0) #Check the blockchain to make sure the ticket hasnt been used with open('BLOCKCHAIN1.CSV', 'rb') as bc: reader = csv.reader(bc, delimiter='\n') for row in reader: for data in row: if data.split(',')[0] == voter_ticket: print("!== Ticket has been used ==!") exit(0) #Dispkay polling options print("Select your option") choice = raw_input("A. ABC\nB. DEF\nC. GHI\n") if choice == 'A' or choice == 'a': voter_choice = 'ABC' elif choice == 'B' or choice == 'b': voter_choice = 'DEF' elif choice == 'C' or choice == 'c': voter_choice = 'GHI' else: print("Unknown choice!") exit(0) #Display conformation print("\n[*] Your Ticket:%s\n[*] Your vote:\t%s\n" % (voter_ticket, voter_choice)) confirm = raw_input("Confirm? y/n\n") if confirm == 'y' or confirm == 'Y': print "" #Vote must be encrypted, split and ticket marked as used #Encrypt vote print("-> Encrypting vote") random_key = os.urandom(32) cipher = AESCipher(random_key) encrypted_vote = cipher.encrypt(voter_choice) #Save encryption key f = open("privKey.txt", "w") f.write(base64.b64encode(random_key)) f.close() print("-> Key saved locally as privKey.txt") #Create 3 secret shares print("-> Creating shares") #Split into 3 votes that only require 2 to be used secretshares = PlaintextToHexSecretSharer.split_secret( encrypted_vote, 2, 3) #Add used ticket plus share 1 to blockchain print("-> Submitting share 1 to BLOCKCHAIN") with open("BLOCKCHAIN1.csv", 'a') as fp: wr = csv.writer(fp, lineterminator='\n') tmp = [] tmp.append(voter_ticket) tmp.append(secretshares[0]) wr.writerow(tmp) #Add share 2 to government print("-> Submitting share 2 to Government") with open("gov.csv", 'a') as fp: wr = csv.writer(fp, lineterminator='\n') tmp = [] tmp.append(voter_ticket) tmp.append(secretshares[1]) wr.writerow(tmp) #Save share 3 locally f = open("myshare.txt", 'w') f.write(secretshares[2]) f.close() print("-> Saved share 3 locally as myshare.txt") #Mark ticket as used in ticket database f = fileinput.input(files=('tickets.csv')) for line in f: with open('tickets_tmp.csv', 'a') as f: f.write(line.replace(voter_ticket + ",0", voter_ticket + ",1")) os.remove('tickets.csv') os.rename("tickets_tmp.csv", "tickets.csv") receipt_gen(secretshares[2], base64.b64encode(random_key), voter_ticket) #Print receipt print("\n\n==========POLL RECEIPT==========\n") print("[*] Your share: %s" % secretshares[2]) print("[*] Your key: %s" % base64.b64encode(random_key)) print("[*] Your ticket: %s" % voter_ticket) print("\n================================") else: print("!== No confomation ==!") exit(0)
#https://github.com/blockstack/secret-sharing #Note:In production, we'd use SecretSharer, not PlaintextToHexSecretSharer. This is for readability. from secretsharing import PlaintextToHexSecretSharer #Split the hash into 3 pieces SplitHash = PlaintextToHexSecretSharer.split_secret( "This is your encrypted private key (that you encrypted with biometric data)", 2, 3) #Recovery PlaintextToHexSecretSharer.recover_secret(shares[0:2])
from Crypto.Cipher import AES from Crypto.PublicKey import RSA from Crypto.Random.random import * from Crypto import Random import string import sys from secretsharing import PlaintextToHexSecretSharer as SS key=''.join(choice(string.ascii_letters) for x in range(16)) iv=Random.new().read(AES.block_size) cipher=AES.new(key,AES.MODE_CFB,iv) plaintext=open(sys.argv[1],'rb').read() msg = iv+cipher.encrypt(plaintext) open(sys.argv[1]+'.enc','w').write(msg) shares = SS.split_secret(key, 3, 5) for i in range(len(shares)): key=RSA.importKey(open('key-'+str(i)+'.pem','r').read()) cipher=key.encrypt(shares[i],0)[0].encode('base64') open('ciphertext-' + str(i) + '.bin', 'w').write(cipher)
requests.get(url) return kp def extract_share_from_tx(tx): return base64.b64decode( tx['_embedded']['records'][0]['signatures'][0]).decode() PRIZE = '100' PAWN = '100' COUNTERPRIZE = '1' DELTA = 60 # seconds x = 'Hello, World!' # Carol's message x_a, x_b = PlaintextToHexSecretSharer.split_secret(x, 2, 2) hash_x_a = hashlib.sha256(x_a.encode()).digest() hash_x_b = hashlib.sha256(x_b.encode()).digest() horizon = horizon_testnet() print('Initializing keypairs') kp_alice = initialize_keypair() kp_bob = initialize_keypair() kp_carol = initialize_keypair() print('Carol creates accounts a_1 and a_2') kp_a_1 = initialize_keypair(add_funds=False) kp_a_2 = initialize_keypair(add_funds=False) kp_a_1_address = kp_a_1.address().decode() kp_a_2_address = kp_a_2.address().decode()
# pip install secretsharing # https://github.com/blockstack/secret-sharing from secretsharing import PlaintextToHexSecretSharer as SS with open('message1.txt', 'r') as f: PLAINTEXTS = [f.read()] * 5 for i in range(2, 6): with open('message' + str(i) + '.txt', 'r') as f: msg = f.read() shares = SS.split_secret(msg, i, 5) for j in range(5): PLAINTEXTS[j] += shares[j] + '\n' for j in range(5): with open('plaintext-' + str(j+1) + '.txt', 'w') as f: f.write(PLAINTEXTS[j])
def splitSecret(secret, threshold, splits): shares = PlaintextToHexSecretSharer.split_secret(secret, threshold, splits) return shares
if p > n: print("Invalid input!") with open("private_key.pem", 'r') as f: key = f.readlines() # every member of the commission is given a part of secret for every line of the key. # lines have to be reconstructed separately and put together to form the final key shares = [] i = 0 no_of_chars = [] for l in key: no_of_chars.append(len(l)) if i == 19: print(l) shares.append(PlaintextToHexSecretSharer.split_secret(l, p, n)) #print(shares[i]) for j in range(n): name = "share" + str(j) + "_" + str(i) + ".txt" dir = "shares" + str(j) + "/" if not os.path.exists(dir): os.makedirs(dir) with open(dir + name, 'w') as f: f.write(shares[i][j]) i += 1 with open("lines.txt", 'w') as lines: lines.write(str(p) + "\n") lines.write(str(i) + "\n") for line in no_of_chars: lines.write(str(line) + "\n")
def main(): # Select number of shares questions = [ inquirer.List( 'parties', message='How many shares do you want?', choices=['2', '3', '4', 'other'], ), ] answer = inquirer.prompt(questions) if answer['parties'] == 'other': parties = int(raw_input('Type a number: ')) while parties < 2: parties = int(raw_input('Type a number greater than 1: ')) else: parties = int(answer['parties']) # Select revealing threshold if parties > 2: min_threshold = 2 max_threshold = parties thresholds = [x for x in range(min_threshold, max_threshold + 1)] questions = [ inquirer.List( 'threshold', message= 'How many shares should be enough for decryption? (Most secure: ' + str(max_threshold) + ')', choices=thresholds, ), ] answer = inquirer.prompt(questions) threshold = int(answer['threshold']) else: threshold = parties # Select type of shares output questions = [ inquirer.List( 'format', message='Select the format of output images', choices=['png', 'svg', 'terminal'], ), ] format = inquirer.prompt(questions)['format'] # Select size of shares output if format != 'terminal': questions = [ inquirer.List( 'scale', message='Size of output images', choices=['Small', 'Medium', 'Large'], ), ] answers = inquirer.prompt(questions) if answers['scale'] == 'Small': scale = 2 elif answers['scale'] == 'Medium': scale = 4 elif answers['scale'] == 'Large': scale = 8 secret = raw_input('Enter your message: ') wait = animation.Wait('spinner', 'Generating randomness.. It may take a while.. ') wait.start() # Secret-share the message using Shamir's secret sharing scheme. shares = PlaintextToHexSecretSharer.split_secret(secret, threshold, parties) wait.stop() print(shares) for share in shares: # Create png for each share img = pyqrcode.create(share) if format == 'png': img.png(share[0] + '.png', scale=scale) elif format == 'svg': img.svg(share[0] + '.svg', scale=scale) elif format == 'terminal': print(img.terminal())
finished_input = raw_input("Not a valid answer. Try again\n") finished = True if finished_input == 'yes' else False i = i + 1 print "\n### Step 2: The Shared Key" n = i # number of beneficiaries secret = raw_input( "Now, enter a random phrase that will be used to create your secret password (eg. 'I love cats').\n" ) secret = secret.lower() print "Your secret will be shared among " + str( n) + " persons. How many of them will be required to restore it?\n" k = int( raw_input("Please enter an integer k such that 2 <= k < " + str(n) + "\n")) secret_pieces = PlaintextToHexSecretSharer.split_secret(secret, k, n) # create encryption object based on shared secret aes_cipher = AESCipher(secret) beneficiaries = [] for i in range(0, n): # now that we have the shared secret, apply an additional encryption layer doub_enc_message_i = aes_cipher.encrypt( beneficiaries_tmp[i]['enc_message']) message_url_i = store_file_in_ipfs(doub_enc_message_i) address_i = beneficiaries_tmp[i]['wallet_address'] funds_share_i = beneficiaries_tmp[i]['funds_share'] # save the beneficiary dict in array (note that we don't store sensible data) beneficiaries.append({ 'wallet_address':
def shamirs_split(file_object): text = file_object.read() list = PlaintextToHexSecretSharer.split_secret(text, 2, 2) hexcode = SecretSharer.split_secret(list[0][2:], 2, 2) return hexcode, list[1]
# pip install secretsharing # https://github.com/blockstack/secret-sharing from secretsharing import PlaintextToHexSecretSharer as SS with open('message1.txt', 'r') as f: PLAINTEXTS = [f.read()] * 5 for i in range(2, 6): with open('message' + str(i) + '.txt', 'r') as f: msg = f.read() shares = SS.split_secret(msg, i, 5) for j in range(5): PLAINTEXTS[j] += shares[j] + '\n' for j in range(5): with open('plaintext-' + str(j + 1) + '.txt', 'w') as f: f.write(PLAINTEXTS[j])