def _unlock(self, current_sss_tree, key_slot_unlock_data): if "key_slot_id" in current_sss_tree: key_slot_id = current_sss_tree["key_slot_id"] key_slot = self.data["key_slots"][key_slot_id] auth_module = AUTH_TYPE_MAP[key_slot["auth_type"]] cur_key_slot_unlock_data = key_slot_unlock_data[key_slot_id] if cur_key_slot_unlock_data is None: return None return auth_module.unlock_key_slot(key_slot, cur_key_slot_unlock_data) unlocked_nonces = [] for child in current_sss_tree["children"]: child_nonce = self._unlock(child, key_slot_unlock_data) if child_nonce is not None: unlocked_nonces.append(child_nonce) if len(unlocked_nonces ) == current_sss_tree["required_auth_count"]: break else: # We don't have enough info to unlock this tree :( return None return SecretSharer.recover_secret(unlocked_nonces)
def decrypt_secret(fragments): total_fragment = str(fragments[0]).count('^') + 1 data = [[] for _ in range(total_fragment)] for line in fragments: temp = str(line).split('^') for i in range(total_fragment): data[i].append(temp[i]) key = "" for i in range(total_fragment): tmp = SecretSharer.recover_secret(data[i]) expected_length = 10 if (i == total_fragment - 1): expected_length = 4 tmp = "0" * (expected_length - len(tmp)) + tmp key += tmp return str(key)
def shamirs_join(list, str): temp = [] msg_alpha = SecretSharer.recover_secret(list[0:2]) msg_alpha = '1-' + msg_alpha temp.append(msg_alpha) temp.append(str) text = PlaintextToHexSecretSharer.recover_secret(temp[0:2]) return text
def parser(u1, a, b): k = [] for i in range(len(u1)): shares = Shamir.split_secret(u1[i], a, b) tmp = [] for i in shares: tmp.append(int(i[2:], 16)) k.append(tmp) k = np.transpose(np.array(k)).tolist() return k
def recover(s): db = [] for i in range(np.shape(s)[1]): for j in range(np.shape(s)[2]): tmp1 = [] for k in range(np.shape(s)[0]): tmp1.append(str(k + 1) + "-" + str(hex(s[k][i][j]))[2:-1]) answer = Shamir.recover_secret(tmp1) if len(answer) % 2 == 1: answer = '0' + answer db.append(answer.decode('hex')) return db
def _re_key(self, target_nonce, current_sss_tree): if "key_slot_id" in current_sss_tree: key_slot = self.data["key_slots"][current_sss_tree["key_slot_id"]] auth_module = AUTH_TYPE_MAP[key_slot["auth_type"]] auth_module.lock_key_slot(key_slot, target_nonce) else: sss_keys = SecretSharer.split_secret( target_nonce, current_sss_tree["required_auth_count"], len(current_sss_tree["children"]), ) for new_target, child in zip(sss_keys, current_sss_tree["children"]): self._re_key(new_target, child)
def process_image(filename,k,n,users,sender_id): # AES Key key = Random.new().read(32) hexkey = key.encode('hex') # Encrypting Image and Deleting the file aes.encrypt_file(key,filename) os.remove(filename) # Splitting AES Key into N parts shares = SecretSharer.split_secret(hexkey,k,n) # Creating a New Message msg_id = database.new_message(filename + '.enc', k, sender_id) users.insert(0,sender_id) # Updating message queue database.update_message_queue(users,shares,msg_id)
def Recover(): lines = read_in() lines = json.dumps(lines) # remove [u'] # print "Recover input:", lines, ",type ", type(lines) lines = lines.replace("[", "").replace( "]", "").replace('"', "") # remove [,",] lines = lines.split(", ") # divide by comma, # print "lines[0]: ", lines[0] # print "lines[1]: ", lines[1] # print "len(lines) : ", len(lines) f = file("./pk.pem", "r") line = f.readline() line = line.replace("<PublicKey:", "").replace(">", "") pub = PublicKey(int(line)) g = file("./sk.pem", "r") line = g.readline() line = line.replace("<PrivateKey:", "").replace(">", "") priv = PrivateKey(int(line.split()[0]), int(line.split()[1])) cipher = [] for item in range(0, len(lines)): cipher = lines[item].split(" ") c1 = cipher[0] c2 = cipher[1] c3 = cipher[2] decrypt_tmp1 = decrypt(priv, pub, int(c1)) decrypt_tmp1 = str(decrypt_tmp1).decode('hex') decrypt_tmp2 = decrypt(priv, pub, int(c2)) decrypt_tmp2 = str(decrypt_tmp2).decode('hex') decrypt_tmp3 = decrypt(priv, pub, int(c3)) decrypt_tmp3 = str(decrypt_tmp3).decode('hex') # print decrypt_tmp1, decrypt_tmp2, decrypt_tmp3, shares = ["" for x in range(3)] shares[0] = '1-' + str(decrypt_tmp1) shares[1] = '2-' + str(decrypt_tmp2) shares[2] = '3-' + str(decrypt_tmp3) RecoverShare = SecretSharer.recover_secret(shares[0:3]) print RecoverShare
def secret_sharing(): lines = read_in() lamb = int(lines) #lamb = 5 vote = str(lamb) voteMsg = 'bce' + str(vote) shares = SecretSharer.split_secret(voteMsg, 2, 3) #priv, pub = generate_keypair(512) # read pk.pem and sk.pem f = file("./pk.pem", "r") line = f.readline() line = line.replace("<PublicKey:", "").replace(">", "") pub = PublicKey(int(line)) array = [] g = file("./sk.pem", "r") line = g.readline() line = line.replace("<PrivateKey:", "").replace(">", "") priv = PrivateKey(int(line.split()[0]), int(line.split()[1])) # print "Original secret of vote:" # for item in range(0, 3): # print shares[item] # shares = SecretSharer.split_secret( #"c4bbcb1fbec99d65bf59d85c8cb62ee2db963f0fe106f483d9afa73bd4e39a8a", 2, 3) #['1-58cbd30524507e7a198bdfeb69c8d87fd7d2c10e8d5408851404f7d258cbcea7', '2-ecdbdaea89d75f8e73bde77a46db821cd40f430d39a11c864e5a4868dcb403ed', #'3-80ebe2cfef5e40a2cdefef0923ee2bb9d04bc50be5ee308788af98ff609c380a'] sh3 = ["" for x in range(3)] # print "-------------------------encrypt # loop-----------------------------------------" for index in range(0, 3): tmpCoordinate = shares[index][2:].encode('hex') crypt_tmpCoordinate = encrypt(pub, int(tmpCoordinate)) sh3[index] = crypt_tmpCoordinate if index == 2: print str(crypt_tmpCoordinate) + "$", else: print str(crypt_tmpCoordinate),
def send_decrpyted_image(filename,shares,k): hexkey = SecretSharer.recover_secret(shares[0:k]) key = hexkey.decode('hex') aes.decrypt_file(key,filename)
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]
import timeit from secretsharing import SecretSharer data = "baf011876aec65950556a5b3048b4d0e0e57008508270629f0d0e91aac916187561c9e94cb2b118633bd1c8174ac10d1dba342ee31f91fa4f83e398f25581448" n = 2 m = 3 wr = open("resutl.csv", 'w') while m < 8000: start = timeit.default_timer() secret = SecretSharer.split_secret(data, n, m) stop = timeit.default_timer() print(str(n) + " of " + str(m)) print(str(stop - start) + " seconds") wr.write(str(n) + ";" + str(m) + ";" + str(stop - start) + '\n') n += 1 m += 2
#!/usr/bin/env python2 from __future__ import print_function import binascii from secretsharing import SecretSharer SECRETS = [ '1-9608474170977308238036624146101441469538628637045706610338073590812843162969037926492967854559828114435865261425719619743472419864336210874222029453059741', '3-224183841656780872927678242626279871433733831057475254917387185998520511272846647279913467443558309288829498488402883425874249712684215384203475752039681175', '4-524164732834933988556388319839274528391312080836319720002737667326861328789556912063222725295339950383555529443266354316704089242529615243887408038702736241', '5-1015950427545472565825761297620151258974491880324557727968398393745824130327315926142371765654543965113857776728721730398986530543452098367721676829359089545', ] hex_secrets = [] for secret in SECRETS: idx, num = secret.split('-') hex_num = hex(int(num))[2:].rstrip('L') hex_secrets.append(idx + '-' + hex_num) print(hex_secrets) s = SecretSharer.recover_secret(hex_secrets) print(s) print(binascii.unhexlify(s))
def recover(shares): #shares:List return SecretSharer.recover_secret(shares)
def getSharingKey(key, n, k): return SecretSharer.split_secret(key, k, n)
def recoverKey(cls, shares): return SecretSharer.recover_secret(shares)
def shareKey(cls, key, agreement_nbr, total_nbr): shares = SecretSharer.split_secret(key, agreement_nbr, total_nbr) return shares
def recoverSharingKey(shares): return makeKeyFromAscii(SecretSharer.recover_secret(shares))
passwords = list(set(open(potfile, "r").read().splitlines())) current_level = json.load(open(inferno_ball)) level_hashes = current_level["hashes"] level_ciphertext = current_level["ciphertext"] level_shares = current_level["shares"] shares = [] for password in passwords: password = password.rstrip() index = level_hashes.index(password.split(":", 1)[0]) share = level_shares[index] xored = pxor(password.split(":", 1)[1], share) shares.append(str(xored)) secret = SecretSharer.recover_secret(shares) decrypted = decrypt(level_ciphertext, secret.zfill(32).decode('hex')) try: decrypted = json.loads(decrypted) print("Level-up success! SECRET: %s" % secret) decrypted["ciphertext"] = str(decrypted["ciphertext"]) decrypted["hashes"] = [str(s) for s in decrypted["hashes"]] decrypted["shares"] = [str(s) for s in decrypted["shares"]] decrypted["easteregg"] = str(decrypted["easteregg"]) print("Next level's easter-egg: %s" % decrypted["easteregg"]) output_hashes = open(output_path + ".hashes", "w") output_json = open(output_path + ".json", "w") for h in decrypted["hashes"]: output_hashes.write(h + "\n") json.dump(decrypted, output_json)
# print BitcoinToB32SecretSharer.recover_secret(shares[0:7]) s = [] for x in shares: x = x.lower() s.append(x) p = s[0] a1 = s[0:3] a2 = s[4:7] a2.append(p) print '所有密钥值:'.decode('utf-8') for x in s:print x print '' print '组织1 解密文本:'.decode('utf-8') key1 = SecretSharer.recover_secret(a1) print key1 print '' print '组织2 解密文本:'.decode('utf-8') s.append(s[0]) key2 = SecretSharer.recover_secret(a2) print key2 print '' print 'key1:' print key1.encode('hex') print 'key2:' print key2.encode('hex') print '' ss = [] ss.append(shares[0].lower())
def getInformation(self, input_folder): images = [] for files in os.listdir(input_folder): if files.endswith('.png'): images.append(os.path.join(input_folder, files)) self.encrypto_progress.setValue(30) kkey, dataList, ivValueList, structLenList, hmacList, checksum = findInformation(images) self.encrypto_progress.setValue(40) removeList = [] for n, elem in enumerate(checksum): temp = hashlib.sha256(kkey[n].encode() + dataList[n] + hmacList[n]).digest() # print(n, elem, temp) if elem == temp: print("%d CheckSum Assertion Success" % n) else: print("%d CheckSum Assertion Failed" % n) removeList.append(n) removeList.reverse() for i in removeList: del kkey[i] del dataList[i] del ivValueList[i] del structLenList[i] del hmacList[i] del checksum[i] recoverdKey = SecretSharer.recover_secret(kkey) self.encrypto_progress.setValue(50) if len(recoverdKey) % 64 != 0: length = 64 - (len(recoverdKey) % 64) recoverdKey = '0' * length + recoverdKey recoverdKey = makeKeyFromAscii(recoverdKey) self.encrypto_progress.setValue(60) for i in range(0, len(dataList)): recvFileName = 'recovered_output' + str(i) + '.txt' forHmacTest = recoverdKey + dataList[i] hashed = hashlib.sha256(forHmacTest).digest() if hmacList[i] == hashed: print("%d Assertion Success" % i) else: print("%d Assertion Failed" % i) self.encrypto_progress.setValue(80) decrypt_file(recoverdKey, ivValueList[i], dataList[i], structLenList[i], out_filename=recvFileName) self.encrypto_progress.setValue(90)