示例#1
0
def test_ElGamal(num_bit, message):
    print("\n------------------------------------------------------")
    # Generate random prime numbers
    p = BlumBlumShub.generate_prime(num_bit)

    # Test generate_keypair which returns public key ( g, p, h) and the private key (g, p, x)
    public, private = ElGamal.generate_keypair(p)

    print("\n------------------------------------------------------")
    encrypted_msg = ElGamal.encrypt(public, message)

    print("\n------------------------------------------------------")
    decrypted_msg = ElGamal.decrypt(private, encrypted_msg)

    print("\n------------------------------------------------------")
    eve_decrypted_msg = ElGamal.eve(public, encrypted_msg)

    return decrypted_msg, eve_decrypted_msg
示例#2
0
def loop_handler(connection, address, _pk, _sk):
    while True:
        try:
            res = ElGamal.decrypt(pickle.loads(connection.recv(4096)), pk,
                                  sk)  # デシリアライズ -> 復号
            for value in clients:
                if value[1][0] == address[0] and value[1][1] == address[1]:
                    print('Client({}, {}) : {}'.format(value[1][0],
                                                       value[1][1], res))
                else:
                    value[0].send('Client({}, {}) : {}'.format(
                        value[1][0], value[1][1], res).encode())
                    pass
        except Exception as e:
            print(e)
            break
