Example #1
0
 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()
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 recoverSecret(shares):
    for i in range(len(shares)):
        shares[i] = (base64.b64decode(shares[i])).decode('utf-8')
    secret = PlaintextToHexSecretSharer.recover_secret(shares)
    #Converting recovered_key to bytes using base64 module
    secret = base64.b64decode(secret)
    return secret
Example #4
0
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
Example #5
0
def unsecret_num(num, secret_message):
    shares = []
    for i in range(len(secret_message)):
        sf = secret_message[i].split(
            "\n")  #each share is delineated by a newline character
        shares.append(
            sf[num])  #get share from file contents and add to share array
    return SS.recover_secret(shares).strip()
Example #6
0
def check_votes(myshare_file, blockchainshare_file, voter_ticket, keyfile):

    os.system("clear")
    print("----Vote count & check----")
    #Check ticket exits and has been used
    with open('tickets.csv', 'rb') as f:
        rows = csv.reader(f, delimiter=',')
        arows = []
        for x in rows:
            if voter_ticket in x:
                arows.append(x)
        #arows = [row for row in rows if voter_ticket in row]
        f.close()
    if len(arows) <= 0:
        print("Ticket does not exist")
        exit(0)
    for data in arows:
        if data[1] == '0':
            print("Ticket valid BUT not used")
            exit(0)

    #Count total votes in blockchain
    with open(blockchainshare_file, 'r') as f:
        reader = csv.reader(f, delimiter=',')
        data = list(reader)
        row_count = len(data)

    print("-> %s total vote(s) in blockchain" % row_count)

    #read local share
    print("-> Local share")
    with open(myshare_file, 'r') as f:
        myshare = f.read()
    print("[*] %s" % myshare)

    #Grab the share corresponding to voters ticket from within blockchain
    print("-> Getting share from blockchain")
    with open(blockchainshare_file, 'rb') as f:
        reader = csv.reader(f, delimiter='\n')
        for row in reader:
            for data in row:
                if data.split(',')[0] == voter_ticket:
                    blockchain_share = data.split(',')[1]
                    print("\t-> %s" % blockchain_share)

    #connect shares
    print("-> Reassembling shares")
    tmp = [myshare, blockchain_share]
    recovered_vote = PlaintextToHexSecretSharer.recover_secret(tmp)

    #decrypt shares
    print("-> Decrypting shares")
    with open(keyfile, 'r') as f:
        key = f.read()
    f.close()
    cipher = AESCipher(base64.b64decode(key))
    decrypted_vote = cipher.decrypt(recovered_vote)
    print("[*] Your vote was: %s" % decrypted_vote)
Example #7
0
        def Combine(shares: list):
            """Combine a list of shares to form a secret if the minimum number required is supplied.
			Args:
				shares(list): List of shares.
			Returns:
				str: secret
			"""
            secret = PlaintextToHexSecretSharer().recover_secret(shares)
            return secret
Example #8
0
def decrypt_secret(splits, ciphertext):
    s = PlaintextToHexSecretSharer.recover_secret(splits)
    h = SHA256.new(s.encode("utf-8")).digest()
    IV = h[0:16]
    ekey = h[16:32]
    mode = AES.MODE_CBC
    decryptor = AES.new(ekey, mode, IV=IV)
    dpk = decryptor.decrypt(ciphertext)
    dpk = dpk.decode("utf-8").replace(' ', '')
    key = RSA.importKey(b64decode(dpk))
Example #9
0
def recover(args):
    min = args.min
    keyfile = args.keyfile

    parts = []
    for line in open(keyfile):
        parts.append(line.rstrip('\n'))

    result = PlaintextToHexSecretSharer.recover_secret(parts[0:min])
    print("The full private key is: " + result.rstrip('\n'))
Example #10
0
def combine_and_decrypt(data, subkeys):
    """
    Decrypt the data by recreating the original key with threshold number
    of subkeys.

    Return the decrypted data.
    """
    key = shamir.recover_secret(subkeys)
    decrypted_data = decrypt(data, key.encode())

    return decrypted_data
Example #11
0
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)
Example #12
0
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)
Example #13
0
        def Split(secret: str, min_req: int, total_shares: int):
            """Split a secret into shares.
			Args:
				secret(str): Secret data representated as a string
				min_req(int): Minimum shares required to combine to form secret.
				total_shares(int): Total shares to split the secret into.
			Returns:
				list: shares
			"""
            if min_req >= total_shares:
                raise ValueError(
                    'Total shares must be more than minimum required.')
            shares = PlaintextToHexSecretSharer().split_secret(
                secret, min_req, total_shares)
            return shares
Example #14
0
def main():

    # Enter shares
    shares = [input('Enter your share: ')]
    while True:
        numofSHares = input("Still have more?\tYes\tNo\n").upper()
        if numofSHares == "Y":
            shares.append(input('Enter your share: '))
        elif numofSHares == "N":
            break
        else:
            print("You haven't answered correctly, try again\n")

    # Recover
    message = PlaintextToHexSecretSharer.recover_secret(shares)
    print('Original message:\n' + message)
Example #15
0
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())
Example #16
0
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,
    }
