def generate(self, algorithm, mode): algorithm = algorithm.get() modes = mode.get() mode = get_mode(mode.get()) sim_key = self.HexToByte(get_data(self.sim_key_path, 'Secret key')) if (algorithm.split('-')[0].upper() == 'AES'): iv = Random.new().read(AES.block_size) cipher = AES.new(sim_key, mode, iv) else: iv = Random.new().read(DES3.block_size) cipher = DES3.new(sim_key, mode, iv) data = get_data(self.input_path, 'Data') if len(data) % cipher.block_size != 0: data += ' ' * (cipher.block_size - len(data) % cipher.block_size) encoded = cipher.encrypt(data) encoded = b64encode(encoded) modulus = int(int(get_data(self.public_key_path, 'Modulus'), 16)) public_exp = int( int(get_data(self.public_key_path, 'Public exponent').strip(), 16)) asimmetric_alg = get_data(self.public_key_path, 'Method') if asimmetric_alg != 'RSA': generator = int( int(get_data(self.public_key_path, 'Generator'), 16)) if (asimmetric_alg == 'RSA'): RSAEncryptor = RSA.construct((modulus, public_exp)) encrypted_key = RSAEncryptor.encrypt(sim_key, '') encrypted_key = encrypted_key[0] else: ElGamalEncryptor = ElGamal.construct( (modulus, generator, public_exp)) while 1: k = random.StrongRandom().randint(1, modulus - 1) if GCD(k, modulus - 1) == 1: break encrypted_key = ElGamalEncryptor.encrypt(sim_key, int(k)) k = encrypted_key[1] encrypted_key = encrypted_key[0] file = open(self.envelope_path, 'w') file.write('---BEGIN OS2 CRYPTO DATA---\n') file.write('Description:\n Envelope\n\n') file.write('File name:\n ') file.write(self.envelope_path) file.write('\n\nMethod:\n ' + algorithm.split('-')[0].upper() + '\n ' + asimmetric_alg + '\n\n') if asimmetric_alg != 'RSA': file.write('Secret number:\n ') write_to_file(file, self.ByteToHex(k)) file.write('\n\nCrypt Method:\n ' + modes + '\n\n') file.write('Initialization vector:\n ' + str(self.ByteToHex(iv))) file.write('\n\nKey length:\n ' + str(hex(len(sim_key) * 8)).replace('0x', '') + '\n ') file.write(get_data(self.public_key_path, 'Key length')) file.write('\n\nEnvelope data:\n ') write_to_file(file, encoded.decode()) file.write('\n\nEnvelope crypt key:\n ') write_to_file(file, self.ByteToHex(encrypted_key)) file.write('\n\n---END OS2 CRYPTO DATA---')
def test_encryption(self): for tv in self.tve: d = self.convert_tv(tv, True) key = ElGamal.construct(d['key']) ct = key._encrypt(d['pt'], d['k']) self.assertEqual(ct[0], d['ct1']) self.assertEqual(ct[1], d['ct2'])
def __init__(self, hostname): # with open('key.pkl', 'rb') as input: # self.key = pickle.load(input) # self.key = ElGamal.generate(1024, Random.new().read) # with open('key.txt', 'w') as f: # f.write(str(self.key.p) + '\n') # f.write(str(self.key.g) + '\n') # f.write(str(self.key.y) + '\n') # f.write(str(self.key.x) + '\n') self.hostname = hostname if self.hostname == config.SERVER_A_HOSTNAME: path = 'key1.txt' elif self.hostname == config.SERVER_B_HOSTNAME: path = 'key2.txt' elif self.hostname == config.SERVER_C_HOSTNAME: path = 'key3.txt' else: print('invalid hostname') sys.exit(1) with open(path, 'r') as f: p = config.P g = config.G x = int(f.readline()) y = int(f.readline()) self.key = ElGamal.construct((p, g, y, x)) print('finish initialization')
def test_signing(self): for tv in self.tvs: d = self.convert_tv(tv, True) key = ElGamal.construct(d['key']) sig1, sig2 = key._sign(d['h'], d['k']) self.assertEqual(sig1, d['sig1']) self.assertEqual(sig2, d['sig2'])
def load_unencrypted(pkeyInfo): version, pkeyAlgo, pkeyData = pkeyInfo[0:3] if version != 0: raise PKCSError('unknown PKCS#8 version: {}'.format(version)) algoId, algoParms = pkeyAlgo.get_pos(0,2) if algoId == OID_PKCS_RSAPKEY: from Crypto.PublicKey import RSA rsakey = asn1.loads(pkeyData) vals = rsakey[1:6] # n, e, d, p, q pkey = RSA.construct([long(val) for val in vals]) print 'RSA!', vals elif algoId == OID_PKCS_DSAPKEY: from Crypto.PublicKey import DSA p, q, g = algoParms x = asn1.loads(pkeyData) y = pow(g, x, p) vals = (y, g, p, q, x) pkey = DSA.construct([long(val) for val in vals]) elif algoId == OID_PKCS_DHPKEY: from Crypto.PublicKey import ElGamal p, g = algoParms[0:2] x = asn1.loads(pkeyData) y = pow(g, x, p) vals = (p, g, y, x) pkey = ElGamal.construct([long(val) for val in vals]) else: raise PKCSError('unknown PKCS#8 key algorithm: {}'.format(algoId)) return pkey
def verify_ElGamal(msg, sig_tuple, key_tuple): """Verify an ElGamal signature. :Parameters: - `msg`: string of data signature applies to - `sig_tuple`: tuple of ElGamal signature integers (a, b) (see `ElGamal signature tuple`_) - `key_tuple`: tuple of ElGamal key integers (p, g, y) (see `ElGamal key tuple`_) :Returns: tuple (integer, None) where integer == 1 or 0, verification true or false .. _ElGamal signature tuple: ElGamal signature tuple: - `a`: integer ElGamal "a" - `b`: integer ElGamal "b" .. _ElGamal key tuple: ElGamal key tuple: - `p`: integer ElGamal prime - `g`: integer ElGamal group - `y`: integer ElGamal public key """ import Crypto.PublicKey.ElGamal as ELG elg = ELG.construct(key_tuple) # note change in ordering return elg.verify(msg, sig_tuple)
def reencrypt(self, cipher, pubkey=None): ''' >>> B = 64 >>> k = AVCrypt(bits=B) >>> clears = [random.StrongRandom().randint(1, B) for i in range(5)] >>> cipher = [k.encrypt(i) for i in clears] >>> cipher2 = [k.reencrypt(i) for i in cipher] >>> d = [k.decrypt(i) for i in cipher] >>> d2 = [k.decrypt(i) for i in cipher2] >>> clears == d == d2 True >>> cipher != cipher2 True ''' if pubkey: p, g, y = pubkey k = ElGamal.construct((p, g, y)) else: k = self.k a, b = cipher a1, b1 = self.encrypt(1, k=k) return ((a * a1) % k.p, (b * b1) % k.p)
def test_decryption(self): for tv in self.tve: for as_longs in (0, 1): d = self.convert_tv(tv, as_longs) key = ElGamal.construct(d['key']) pt = key.decrypt((d['ct1'], d['ct2'])) self.assertEqual(pt, d['pt'])
def reencrypt(self, cipher, pubkey=None): ''' >>> B = 256 >>> k = MixCrypt(bits=B) >>> clears = [random.StrongRandom().randint(1, B) for i in range(5)] >>> cipher = [k.encrypt(i) for i in clears] >>> cipher2 = [k.reencrypt(i) for i in cipher] >>> d = [k.decrypt(i) for i in cipher] >>> d2 = [k.decrypt(i) for i in cipher2] >>> clears == d == d2 True >>> cipher != cipher2 True ''' if pubkey: p, g, y = pubkey k = ElGamal.construct((p, g, y)) else: k = self.k a, b = map(int, cipher) a1, b1 = map(int, self.encrypt(1, k=k)) p = int(k.p) return ((a * a1) % p, (b * b1) % p)
def test_signing(self): for tv in self.tvs: for as_longs in (0, 1): d = self.convert_tv(tv, as_longs) key = ElGamal.construct(d["key"]) sig1, sig2 = key.sign(d["h"], d["k"]) self.assertEqual(sig1, d["sig1"]) self.assertEqual(sig2, d["sig2"])
def test_encryption(self): for tv in self.tve: for as_longs in (0, 1): d = self.convert_tv(tv, as_longs) key = ElGamal.construct(d['key']) ct = key.encrypt(d['pt'], d['k']) self.assertEqual(ct[0], d['ct1']) self.assertEqual(ct[1], d['ct2'])
def test_signing(self): for tv in self.tvs: for as_longs in (0,1): d = self.convert_tv(tv, as_longs) key = ElGamal.construct(d['key']) sig1, sig2 = key.sign(d['h'], d['k']) self.assertEquals(sig1, d['sig1']) self.assertEquals(sig2, d['sig2'])
def test_encryption(self): for tv in self.tve: for as_longs in (0,1): d = self.convert_tv(tv, as_longs) key = ElGamal.construct(d['key']) ct = key.encrypt(d['pt'], d['k']) self.assertEquals(ct[0], d['ct1']) self.assertEquals(ct[1], d['ct2'])
def reconstruct_key(k_dict): """ Reconstruye una clave a partir de un diccionario de Python. Utilizado para desserialización. :param k_dict: Un diccionario que describe una clave. :return: Un objeto de clave ElGamal. """ p = k_dict.get("p") g = k_dict.get("g") y = k_dict.get("y") x = k_dict.get("x") if x: return ElGamal.construct((p, g, y, x)) else: return ElGamal.construct((p, g, y))
def test_signing(self): for tv in self.tvs: for as_longs in (0, 1): d = self.convert_tv(tv, as_longs) key = ElGamal.construct(d['key']) sig1, sig2 = key.sign(d['h'], d['k']) self.assertEqual(sig1, d['sig1']) self.assertEqual(sig2, d['sig2'])
def test_encryption(self): for tv in self.tve: for as_longs in (0, 1): d = self.convert_tv(tv, as_longs) key = ElGamal.construct(d["key"]) ct = key.encrypt(d["pt"], d["k"]) self.assertEqual(ct[0], d["ct1"]) self.assertEqual(ct[1], d["ct2"])
def setUpClass(cls): cls.A = ''.join(random.choice(string.ascii_letters) for _ in range(12)) cls.B = ''.join(random.choice(string.ascii_letters) for _ in range(12)) keyA = ElGamal.generate(cls.NUM_BITS, Random.new().read) with open(cls.A, 'w') as f: f.write(export_elgamal_key(keyA)) with open(cls.A + '.pub', 'w') as f: f.write(export_elgamal_key(keyA.publickey())) x = random.randint(1 + 1, keyA.p - 1 - 1) y = pow(keyA.g, x, keyA.p) tup = (keyA.p, keyA.g, y, x) keyB = ElGamal.construct(tup) with open(cls.B, 'w') as f: f.write(export_elgamal_key(keyB)) with open(cls.B + '.pub', 'w') as f: keyB = ElGamal.construct(tup) f.write(export_elgamal_key(keyB.publickey()))
def test_verification(self): for tv in self.tvs: d = self.convert_tv(tv, True) key = ElGamal.construct(d['key']) # Positive test res = key._verify( d['h'], (d['sig1'],d['sig2']) ) self.failUnless(res) # Negative test res = key._verify( d['h'], (d['sig1']+1,d['sig2']) ) self.failIf(res)
def keyConstruct(self, args): """ input a tuple of following elements in order which satisfy: """ key = ElGamal.construct(args) return key
def set_key(self, key): key_data = [] for part in range(8 * len(key) // self.key_size): key_part = key[self.key_size // 8 * part:self.key_size // 8 * (part + 1)] key_part_int = int.from_bytes(key_part, byteorder='big', signed=False) key_data.append(key_part_int) self.key = CryptoElGamal.construct(key_data)
def test_verification(self): for tv in self.tvs: d = self.convert_tv(tv, True) key = ElGamal.construct(d['key']) # Positive test res = key._verify(d['h'], (d['sig1'], d['sig2'])) self.assertTrue(res) # Negative test res = key._verify(d['h'], (d['sig1'] + 1, d['sig2'])) self.assertFalse(res)
def decrypt_public(algorithm, key_tuple, cipher_tuple): """Decrypt public key encrypted data. :Parameters: - `algorithm`: integer public key algorithm constant - `key_tuple`: tuple containing a public and private integers of the target key, RSA values (n, d) or ElGamal values (p, x) - `cipher_tuple`: tuple containing the integers of the encrypted data, coerced RSA value (c, ) and ElGamal values (a, b) :Returns: string cleartext `decrypt_public()` works with public key encrypted information (information encrypted to public key values and decrypted using the corresponding secret key values). This function works with tuples of public key values and tuples of values that comprise the "ciphertext." **Use this function to decrypt public key encrypted session key packets.** RSA key tuple (n, d): - `n`: integer RSA product of primes p & q - `d`: integer RSA decryption key RSA cipher tuple (c, ): - `c`: integer m**e mod n ElGamal key tuple (p, x): - `p`: integer ElGamal prime - `x`: integer ElGamal private key ElGamal cipher tuple (a, b): - `a`: integer ElGamal value g**k mod p - `b`: integer ElGamal value m * y**k mod p Use this for decrypting public-key encrypted session keys. """ key_tuple = tuple([long(i) for i in key_tuple]) # long(): fastmath dep if algorithm in [ASYM_RSA_EOS, ASYM_RSA_E]: from Crypto.PublicKey import RSA key = RSA.construct((key_tuple[0], 0L, key_tuple[1])) # L for fastmath a = STN.int2str(cipher_tuple[0]) return key.decrypt((a,)) elif algorithm in [ASYM_ELGAMAL_EOS, ASYM_ELGAMAL_E]: from Crypto.PublicKey import ElGamal key = ElGamal.construct((key_tuple[0], 0, 0, key_tuple[1])) a = STN.int2str(cipher_tuple[0]) b = STN.int2str(cipher_tuple[1]) return key.decrypt((a, b)) else: raise NotImplementedError, "Unsupported asymmetric algorithm:%s" % algorithm
def test_verification(self): for tv in self.tvs: for as_longs in (0, 1): d = self.convert_tv(tv, as_longs) key = ElGamal.construct(d["key"]) # Positive test res = key.verify(d["h"], (d["sig1"], d["sig2"])) self.assertTrue(res) # Negative test res = key.verify(d["h"], (d["sig1"] + 1, d["sig2"])) self.assertFalse(res)
def __init__(self, data): _PubkeyAlg.__init__(self) (p, pos) = _parseMPI(data) (g, length) = _parseMPI(data[pos:]) pos += length (y, length) = _parseMPI(data[pos:]) if pos + length != len(data): raise ValueError, "Invalid ElGamal public key data" if ElGamal is None: raise NotImplementedError, "python-Crypto not available" self.elgamal = ElGamal.construct((p, g, y))
def test_verification(self): for tv in self.tvs: for as_longs in (0, 1): d = self.convert_tv(tv, as_longs) key = ElGamal.construct(d['key']) # Positive test res = key.verify(d['h'], (d['sig1'], d['sig2'])) self.failUnless(res) # Negative test res = key.verify(d['h'], (d['sig1'] + 1, d['sig2'])) self.failIf(res)
def allocate_key(address_list): for address in address_list: res = requests.get(url="http://" + address + config.port + '/public_key') res = res.json() p = res['p'] g = res['g'] y = res['y'] pkey = ElGamal.construct((int(p), int(g), int(y))) pkeys.append(pkey) return pkeys
def construct(pub_dict, priv_dict): """Construct ElGamal object key based on given components :components: tuple ElGamal components usually p, g, y and x. Where x is the secret key and it is optional. :returns: Crypto.PublicKey.ElGamal.ElGamalobj """ return ElGamal.construct((pub_dict['p'], pub_dict['g'], pub_dict['y'], priv_dict['x']))
def generate(self, hash_function): data = get_data(self.input_path, 'Data') modulus = int(int(get_data(self.private_key_path, 'Modulus'), 16)) private_exp = int( int(get_data(self.private_key_path, 'Private exponent'), 16)) public_exp = int( int(get_data(self.public_key_path, 'Public exponent').strip(), 16)) private_key_size = get_data(self.private_key_path, 'Key length') asimmetric_alg = get_data(self.private_key_path, 'Method') m = hashlib.new(hash_function.get()) m.update(data.encode(encoding='utf-8')) hash = m.digest() if (asimmetric_alg == 'RSA'): RSAEncryptor = RSA.construct((modulus, public_exp, private_exp)) signature = RSAEncryptor.sign(hash, '')[0] self.signature_second_part = '' else: generator = int( int(get_data(self.private_key_path, 'Generator'), 16)) ElGamalEncryptor = ElGamal.construct( (modulus, generator, public_exp, private_exp)) while 1: k = random.StrongRandom().randint(1, int(modulus - 1)) if GCD(k, int(modulus - 1)) == 1: break signature = ElGamalEncryptor.sign(hash, int(k)) k = signature[1] signature = signature[0] self.signature = signature data = b64encode(data.encode()) signature = hex(signature) # zapisivanje file = open(self.signature_path, 'w') file.write('---BEGIN OS2 CRYPTO DATA---\n') file.write('Description:\n Signature\n\n') file.write('File name:\n ') file.write(self.signature_path) file.write('\n\nMethod:\n ' + hash_function.get() + '\n ' + asimmetric_alg) if asimmetric_alg != 'RSA': file.write('\n\nSecret number:\n ') write_to_file(file, str(hex(k).upper()[2:])) file.write('\n\nKey length:\n ') file.write( str(hex(len(hash) * 8)).upper().replace('0X', '') + '\n ') file.write(private_key_size) file.write('\n\nData:\n ') write_to_file(file, data.decode()) file.write('\n\nSignature:\n ') write_to_file(file, str(signature).upper().replace('0X', '')) file.write('\n\n---END OS2 CRYPTO DATA---')
def encrypt_public(algorithm, msg, key_tuple): """Encrypt data to a public key. :Parameters: - `algorithm`: integer public key algorithm constant - `key_tuple`: tuple containing a public and private integers the target key, RSA values (n, d) or ElGamal values (p, g, y) (see `RSA key tuple`_ and `ElGamal key tuple`_) :Returns: tuple ciphertext (a, b) for ElGamal and (r,) for RSA .. _RSA key tuple: RSA key tuple (n, e): - `n`: integer RSA product of primes p & q - `e`: integer RSA encryption key .. _ElGamal key tuple: ElGamal key tuple (p, g, y): - `p`: integer ElGamal prime - `g`: integer ElGamal group generator - `y`: integer ElGamal public key """ import Crypto.Util.number key_tuple = tuple([long(i) for i in key_tuple]) # fastmath dep if algorithm in [ASYM_RSA_EOS, ASYM_RSA_E]: from Crypto.PublicKey import RSA key = RSA.construct(key_tuple) k = '' elif algorithm in [ASYM_ELGAMAL_EOS, ASYM_ELGAMAL_E]: from Crypto.PublicKey import ElGamal key = ElGamal.construct(key_tuple) k = Crypto.Util.number.getPrime(128, gen_random) else: raise NotImplementedError, "Can't handle public encryption algorithm->(%s)" % algorithm enc_tup = key.encrypt(msg, k) # Crypto returns strings instead of integers. return tuple([STN.str2int(x) for x in enc_tup]) # Why?
def load_x509(cert): def make_attrlist(value): return [{ATTR_NAMES.get(id, id): val} for item in value for id, val in item.iteritems()] cert, signAlg, signData = cert idx = cert.find_tag(0) pkeyAlgo, pkeyData = cert[idx+6] algoId, algoParms = pkeyAlgo.get_pos(0,2) if algoId == OID_PKCS_RSAPKEY: from Crypto.PublicKey import RSA rsakey = asn1.loads(pkeyData) vals = rsakey[0:2] # n, e pkey = RSA.construct([long(val) for val in rsakey]) elif algoId == OID_PKCS_DSAPKEY: from Crypto.PublicKey import DSA p, q, g = algoParms y = asn1.loads(pkeyData) vals = (y, g, p, q) pkey = DSA.construct([long(val) for val in vals]) elif algoId == OID_PKCS_DHPUBNUM: from Crypto.PublicKey import ElGamal p, g, q = algoParms[0:3] y = asn1.loads(pkeyData) vals = (p, g, y) pkey = ElGamal.construct([long(val) for val in vals]) else: raise PKCSError('unknown X.509 key algorithm: {}'.format(algoId)) pkey.serialNumber = cert[idx+1] pkey.signature = cert[idx+2] pkey.issuer = make_attrlist(cert[idx+3]) pkey.validFrom, pkey.validTo = cert[idx+4] pkey.subject = make_attrlist(cert[idx+5]) pkey.version = cert.get_tag(0, None, 0) + 1 if pkey.version >= 2: pkey.issuerUniqueID = cert.get_tag(1, asn1.BIT_STRING) pkey.subjectUniqueID = cert.get_tag(2, asn1.BIT_STRING) if pkey.version >= 3: # pkey.extensions = cert.get_tag(3, None, []) extensions = cert.get_tag(3, None, []) pkey.extensions = {} for extension in extensions: extnId = extension[0] if extension[1] == True: extnVal = (True, asn1.loads(extension[2])) else: extnVal = (False, asn1.loads(extension[1])) pkey.extensions[ATTR_NAMES.get(extnId, extnId)] = extnVal return pkey
def decrypt_vote_tally_threshold(public_key, shares, vote_tally): """ Realiza el descifrado de los votos mediante un esquema de cifrado umbral. .. note:: Idealmente no se reconstruye la clave sino que se usa algún protocolo de computación distribuida para ejectuar el cómputo **SIN** reconstruir la clave. :param public_key: La clave pública de la elección. :param vote_tally: El escrutinio cifrado de votos. :param shares: Una lista de secretos compartidos que permiten descifrar conjuntamente los votos. :returns: El escrutinio de votos descifrado. """ private_key = ElGamal.construct((public_key.p, public_key.g, public_key.y, recover_secret(shares))) return list(map(lambda x: private_key.decrypt(x), vote_tally))
def __ElGamal_importKey(self, extern_key): """Import an ElGamal key (public or private), encoded in either PEM or DER form. :params str extern_key: The key to import, encoded as a string :returns: an ElGamalobj representing a key :rtype: ElGamalobj """ try: key_dict = json.loads(_bytes_to_string(extern_key)) _tup = [key_dict['p'], key_dict['g'], key_dict['y']] if 'x' in key_dict: _tup.append(key_dict['x']) return ElGamal.construct(tuple(_tup)) except: raise CryptoError("Can not parse key")
def open_envelope(self): envelope_data = b64decode(get_data(self.envelope_path, 'Envelope data')) crypt_key = self.HexToByte( get_data(self.envelope_path, 'Envelope crypt key')) private_exp = int( int(get_data(self.private_key_path, 'Private exponent'), 16)) public_exp = int( int(get_data(self.public_key_path, 'Public exponent'), 16)) crypt_method = get_mode(get_data(self.envelope_path, 'Crypt Method')) methods = get_methods(self.envelope_path).split(':') modulus = int(int(get_data(self.private_key_path, 'Modulus'), 16)) iv = self.HexToByte( get_data(self.envelope_path, 'Initialization vector')) if methods[1] == 'RSA': RSAEncryptor = RSA.construct((modulus, public_exp, private_exp)) decrypted_key = RSAEncryptor.decrypt((crypt_key, '')) else: generator = int( int(get_data(self.private_key_path, 'Generator'), 16)) k = self.HexToByte( get_data(self.envelope_path, 'Secret number').lower().strip()) ElGamalEncryptor = ElGamal.construct( (modulus, generator, public_exp, private_exp)) decrypted_key = ElGamalEncryptor.decrypt((crypt_key, k)) if (methods[0] == 'AES'): cipher = AES.new(decrypted_key, crypt_method, iv) data = cipher.decrypt(envelope_data) else: cipher = DES3.new(decrypted_key, crypt_method, iv) data = cipher.decrypt(envelope_data) # zapisivanje data-e file = open(self.output_path, 'w') file.write('---BEGIN OS2 CRYPTO DATA---\n') file.write('Description:\n Decrypted Envelope\n\n') file.write('File name:\n ') file.write(self.output_path) file.write('\n\nMethod:\n ' + methods[0] + '\n ' + methods[1] + '\n\n') file.write('Data:\n ') write_to_file(file, data.decode()) file.write('\n\n---END OS2 CRYPTO DATA---')
def check(self): data = get_data(self.signature_path, 'Data') data = b64decode(data) modulus = int(int(get_data(self.public_key_path, 'Modulus'), 16)) public_exp = int( int(get_data(self.public_key_path, 'Public exponent').strip(), 16)) methods = get_methods(self.signature_path).split(':') if methods[1] != 'RSA': generator = int( int(get_data(self.public_key_path, 'Generator'), 16)) k = int( int( get_data(self.signature_path, 'Secret number').strip(), 16)) signature = get_data(self.signature_path, 'Signature') signature = int(int(signature, 16)) m = hashlib.new(methods[0]) m.update(data) hash = m.digest() if methods[1] == 'RSA': RSAEncryptor = RSA.construct((modulus, public_exp)) if RSAEncryptor.verify(hash, (signature, '')): print("Message is authentic") tkinter.messagebox.showinfo("Message is authentic") else: print("Integrity and authentic are disrupted!") tkinter.messagebox.showinfo( "Integrity and authentic are disrupted!") else: ElGamalEncryptor = ElGamal.construct( (modulus, generator, public_exp)) if ElGamalEncryptor.verify(hash, (signature, k)): print("Message is authentic") tkinter.messagebox.showinfo("Message is authentic") else: print("Integrity and authentic are disrupted!") tkinter.messagebox.showinfo( "Integrity and authentic are disrupted!")
def elgamal_auth(usr, sig1, sig2): # Database connection conn = MySQLdb.connect( host='localhost', user='******', passwd='123456', db='project', charset='utf8' ) cur = conn.cursor() # Search username in database and key files sql_search = "SELECT * FROM users WHERE loginid = '%s'" % usr if cur.execute(sql_search) == 1L and os.path.exists('auth/elgamal/keys/%s.pub' % usr): # Signature authentication f = open('auth/elgamal/keys/%s.pub' % usr,'r') pk = f.read() f.close() p = long(pk.split(' ')[0]) g = long(pk.split(' ')[1]) y = long(pk.split(' ')[2]) t = (p, g, y) key = ElGamal.construct(t) h = SHA.new(usr).digest() sig = (long(sig1), long(sig2)) if key.verify(h,sig): return 1 else: return 2
def gen(args): name = unicode(raw_input("Please enter your preferred username: ")) with open('identity', 'w') as f: f.write(name.encode('utf-8')) if args.key_size: el_gamal = ElGamal.generate(args.key_size, Random.new().read) elif args.parameter_from: parameters = [ int(value) for value in args.parameter_from.read().splitlines() ] assert len(parameters) >= 2 p = parameters[0] g = parameters[1] x = random.randint(1 + 1, p - 1 - 1) y = pow(g, x, p) el_gamal = ElGamal.construct((p, g, y, x)) else: raise RuntimeError with open(name, 'w') as f: f.write(export_elgamal_key(el_gamal)) with open(name + '.pub', 'w') as f: f.write(export_elgamal_key(el_gamal.publickey()))
def getk(self, p, g): x = rand(p) y = pow(g, x, p) self.k = ElGamal.construct((p, g, y, x)) return self.k
data = s.recv(1024) #g = s.recv(1024) #y = s.recv(1024) #p is first string, g is 2nd string, y is 3rd string keyArray = data.split('\n') p = int(keyArray[0]) g = int(keyArray[1]) y = int(keyArray[2]) print 'p is: ' + str(p) print 'g is: ' + str(g) print 'y is: ' + str(y) #make an elgamal object publickey = ElGamal.construct((p,g,y)) #encrypting the privateKey and initVector elGamalEncryption = publickey.encrypt(privateKey, random.randint(1, p - 2)) #initVectorEncryption = publickey.encrypt(initVector, random.randint(1, p - 2)) #send over the privateKey and initVector with masks encryptMessage = str(elGamalEncryption[0]) + '\n' + str(elGamalEncryption[1]) #+ '\n' + str(initVectorEncryption[0]) + '\n' + str(initVectorEncryption[1]) #print initVectorEncryption[0] #print initVectorEncryption[1] s.sendall(encryptMessage)
def setk(self, p, g, y, x): self.k = ElGamal.construct((p, g, y, x)) return self.k
def _construct(y, x=None): tup = (elgamal_p, elgamal_g, y, x) if x else (elgamal_p, elgamal_g, y) return ElGamal.construct(tup)
def test_decryption(self): for tv in self.tve: d = self.convert_tv(tv, True) key = ElGamal.construct(d['key']) pt = key._decrypt((d['ct1'], d['ct2'])) self.assertEquals(pt, d['pt'])
def read_key(cls, file_to_read): with open(file_to_read, 'r') as file: key_dict = json.load(file) key = ElGamal.construct((key_dict['p'], key_dict['g'], key_dict['y'], key_dict['x'])) return cls(key)
def read_pub(cls, file_to_read): with open(file_to_read, 'r') as file: pub_key_dict = json.load(file) key = ElGamal.construct((pub_key_dict['p'], pub_key_dict['g'], pub_key_dict['y'], -1)) return cls(key.publickey())
def getpk(key): tup = tuple(map(int, (key['p'], key['g'], key['y']))) pk = ElGamal.construct(tup) pk.q = int(key['q']) return pk
def ElGamalKey(pub=None, priv=None, fd=None): """ make ElGamal KeyPair Object """ if fd is not None: pub = int.from_bytes(fd.read(256), 'big') priv = int.from_bytes(fd.read(256), 'big') if priv: return ElGamal.construct((elgamal_p, elgamal_g, pub, priv)) return ElGamal.construct((elgamal_p, elgamal_g, pub))
def test_signing(self): for tv in self.tvs: d = self.convert_tv(tv, True) key = ElGamal.construct(d['key']) sig1, sig2 = key._sign(d['h'], d['k']) self.assertEquals(sig1, d['sig1']) self.assertEquals(sig2, d['sig2'])
def test_encryption(self): for tv in self.tve: d = self.convert_tv(tv, True) key = ElGamal.construct(d['key']) ct = key._encrypt(d['pt'], d['k']) self.assertEquals(ct[0], d['ct1']) self.assertEquals(ct[1], d['ct2'])
def test_decryption(self): for tv in self.tve: for as_longs in (0, 1): d = self.convert_tv(tv, as_longs) key = ElGamal.construct(d["key"]) pt = key.decrypt((d["ct1"], d["ct2"])) self.assertEqual(pt, d["pt"])
def sign_ElGamal(msg, key_tuple, k=None): """Create an ElGamal signature. :Parameters: - `msg`: string of data signature applies to - `key_tuple`: tuple ElGamal key integers (p, g, x) (see `ElGamal key tuple`_) - `k`: integer (must be relatively prime to p-1) :Returns: tuple (integer, integer) ElGamal signature values (a, b) .. _ElGamal key tuple: ElGamal key tuple: - `p`: integer ElGamal prime - `g`: integer ElGamal random "g" value - `x`: integer ElGamal private key """ import Crypto.PublicKey.ElGamal as ELG if k is None: # generate our own prime k value (k relatively prime to p-1) import Crypto.Util.number as NUM import Crypto.Util.randpool as RND rnd = RND.RandomPool() q = key_tuple[0] # no restrictions on bit length for k, good enough? k = NUM.getPrime(8*len(STN.int2str(q)), rnd.get_bytes) elg = ELG.construct((key_tuple[0], key_tuple[1], 0, key_tuple[2])) return elg.sign(msg, k)
def test_decryption(self): for tv in self.tve: for as_longs in (0,1): d = self.convert_tv(tv, as_longs) key = ElGamal.construct(d['key']) pt = key.decrypt((d['ct1'], d['ct2'])) self.assertEquals(pt, d['pt'])