Ejemplo n.º 1
0
def test_encode(p, q_set):
    for __ in range(100):
        _, public_key = generate_keys(p=p, q_set=q_set)
        x = get_coprime_integer(public_key.p)
        message = random.randint(1, 1000)
        bx = pow(public_key.b, x, public_key.p)
        b1 = public_key.p + bx
        assert (message*b1) % public_key.p == (message*bx) % public_key.p
Ejemplo n.º 2
0
 def generate_keypair(self):
     cs = self.cipher_suite
     scheme = cs.scheme
     if scheme == "Paillier":
         sk, pk = paillier.generate_keypair(cs.modulus_length)
         # print(pk.n)
     elif scheme == "ElGamal":
         sk, pk = elgamal.generate_keys(cs.modulus_length)
         # print(pk.p)
     return sk, pk
def main():
    with open("files/initial.txt", "r") as file:
        data = file.read()

        public_key, private_key = elgamal.generate_keys()
        print("\nPublic Key: {}\nPrivate Key: {}\n".format(
            public_key, private_key))

        encrypted_data = elgamal.encrypt(data, public_key)
        write_to_file("files/encrypted.txt", encrypted_data)
        print("\nencrypted data:\n{}".format(encrypted_data))

        decrypted_data = elgamal.decrypt(encrypted_data, private_key)
        write_to_file("files/decrypted.txt", decrypted_data)
        print("\ndecrypted data:\n{}".format(decrypted_data))
Ejemplo n.º 4
0
    def menu(cls):
        elGamalKeys = elgamal.generate_keys()

        key = RSA.generate(2048)

        public_key = key.publickey().export_key()
        file_out = open("receiver.pem", "wb")
        file_out.write(public_key)
        file_out.close()

        private_key = key.export_key()
        file_out = open("private.pem", "wb")
        file_out.write(private_key)
        file_out.close()

        print("-----------------------------------------------")
        print("--------CRYPTAGE DECRYPTAGE ASYMETRIQUE--------")
        print("-----------------------------------------------")

        while (True):
            print('\n')
            choice = pyip.inputMenu(['Crypter un message', 'Quitter'])
            if (choice == 'Crypter un message'):
                method = pyip.inputMenu(['RSA', 'ElGamal'])
                print(method)
                if (method == 'RSA'):
                    choice, signature = AsymmetricEncryption.encrypt(
                        public_key, elGamalKeys, key, method=method)
                else:
                    choice, cipher = AsymmetricEncryption.encrypt(
                        public_key, elGamalKeys, key, method=method)

                print('\nVoulez-vous decrypter votre message ?  ')
                decrypt = pyip.inputMenu(['oui', 'non'])
                if (decrypt == 'non'):
                    continue
                elif (method == 'RSA'):
                    AsymmetricEncryption.decrypt(key, elGamalKeys, method,
                                                 choice, signature)
                elif (method == 'ElGamal'):
                    AsymmetricEncryption.decrypt(key, elGamalKeys, method,
                                                 choice, cipher)

            else:
                return
    def menu(cls):
        elGamalKeys = elgamal.generate_keys()

        key = RSA.generate(2048)

        public_key = key.publickey().export_key()
        file_out = open("receiver.pem", "wb")
        file_out.write(public_key)
        file_out.close()

        private_key = key.export_key()
        file_out = open("private.pem", "wb")
        file_out.write(private_key)
        file_out.close()

        ascii_banner = pyfiglet.figlet_format("ASYMMETRIC ENCRYPTION")
        print(ascii_banner)

        while (True):
            print('\n')
            choice = pyip.inputMenu(['encryption', 'quit'])
            if (choice == 'encryption'):
                method = pyip.inputMenu(['RSA', 'ElGamal'])
                print(method)
                if (method == 'RSA'):
                    choice, signature = AsymmetricEncryption.encrypt(
                        public_key, elGamalKeys, key, method=method)
                else:
                    choice, cipher = AsymmetricEncryption.encrypt(
                        public_key, elGamalKeys, key, method=method)

                print('\nFor decryption : ')
                decrypt = pyip.inputMenu(['yes', 'no'])
                if (decrypt == 'no'):
                    continue
                elif (method == 'RSA'):
                    AsymmetricEncryption.decrypt(key, elGamalKeys, method,
                                                 choice, signature)
                elif (method == 'ElGamal'):
                    AsymmetricEncryption.decrypt(key, elGamalKeys, method,
                                                 choice, cipher)

            else:
                return
Ejemplo n.º 6
0
def create_genesis_block():
    cipher = elgamal.generate_keys(seed=0xffffffffffffff, iNumBits=18)
    return Block(0, time.time(), {"transactions": None}, cipher, 18)