Example #17
0
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)
Example #18
0
def main():
    # Enter shares
    shares = [raw_input('Enter your share: ')]
    while True:
        questions = [
            inquirer.List(
                'share',
                message='Enter next share',
                choices=['OK', 'I don\'t have another one'],
            ),
        ]
        answer = inquirer.prompt(questions)['share']
        if answer != 'OK':
            break
        shares.append(raw_input('Enter your share: '))

    # Recover
    wait = animation.Wait('spinner',
                          'Generating randomness.. It may take a while.. ')
    wait.start()
    message = PlaintextToHexSecretSharer.recover_secret(shares)
    wait.stop()
    print('Original message:\n' + message)
Example #19
0
def dry_run():
    final_votes = []
    os.system("clear")
    print("----Counting Votes (gov)----")

    with open("BLOCKCHAIN1.csv", 'rb') as f:
        reader = csv.reader(f, delimiter='\n')
        for row in reader:
            for data in row:
                current_ticket = data.split(',')[0]
                with open('gov.csv') as g:
                    readerg = csv.reader(g, delimiter='\n')
                    for rowg in readerg:
                        for datag in rowg:
                            gov_ticket = data.split(',')[0]
                            if current_ticket == gov_ticket:
                                bs_share = data.split(',')[1]
                                gov_share = datag.split(',')[1]
                                voter_key = data.split(',')[2]
                                print("-> Ticket: %s" % current_ticket)
                                print("\tKey: %s" % voter_key)
                                print(
                                    "\n\tShares:\n\t\tBlockchain: %s\n\t\tGov: %s"
                                    % (bs_share, gov_share))

                                tmp = [bs_share, gov_share]
                                recovered_vote = PlaintextToHexSecretSharer.recover_secret(
                                    tmp)
                                cipher = AESCipher(base64.b64decode(voter_key))
                                decrypted_vote = cipher.decrypt(recovered_vote)
                                print("\tDecrypted Vote: %s" % decrypted_vote)
                                final_votes.append(decrypted_vote)

    print("\n-> Final vote counting")
    counts = Counter(final_votes)
    for key, value in counts.iteritems():
        print("%s votes for |%s|" % (value, key))
Example #20
0
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.")
Example #21
0
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
Example #22
0
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]
Example #23
0
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.PublicKey import RSA
from base64 import b64decode
import encrypt
from secretsharing import PlaintextToHexSecretSharer as SS

values = [0, 4, 3, 6]
plains = [[], [], [], []]
for i in values:
    with open("pkey-%d.pem" % i) as f:
        data = f.read()
    data = data.splitlines()
    data = data[1:-1]
    data = ''.join(data)

    keyDER = b64decode(data)
    keyPriv = RSA.importKey(keyDER)

    for j in xrange(1, 6):
        with open("ciphertext-%d.bin" % j, 'rb') as f:
            data = f.read()
        data = encrypt.decrypt(keyPriv, data)
        if data is not None:
            values = data.splitlines()[1:]
            for i, v in enumerate(values):
                plains[i].append(v)
for v in plains:
    print(SS.recover_secret(v))
Example #24
0
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())
# 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])

Example #26
0
shares = []
for secretCollection in plaintexts:
    secrets = secretCollection.splitlines()[1:]
    for secret in secrets:
        shares.append(secret)

for i in shares:
    for j in shares:
        if(j==i):
            continue
        for k in shares:
            if(k==i or k==j):
                continue
            try:
                flag = PlaintextToHexSecretSharer.recover_secret([i,j,k])
                if('flag' in flag.lower()):
                    print(flag)
            except:
                pass
            for l in shares:
                if(l==i or l==j or l == k):
                    continue
                for m in shares:
                    if(m==i or m==j or m == k or m==l):
                        continue
                try:
                    flag = PlaintextToHexSecretSharer.recover_secret([i,j,k,l,m])
                    if('flag' in flag.lower()):
                        if('ndQzjRpnSP60NgWET6jX' not in flag):
                            print(flag)
 def recover_shared_secret(self):
     # TODO: manage exceptions
     if len(self.collected_secrets) >= self.k:
         self.secret = PlaintextToHexSecretSharer.recover_secret(
             self.collected_secrets)
Example #28
0
            # check if the equation x^2 - s*x + n = 0
            # has integer roots
            discr = s*s - 4*n
            if(discr>=0):
                t = Arithmetic.is_perfect_square(discr)
                if t!=-1 and (s+t)%2==0:
                    return d

for i in range(10):
    if keys[i] is None:
        k = load_key(i)
        x = wiener(k.e, k.n)
        if x is not None:
            impl = RSA.RSAImplementation(use_fast_math=False)
            partial = impl.construct((k.n, 0L))
            partial.key.e = k.e
            partial.key.d = x
            keys[i] = partial
            try_decrypt(keys[i])