示例#3
0
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License
'''

# Dependencies
import ElGamal as eg
import Redis
import ast

RCh = Redis.RedisChannel()
print("Alice creates her ElGamal Keys: ")
AliceElGamal = eg.ElGamalEncryption(False, keyFile='Utils/primes50.txt')
print("Alice connects and reads Bob's Public key from the channel:")
RCh.connect()
BobPubKey = ast.literal_eval(
    RCh.getRedisVariable('BobPublicKey').decode('utf-8'))
print('Bob Key is: ' + str(BobPubKey))
plainText = 'ciao!'
print('Plain Text: ' + str(plainText))
print('Alice encrypts her message:')
encrypted = AliceElGamal.encrypt(data=plainText, receiverPubKey=BobPubKey)
print(encrypted)
print('Alice sends her message.')
RCh.redisPublish(str(encrypted))
示例#4
0
    PORT = 8766

    socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket.bind((HOST, PORT))
    socket.listen(1)

    print('Waiting for connect from client ...')

    # コネクションとアドレスを取得
    connection, address = socket.accept()
    print('Client connected: ', address)

    print('Key bits ?')
    bits = int(input('> '))
    print('OK, Your', str(bits)+'-bit keys are:')
    pk, sk = ElGamal.gen_key(bits=bits)
    print('public:', pk)  # 公開鍵
    print('secret:', sk)  # 秘密鍵
    line = str(pk[0])+' '+str(pk[1])+' '+str(pk[2])
    connection.send(line.encode("UTF-8"))  # 公開鍵を送る
    print('Given the client the public key ...')
    data = connection.recv(4096).decode()  # クライアントからの応答を確認
    print('Client:', data)

    # 無限ループ byeの入力でループを抜ける
    while True:

        # クライアントからデータを受信
        recvline = ElGamal.decrypt(pickle.loads(connection.recv(4096)), pk, sk)  # デシリアライズ -> 復号

        if recvline == 'bye':
示例#5
0
    HOST = '127.0.0.1'
    PORT = 55580
    socket.bind((HOST, PORT))
    socket.listen(5)  # 5 ユーザまで接続を許可
    clients = []
    while True:
        try:
            # 接続要求を受信
            conn, addr = socket.accept()
        except KeyboardInterrupt:
            socket.close()
            exit()
            break
        print('Client connected(IP:{}, PORT:{})'.format(addr[0], addr[1]))

        print('Key bits ?')
        bits = int(input('> '))
        print('OK, Your', str(bits) + '-bit keys are:')
        pk, sk = ElGamal.gen_key(bits=bits)
        print('public:', pk)  # 公開鍵
        print('secret:', sk)  # 秘密鍵
        line = str(pk[0]) + ' ' + str(pk[1]) + ' ' + str(pk[2])
        conn.send(line.encode())  # 公開鍵を送る
        print('Given the client the public key ...')

        clients.append((conn, addr))
        thread = threading.Thread(target=loop_handler,
                                  args=(conn, addr, pk, sk),
                                  daemon=True)
        thread.start()
示例#6
0
        try:
            _recvline = _sock.recv(4096)
            print(_recvline.decode())
        except Exception as e:
            print(e)
            break


if __name__ == '__main__':
    socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    HOST = '127.0.0.1'
    PORT = 55580
    socket.connect((HOST, PORT))

    print('Waiting for input public key ...')
    pk_li = []
    while True:
        recvline = socket.recv(4096).decode()
        if recvline != '':
            pk_li = recvline.split(' ')
            pk = tuple([int(x) for x in pk_li])
            assert (len(pk) == 3)
            print('public key: ', pk)
            break

    while True:
        your_input = input('')
        socket.send(pickle.dumps(ElGamal.encrypt(your_input, pk)))  # 暗号化 -> シリアライズ
        thread = threading.Thread(target=Handler, args=(socket,), daemon=True)
        thread.start()
示例#7
0
    socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket.connect(SERVER)

    print('Waiting for input public key ...')
    recvline = ''
    sendline = ''
    pk_li = []
    while True:
        recvline = socket.recv(4096).decode()
        if recvline != '':
            pk_li = recvline.split(' ')
            pk = tuple([int(x) for x in pk_li])
            assert (len(pk) == 3)
            print('public key: ', pk)
            socket.send('OK!'.encode('UTF-8'))
            break

    line = ''
    while line != 'bye':
        # 標準入力からデータを取得
        print('Enter your message here.')
        line = input('> ')

        # サーバに送信
        socket.send(pickle.dumps(ElGamal.encrypt(line, pk)))  # 暗号化 -> シリアライズ

    socket.close()

    print('Client side closed.')
示例#8
0
def ElGamalDecryption(p, q, x, r, t):

    return ElGamal.decrypt(p, q, x, r, t)
示例#9
0
opt = int(input('Masukkan pilihan enkripsi/dekripsi : '))
if opt == 1:
    p = int(input('Masukkan nilai p : '))
    g = int(input('Masukkan nilai g : '))
    x = int(input('Masukkan nilai x : '))
    k = int(input('Masukkan nilai k : '))
    ek = ElGamalKey(p, g, x)
    stringfile = str(input('Masukkan nama File yang di enkrip : '))
    cipherfile = str(input('Masukkan nama File hasil enkrip : '))
    publicfilename = str(
        input('Masukkan nama file public key (tanpa extension) : '))
    privatefilename = str(
        input('Masukkan nama file private key (tanpa extension) : '))
    ek.saveKey(publicfilename, privatefilename)
    e = ElGamal()
    e.encryption(stringfile, cipherfile, publicfilename + '.pub', k)

if opt == 2:
    e = ElGamal()
    privatefilename = str(
        input('Masukkan nama file private key (tanpa extension) : '))
    encryptedfilename = str(
        input('Masukkan nama file yang akan di decrypt : '))
    decryptedfilename = str(input('Masukkan nama file hasil decrypt : '))
    e.decryption(encryptedfilename, decryptedfilename,
                 privatefilename + '.priv')

if opt == 3:
    print('menu 3')
示例#10
0
def ElGamalEncryption(p, q, g, y, message):
    cipher = ElGamal.encrypt(p, q, g, y, message)
    r, t = cipher[0], cipher[1]

    return r, t
示例#11
0
def ElGamalAndDSAKeyGeneration(security_level):
    keys = ElGamal.generateKeys(security_level)
    p, q, g, x, y = keys[0], keys[1], keys[2], keys[3], keys[4]
    # x = private key   y = public key
    return p, q, g, x, y
# --->
# Voor gebruik in IDLE (Windows):
# --->
import sys
import os
z = os.path.dirname(os.path.abspath(__file__))
sys.path.append(z)
# <---

# Samenvoeging klassen voor een demonstratie van het ElGamal systeem.

from ElliptischeKromme import *
from ElGamal import *

# Start van het script

K = ElliptischeKromme(5, 1, 23)
k = Punt(K, 0, 1)
C = Punt(K, 5, 6)
EG = ElGamal(K, k, C)
print(EG)
boodschap = input('\nVoer een boodschap bestaand uit enkel kleine letters en spaties in:\n')
c = EG.codeerBoodschap(boodschap)
print('\nDe boodschap "%s" is gecodeerd:\n%s' % (boodschap, EG.printCode(c)))
origineel = EG.decodeerBoodschap(c)
print('\nDe code is terugvertaald naar:\n%s' % (origineel))
示例#13
0
# -*- coding: utf-8 -*-
"""Q3.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/13tCas5l6AZ3awkg_R2oClrN5OdmSzHD7
"""

import ElGamal

q = 20229678282835322453606583744403220194075962461239010550087309021811
p = 12515043909394803753450411022649854273721537251011107748826811168459680628351391154487041320595006736239332192492236943966523053744476127728797963808151142506595330120621663371518281181204797831707349436558443139355672347825267728879376289677517268609959671235059224994785463608330669494457163250373581380036247652030969481046772013799271268710104487022164865004802864076066974153012125551060906054112920469869045223329577015935824864428612446723942040465300185917923305042033306319809712618872063796904132788285518497999327485929730921202745935936913834577610254298809205575162005025170878200786590751850006857921419
g = 2256483143741433163413007675067934542893022968337437312283381964942344365449719628255630752397325376452002398784394008507857025386943645437696558240874471345442532398588406749907930002481624160959132193798842426822193910104962138845873425590946341754334144292886002962901550160578482452138075339294826241799645761655320983735381974177635207208471824667516956679913974643342159550037320378814445802296879470561504511689460916200417902612323039671250567503846175990654512915878143201233050978046269551126178155060158781645062181955781969136435905570787457855530003987887049118699525033120811790739590564684316550493132
h = 1265126138933377994348793193477342224736956600354964713945582205290651827674605003741290400826146165752452701594226002213036650208863340321329798489264160728930653315907521926136642928347549825144026262035747350182493795559385070130959552499813885202334575993642935128132458545523498489490586883187848396314164874056757696154989511633927620869557222556876855999079308839417416012746206040455611002092520255736121673298963050693639916367968280807028975614596114022230524360150581344884219834519025619777858430431159461562871537004523472161672182851052258466610762884570310894027628303901161674783788320479747219000276
r = 3813677439444837990381281624769265484071989883494833765363155214071727573627590213038823018054653614040833306533736593789523636716088751609591517852868217052905415751457961942309213803782661174042131067555996860094296315483087375444362454092891960492098796234624392186112659124915872546640723139762874453050592110272036917039293020539724872406856066252779419482651672320132092421939867392668795959155312634804888215300607725584330531720210355201550529764936881761210810883102986464111409096572364185502722477587178710137175828696000683028806920671859797982157383943866111320227830105178421690303627627943337128795446
t = 10192033240113377640860169195054315981727514327329008790444130729107056930047299547755150775636237252367979032815426685448329207318153807026080454908281501010744250818034651670583477952735248499512182344163892706808295058861406156976805817052235913385764008189983049947270530103937035152142021836645533913141135755114076443812677194719578205394500861775715274421701692402012349095849491286883920257290062297268751154540379108778881866697419701006074165418163601856726590995982244188091368811214058385356303967475393274055097781937296940874619027724511050397080303621427005403200736696096764013637291006737753794119814

for k in range(1, q - 1):  #all possible k values
    r_ = pow(g, k, p)  #calculating the corresponding r value
    if r_ == r:  #check if it's same with r given in the question, if yes we found k
        print("k is:", k)
        break

m = (t * ElGamal.modinv(pow(h, k, p), p)) % p  #computing m
print("m in integer form is:", m)
print("m is:", m.to_bytes((m.bit_length() + 7) // 8,
                          byteorder='big'))  #converting m to string
示例#14
0
文件: main.py 项目: aslit/RSA-ElGamal
                    if type_encryption == "1":

                        # Use Blum Blum Shub algorithm to generate random prime numbers
                        p = BlumBlumShub.generate_prime(num_bit)
                        q = BlumBlumShub.generate_prime(num_bit)

                        RSA.generate_keypair(p, q)

                    # If encryption algorithm is El-Gamal
                    elif type_encryption == "2":

                        # Use Blum Blum Shub algorithm to generate random prime number
                        p = BlumBlumShub.generate_prime(
                            num_bit)  # 127 #999416681 #2860486313 #127

                        public, private = ElGamal.generate_keypair(p)

                # Otherwise, function 2 - Encrypt a message
                elif function == "2":

                    # Get the message from user
                    message = input("Please enter your message : ")

                    # Get the public key from user
                    public = input(
                        "Please enter the public key ( (g, p, h) for El-Gamal /(e,n) for RSA ): "
                    )

                    print(
                        "\n------------------------------------------------------"
                    )