Ejemplo n.º 7
0
def mine(a, blockchain, node_pending_transactions):

    BLOCKCHAIN = blockchain
    NODE_PENDING_TRANSACTIONS = node_pending_transactions

    while True:
        """Mining is the only way that new coins can be created.
        In order to prevent too many coins to be created, the process
        is slowed down by a proof of work algorithm.
        """
        # Get the last proof of work
        last_block = BLOCKCHAIN[-1]

        if last_block.index == 0:
            time.sleep(1)

        if (last_block.index + 2) % term == 2:
            difficulty = Calculate_Difficulty(last_block.public_key_size)

        NODE_PENDING_TRANSACTIONS = requests.get(MINER_NODE_URL +
                                                 "/txion?update=" +
                                                 MINER_ADDRESS).content
        NODE_PENDING_TRANSACTIONS = json.loads(NODE_PENDING_TRANSACTIONS)
        NODE_PENDING_TRANSACTIONS.append({
            "from": "network",
            "to": MINER_ADDRESS,
            "amount": 1
        })
        new_block_data = {"transactions": list(NODE_PENDING_TRANSACTIONS)}

        new_block_index = last_block.index + 2
        new_block_timestamp = time.time()
        before_header_hash_ = BLOCKCHAIN[-1].hash_header()
        before_public = BLOCKCHAIN[-1].next_public
        cipher = elgamal.generate_keys(
            iNumBits=difficulty,
            seed=int(before_public.p + before_public.g + before_public.h))
        new_block_next_public = cipher
        candidate_block = Block(new_block_index,
                                new_block_timestamp,
                                new_block_data,
                                new_block_next_public,
                                difficulty,
                                before_header_hash=before_header_hash_)

        # Find the proof of work for the current block being mined
        # Note: The program will hang here until a new proof of work is found
        proof = proof_of_work(last_block, candidate_block, BLOCKCHAIN)
        # If we didn't guess the proof, start mining again
        if not proof[0]:
            # Update blockchain and save it to file
            BLOCKCHAIN = proof[1]
            a.send(BLOCKCHAIN)
            continue
        else:
            # Once we find a valid proof of work, we know we can mine a block so
            # ...we reward the miner by adding a transaction
            # First we load all pending transactions sent to the node server
            '''
            # Then we add the mining reward
            NODE_PENDING_TRANSACTIONS.append({
                "from": "network",
                "to": MINER_ADDRESS,
                "amount": 1})
            # Now we can gather the data needed to create the new block
            '''
            # Empty transaction list

            NODE_PENDING_TRANSACTIONS = []
            # Now create the new block
            BLOCKCHAIN.append(proof[0])
            # print("before_public_key = " + str(proof[0].key.p * proof[0].key.q))
            print(
                json.dumps(
                    {
                        "index":
                        str(proof[0].index),
                        "timestamp":
                        str(proof[0].timestamp),
                        "header_hash":
                        str(proof[0].hash_header()),
                        "difficult":
                        str(proof[0].difficult),
                        "public_key_size":
                        str(proof[0].public_key_size),
                        "before_header_hash":
                        str(proof[0].before_header_hash),
                        "next_public":
                        "( " + str(hex(proof[0].next_public.g)) + ", " +
                        str(hex(proof[0].next_public.h)) + ", " +
                        str(hex(proof[0].next_public.p)) + " )",
                        "nonce":
                        "( " + str(proof[0].nonce) + " )",
                        "data":
                        proof[0].data
                    },
                    indent=4) + "\n")
            a.send(BLOCKCHAIN)
            requests.get(MINER_NODE_URL + "/blocks?update=" + MINER_ADDRESS)
Ejemplo n.º 8
0
if __name__ == "__main__":
    args = get_args()
    bitLen = int(args.bit_lenght)
    if args.type == 'rsa':
        (e, n), (d, n) = rsa.generate_keys(bitLen)
        with open(args.key_name + '_public', 'w') as p:
            p.write(str(e) + "\n")
            p.write(str(n))
        with open(args.key_name + '_private', 'w') as p:
            p.write(str(d) + "\n")
            p.write(str(n))
        print "keys {0}_public and {0}_private {1} succesfully generated".format(args.key_name, bitLen)

    if args.type == 'elgamal':
        (p, g, y), (p, x) = elgamal.generate_keys(bitLen)
        with open(args.key_name + '_public', 'w') as f:
            f.write(str(p) + "\n")
            f.write(str(g) + "\n")
            f.write(str(y))
        with open(args.key_name + '_private', 'w') as f:
            f.write(str(p) + "\n")
            f.write(str(x))
        print "keys {0}_public and {0}_private {1} succesfully generated".format(args.key_name, bitLen)

    if args.type == 'f_s':
        (n, v), (n, s) = f_s.generate_keys(bitLen)
        with open(args.key_name + '_public', 'w') as f:
            f.write(str(n) + "\n")
            f.write(str(v))
        with open(args.key_name + '_private', 'w') as f:
Ejemplo n.º 9
0
""" Testing the elgamal module """

if __name__ == "__main__":
    # Documents to sign
    msgs = ["ECRYP", "kwojakow", "ElGamal Digital Signature", "lorem ipsum", "dorime interimo adapare dorime ameno ameno latire latiremo dorime"]
    # Hash function
    hfun = sha256()
    # Bit Length
    N = 32

    # Testing the signatures for the documents
    for msg in msgs:
        print("Message:")
        print(msg)

        elgsys = elgamal.generate_system(N, hfun)
        print("Generated system:")
        print(elgsys)

        keys = elgamal.generate_keys(elgsys)
        print("Generated key pair (x, y):")
        print(keys)

        sig = elgamal.sign(elgsys, msg, keys[0])
        print("Generated signature pair (r, s):")
        print(sig)

        is_valid = elgamal.verify(elgsys, msg, sig, keys[1])
        print("Is signature valid?")
        print(is_valid)