# Found with factorization outside the script
plaintexts[0] = """Congratulations, you decrypted a ciphertext!  One down, two to go :)
1-32a1cd9f414f14cff6685879444acbe41e5dba6574a072cace6e8d0eb338ad64910897369b7589e6a408c861c8e708f60fbbbe91953d4a73bcf1df11e1ecaa2885bed1e5a772bfed42d776a9
1-e0c113fa1ebea9318dd413bf28308707fd660a5d1417fbc7da72416c8baaa5bf628f11c660dcee518134353e6ff8d37c
1-1b8b6c4e3145a96b1b0031f63521c8df58713c4d6d737039b0f1c0750e16e1579340cfc5dadef4e96d6b95ecf89f52b8136ae657c9c32e96bf4384e18bd8190546ff5102cd006be5e1580053
1-c332b8b93a914532a2dab045ea52b86d4d3950a990b5fc5e041dce9be1fd3912f9978cad009320e18f4383ca71d9d79114c9816b5f950305a6dd19c9f458695d52"""

from secretsharing import PlaintextToHexSecretSharer as SS

print SS.recover_secret(x.split('\n')[2] for x in plaintexts if x is not None)
Example #29
0
from secretsharing import PlaintextToHexSecretSharer 
done = False
parts = []
while not done:
	inVar = raw_input("Enter a part to restore: ")
	parts.append(inVar)
	inVar = raw_input("Done? (y/n): ")
	if(inVar.lower() == "y"):
		done = True



print PlaintextToHexSecretSharer.recover_secret(parts)
Example #30
0
def splitSecret(secret, threshold, splits):
    shares = PlaintextToHexSecretSharer.split_secret(secret, threshold, splits)
    return shares
Example #31
0
def recoverSecret(shares):
    secret = PlaintextToHexSecretSharer.recover_secret(shares)
    return secret
Example #32
0


w = RSAExploits.Wiener()
#we know to run it only on key-3.pem because the public exponent in that key is very large
w.run([y[3]])

n3 = n[3]
p3 = y[3].get_p()
q3 = y[3].get_q()
e3 = b[3].key.e
assert p3 * q3 == n3

tot3 = n3 - (p3 + q3 - 1)
d3 = modinv(e3, tot3)
privkey3 = RSA.construct((n3, e3, d3))
for c in cts:
    temp = decrypt(privkey3, c)
    if(temp):
        plaintexts.append(temp)
        break
#cut off the congratulations messages and break up each line
pt1 = plaintexts[0].strip().split("\n")[1:]
pt2 = plaintexts[1].strip().split("\n")[1:]
pt3 = plaintexts[2].strip().split("\n")[1:]

#zip them together and recover the secret.
#zipped so we can combine pt1[n] pt2[n] and pt3[n] easily 
for i in zip(pt1, pt2, pt3):
    print(PlaintextToHexSecretSharer.recover_secret(i))
# 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])
Example #34
0
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)
Example #35
0
y.append(m.split('\n')[2])
z.append(m.split('\n')[3])
print m
"""
Congratulations, you decrypted a ciphertext!  One down, two to go :)
3-17e568ddc3ed3e6fe330ca47a2b27a2707edd0e0839df59fe9114fe6c08c6fc1ac1c3c8d9ab3cf7860dac103dff464d4c215e197b54f0cb46993912c3d0220a3eb1b80adf33ee2cc59b0372c
3-b69efb4f9c5205175a4c9afb9d3c7bef728d9fb6c9cc1241411b31d4bd18744660391a330cefa8a86af8d2b80c881cfa
3-572e70c5acfbe8b4c2cbd47217477d217da88c256ff2586af6a18391972c258bbea6143e7cd2ff6d39393efeb64d51d9318a2c337e50e2d764a42173bc3a1d5c7c8f24b64043daf5d2a8e9f4
3-e9e6850880eb0a44d36fe9f2e5a458c6da3977b7fcd285afa27e9bfc116b1408570991504116b81864b03a7060bfd5d3fb6e007bb346f276d749befd545d1489c4
"""

# key-1.pem, ciphertext-5.bin
(p, q) = fermat(n[1])
m = decrypt(p, q, c[4])
x.append(m.split('\n')[1])
y.append(m.split('\n')[2])
z.append(m.split('\n')[3])
print m
"""
Congratulations, you decrypted a ciphertext!  One down, two to go :)
5-7d29041c468b680fcff93c16011a2869f17de75b929b787503b412becde0321ec72fe1e499f2150a1dacb9a5f701c0b37470049dd560cef5163543469817971f50782f763f0b05ab7088f7ae
5-a7a1e271cf263279cece532b540545fa539b0f3650e2929163b02ee5459debdc53c1e07149eb2153015bb5c88e6270e8
5-149480c5c75cbe320564adfa432ac8ea241e048ed39c8bc6be14ca80c392487f43a7882075d785d62cb314ea6c89a6b5f28adfa56ec481e124567b88241de2a6cabcc7ec9de3acac8be5375b
5-7285289084282d559573f68eef10191091d76d6670014202670651f867cd2bc8640a86eef1c1e482affc7ae801fa446956c2186972fb6b7bac88c91d050c9d3cca
"""

print SS.recover_secret(x)
print SS.recover_secret(y)
print SS.recover_secret(z)
# FLAG{ndQzjRpnSP60NgWET6jX}
Example #36
0
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))