Ejemplo n.º 10
0
    random.shuffle(C)
    return C


def IsAliceRicher(C, sk):
    ansTemp = 0
    for c in C:
        if elgamal.decrypt(sk, c) == 1:
            ansTemp = 1  # x >y
    return ansTemp


## works for numbers greter than 0 and less than < 1024
if __name__ == '__main__':

    sk, pk = elgamal.generate_keys(256)

    n = 11

    # Alice has x
    # x -->[0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0]
    x = [random.randint(0, 1) for i in range(n)]
    y = [random.randint(0, 1) for i in range(n)]

    GT = -1
    for i in range(n):
        if x[i] > y[i]:
            GT = 1
            break
        elif x[i] < y[i]:
            GT = 0
Ejemplo n.º 11
0
import socket
import sys
import elgamal
import os
import pickle

dicc = elgamal.generate_keys()
publicKey = dicc['publicKey']
privateKey = dicc['privateKey']
pickled_data = pickle.dumps(publicKey)

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the port
server_address = ('localhost', 10000)
print('starting up on {} port {}'.format(*server_address))
sock.bind(server_address)

# Listen for incoming connections
sock.listen(1)

while True:
    # Wait for a connection
    print('waiting for a connection')
    print('Esprando solicitud...')
    connection, client_address = sock.accept()
    try:
        print('connection from', client_address)

        # Receive the data in small chunks and retransmit it
Ejemplo n.º 12
0
    hex_lenth = len(str(hashlib.sha512(repr(data).encode('ascii')).hexdigest()))
    return data + str(hashlib.sha512(repr(data).encode('ascii')).hexdigest())

def verify_signature(data, signature):
    return signature == create_signature(data)


print("Create your dyplom")
my_diplom = input()
data_lenth = len(my_diplom)
signature = create_signature(my_diplom)
print("Dyplom with hsa512 injection:")
print(signature)
########################################

keys = elgamal.generate_keys(128)
pub = keys['privateKey']
priv = keys['publicKey']
true_mesg = elgamal.encrypt(priv, signature)
print("Encrypted dyplom:")
print(true_mesg)
print("\0")
########################################
print("City is becoming sleep")
print("...")
print("Mafia awakes")

print("Change that diplom, Johny")
another_dyplom = input()
weird_signature = create_signature(another_dyplom)
print("false dyplom with hsa512 injection:")
def generate_keys():
    n = 0
    c = 0
    n = int(input(" give N: "))
    c = int(input(" give C: "))
    return elgamal.generate_keys(n, c)
Ejemplo n.º 14
0
# sender generates message signature
s = rsa.sign(keys['n'], keys['d'], message)
print("Signature:", s)

# receiver verifies the signiature and message
verified = rsa.verify_signature(keys['n'], keys['e'], s, message)
print("Message matches signature:", verified)

# ElGamal #############################################################

print("ElGamal digital signature demo.\n")
message = 4567

# sender generate keys
keys = elgamal.generate_keys(7331, 3411, 41)
print("Keys:", keys, "\n")

# sender chooses random int k, where 0 > k > p-1, and gcd(k, p-1) = 1
k = 919
print("Randomly chosen int k:", k)

# sender generates message signature
s = elgamal.sign(keys['g'], k, keys['p'], keys['x'], message)
print("Generated signature:", s)

# receiver verifies the signiature and message
verify = elgamal.verify_signature(keys['g'], keys['y'], keys['p'], s['r'],
                                  s['s'], message)
print("\nVerification params v, w:", verify['v'], verify['w'],
      "\nMessage matches signature:", verify['result'])
Ejemplo n.º 15
0
def test_encode_decode():
    private_key, public_key = generate_keys()
    cryptogram = encode(public_key, ord('m'))
    message = decode(cryptogram, private_key)
    assert message == ord('m')
Ejemplo n.º 16
0
# server.py
import socket
import elgamal
import pickle

#elgamal
keys=elgamal.generate_keys()
key_for_server=keys.copy()
del key_for_server['privateKey']
key_server=pickle.dumps(key_for_server,-1)

# create a socket object
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 8001
serversocket.bind(('', port))
serversocket.listen(5)
clientsocket,addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
msg=" "

key_client=clientsocket.recv(1024)
clientsocket.send(key_server)
key_client=pickle.loads(key_client)


while msg!="bye":
    smsg=clientsocket.recv(1024)#.decode('ascii')
    plaintext = elgamal.decrypt(keys['privateKey'],smsg)  #returns the message passed to elgamal.encrypt()
    print("Client(enc) : %s" % smsg)
    print("Client : %s" % plaintext)
Ejemplo n.º 17
0
def generateWalletKeys():
    return elgamal.generate_keys()