Ejemplo n.º 1
0
    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)
Ejemplo n.º 2
0
 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'])
Ejemplo n.º 3
0
    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')
Ejemplo n.º 4
0
	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
Ejemplo n.º 5
0
def elgamal():
    #伪随机数生成器
    random_generator = Random.new().read
    #生成elgamal Key
    elgKey = ElGamal.generate(256, random_generator)
    #生成私钥
    while 1:
        alpha = random.StrongRandom().randint(1, elgKey.p - 1)
        if GCD(alpha, elgKey.p - 1) == 1:
            break

    h = mod(elgKey.g, alpha, elgKey.p)
    message = [33, 14, 22, 62, 00, 17, 4, 62, 24, 14, 20, 66]
    print('message: ', message)
    #加密过程
    #1.随机选择整数y
    y = random.StrongRandom().randint(1, elgKey.p - 1)
    #2.计算c1
    c1 = mod(elgKey.g, y, elgKey.p)
    #3.计算s
    s = mod(h, y, elgKey.p)
    #4.对message进行加密
    ciphertext = [(m * s) % (elgKey.p) for m in message]
    print('ciphetext: ', ciphertext)

    #解密过程
    #1.通过c1计算得到s
    de_s = mod(c1, alpha, elgKey.p)
    #2.获得明文
    x, y, r = ex_gcd(elgKey.p, de_s)
    s_reverse = y % (elgKey.p)
    if s_reverse < 0:
        s_reverse += elgKey.p
    plaintext = [(m * s_reverse) % (elgKey.p) for m in ciphertext]
    print('plaintext: ', plaintext)
Ejemplo n.º 6
0
 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'])
Ejemplo n.º 7
0
 def _test_random_key(self, bits):
     elgObj = ElGamal.generate(bits, Random.new().read)
     self._check_private_key(elgObj)
     self._exercise_primitive(elgObj)
     pub = elgObj.publickey()
     self._check_public_key(pub)
     self._exercise_public_primitive(elgObj)
Ejemplo n.º 8
0
    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)
Ejemplo n.º 9
0
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)
Ejemplo n.º 10
0
 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'])
Ejemplo n.º 11
0
    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---')
Ejemplo n.º 12
0
 def _test_random_key(self, bits):
     elgObj = ElGamal.generate(bits, Random.new().read)
     self._check_private_key(elgObj)
     self._exercise_primitive(elgObj)
     pub = elgObj.publickey()
     self._check_public_key(pub)
     self._exercise_public_primitive(elgObj)
Ejemplo n.º 13
0
 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'])
Ejemplo n.º 14
0
 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'])
Ejemplo n.º 15
0
 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"])
Ejemplo n.º 16
0
 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'])
Ejemplo n.º 17
0
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))
Ejemplo n.º 18
0
 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'])
Ejemplo n.º 19
0
 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"])
Ejemplo n.º 20
0
def get_key():
	key = ElGamal.generate(256, get_random_bytes)
	comps = ('p','g','y','x')
	out = '\n'.join(["{} = {}".format(comp,getattr(key, comp)) for comp in comps])
	with open('./key', 'w+') as k:
		k.write(out)
	key.set_key(user, out['y'],out['x'])
	return key
Ejemplo n.º 21
0
    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()))
Ejemplo n.º 22
0
def generate_ElGamal_key(keysize):
    """
    Genera una clave ElGamal del tamaño especificado.

    :param keysize: El tamaño de la clave.

    :returns: Una clave ElGamal.
    """
    return ElGamal.generate(keysize, Random.new().read)
Ejemplo n.º 23
0
def elgamal_reg(usr, name, sex_zh, unit, title):
    
    # Database connection
    conn = MySQLdb.connect(
            host='localhost',
            user='******',
            passwd='123456',
            db='project',
            charset='utf8'
            )

    cur = conn.cursor()
    
    # Gender transfer
    if sex_zh == u'男':
        sex = 0
    elif sex_zh == u'女':
        sex = 1
    
    # Unit transfer  
    sql_unit = "SELECT * FROM unit WHERE unit_name = '%s'" % unit
    cur.execute(sql_unit)
    result_unit = cur.fetchall()
    unitid = result_unit[0][0] 
             
    # Avoid duplication
    sql_search = "SELECT * FROM users WHERE loginid = '%s'" % usr
    
    if cur.execute(sql_search) == 0L:
    
        # Insert into database
        sql = "insert into users(loginid, pass_word, name, sex, unitid, title) values('%s', '', '%s', '%d', '%d', '%s')" % (usr, name, sex, unitid, title) 
        cur.execute(sql)
        conn.commit()
        cur.close()
        conn.close()
        
        # Key generation
        key = ElGamal.generate(256, Random.new().read)

        # Key data
        p = key.p
        g = key.g
        y = key.y
        x = key.x

        
        # Save user's public key
        f = open('auth/elgamal/keys/%s.pub' % usr,'w')
        f.write(str(p) + ' ' + str(g) + ' ' + str(y))
        f.close()  
        
        return 1, p, g, y, x
    
    # Registeration failed
    else:
        return 2, 0, 0, 0, 0
Ejemplo n.º 24
0
def pyCrypto():
    import Crypto
    from Crypto.Cipher import AES, DES, DES3, ARC2, ARC4, Blowfish, CAST, PKCS1_v1_5, PKCS1_OAEP, XOR
    from Crypto.PublicKey import ElGamal

    Crypto.Cipher.AES.new()  # Noncompliant
    Crypto.Other.AES.new()  # OK
    AES.new(key=key)  # Noncompliant
    DES.new(key=key)  # Noncompliant
    DES3.new(key=key)  # Noncompliant
    ARC2.new(key=key)  # Noncompliant
    ARC4.new(key=key)  # Noncompliant
    Blowfish.new(key=key)  # Noncompliant
    CAST.new(key=key)  # Noncompliant
    PKCS1_v1_5.new(key=key)  # Noncompliant
    PKCS1_OAEP.new(key=key)  # Noncompliant
    XOR.new(key=key)  # Noncompliant

    ElGamal.generate(key_size)  # Noncompliant
Ejemplo n.º 25
0
 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)
Ejemplo n.º 26
0
 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)
Ejemplo n.º 27
0
    def keyConstruct(self, args):
        """
        input a tuple of following elements in order
        which satisfy:
     
        """

        key = ElGamal.construct(args)

        return key
Ejemplo n.º 28
0
 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)
Ejemplo n.º 29
0
def generateKeyPair(keySize):
    privateKey = ElGamal.generate(keySize, Random.new().read)
    privateKey.x = int(privateKey.x)
    privateKey.y = int(privateKey.y)
    privateKey.p = int(privateKey.p)
    privateKey.g = int(privateKey.g)
    publicKey = privateKey.publickey()
    publicKey.p = int(publicKey.p)
    publicKey.g = int(publicKey.g)
    return privateKey, publicKey
Ejemplo n.º 30
0
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
Ejemplo n.º 31
0
def generate_elgamal_keypair():
    """Return an ElGamal object with newly generated keypair"""
    if 'SFLVAULT_IN_TEST' in os.environ:
        print "WARNING: IN TEST MODE, EVERY KEYPAIR GENERATION IS BYPASSED AND USES A PRE-GENERATED AND WORLD-KNOWN KEYPAIR. REMOVE 'SFLVAULT_IN_TEST' FROM YOUR ENVIRONMENT IF YOU ARE DOING THIS ON PRODUCTION"
        eg = ElGamal.ElGamalobj()
        keys = [(177089723724552644256797243527295142469255734138493329314329932362154457094059269514887621456192343485606008571733849784882603220703971587460034382850082611103881050702039214183956206957248098956098183898169452181835193285526486693996807247957663965314452283162788463761928354944430848933147875443419511844733534867714246125293090881680286010834371853006350372947758409794906981881841508329191534306452090259107460058479336274992461969572007575859837L, 2368830913657867259423174096782984007672147302922056255072161233714845396747550413964785336340342087070536608406864241095864284199288769810784864221075742905057068477336098276284927890562488210509136821440679916802167852789973929164278286140181738520594891315446533462206307248550944558426698389577513200698569512147125339722576147002382255876258436727504192479647579172625910816774587488928783787624267035610900290120258307919121453927670441700811482181614216947L, 5861471316007038922650757021308043193803646029154275389954930654765928019938681282006482343772842302607960473277926921384673235972813815577111985557701858831111694263179407993690846841997398288866685890418702914928188654979371728552059661796422031090374692580710906447170464105162673344042938184790777466702148445760745296149876416417949678454708511011740073066144877868339403040477747772225977519821312965207L, 1169412825199936698700035513185825593893938895474876750007859746409857305379860678064015124546593449912724002752383066585681624318254362438491372548721947497497739043831382430104856590871057670575051579668363576657397472353061812950884556034822611307705562237354213497368218843244103113882159981178841442771150519161251285978446459307942619668439466357674240712609844734284943761543870187004331653216116937988266963743961096619840352159665738163357566198583064435L),
                (363126185715790250119395282425017818083421673278440118808474954552806007436370887232958142538070938460903011757636551318850215594111019699633958587914824512339681573953775134121488999147928038505883131989323638021781157246124428000084118138446325126739005521403114471077697023469488488105229388102971903306007555362613775010306064798678761753948810755236011346132218974049446116094394433461746597812371697367173395113014824646850943586174124632464143L, 1989666736598081965365973787349938627625613245335951894925228395719349924579514682166704542464221001327015131231101009506582078440087637470784673000661958376397578391397303146171320274531265903747455382524598808613766406694744319576824028880703970997080651320662468590292703565426391011134523391035995750230341849776175803186815053305823053143914398318121693692044542134832809759905437953710838534372887584358442203447387293183908262967797038874535690090799742911L, 133850088107174975861015682594827971956767368440585898108600141692889215241539178575381178799995195531301157505453120993980045956642227472649664668888717884598815932243844750408878011387532720932159839454554017574665882963054750224693505390054364096154711586190837517112644639757613967217614109546151313073865262488626822109764294618345504453742784825659007630866924661811701179640013729327586347L, 742665583685283032188129474839034185107068199926583417281240975739235100098517297493350864258177674271267050862217567671938790648634008735784684115797768392310253433978502694449565453913758801583487678024491118014887051643096970952295790434950566748516670079663712282848262006606082748685002561868381598918739708181310245226480020229450553192469536632519293406262550081671717685585065331112633947328611250435010734072352883491446355872734313855711051794348490960L)]
        eg.g, eg.p, eg.x, eg.y = keys[random.randint(0, 1)]
        return eg
    # Otherwise, generate, really :)
    return ElGamal.generate(1536, randfunc)
Ejemplo n.º 32
0
 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))
Ejemplo n.º 33
0
 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)
Ejemplo n.º 34
0
 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)
Ejemplo n.º 35
0
def pyCrypto():
    import Cryptodome
    from Cryptodome.Cipher import AES, ChaCha20, DES, DES3, ARC2, ARC4, Blowfish, CAST, PKCS1_v1_5, PKCS1_OAEP, ChaCha20_Poly1305, Salsa20
    from Cryptodome.PublicKey import ElGamal

    Cryptodome.Cipher.AES.new()  # Noncompliant
    Cryptodome.Other.AES.new()  # OK
    AES.new(key=key)  # Noncompliant
    ChaCha20.new(key=key)  # Noncompliant
    DES.new(key=key)  # Noncompliant
    DES3.new(key=key)  # Noncompliant
    ARC2.new(key=key)  # Noncompliant
    ARC4.new(key=key)  # Noncompliant
    Blowfish.new(key=key)  # Noncompliant
    CAST.new(key=key)  # Noncompliant
    PKCS1_v1_5.new(key=key)  # Noncompliant
    PKCS1_OAEP.new(key=key)  # Noncompliant
    ChaCha20_Poly1305.new(key=key)  # Noncompliant
    Salsa20.new(key=key)  # Noncompliant

    ElGamal.generate(key_size)  # Noncompliant
Ejemplo n.º 36
0
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']))
Ejemplo n.º 37
0
Archivo: app.py Proyecto: ansjcy/clode
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
Ejemplo n.º 38
0
def keygen(keyfile):
    key = ElGamal.generate(1024, Random.new().read)
    comps_priv = ('p', 'g', 'y', 'x')
    comps_pub = ('p', 'g', 'y')

    out = ",".join(["{}".format(getattr(key, comp)) for comp in comps_priv])
    with open(keyfile, 'w') as key_file:
        key_file.write(out)

    out = ",".join(["{}".format(getattr(key, comp)) for comp in comps_pub])
    with open(keyfile + ".pub", 'w') as key_file:
        key_file.write(out)
Ejemplo n.º 39
0
def generate_elgamal_keypair():
    """Return an ElGamal object with newly generated keypair"""
    if 'SFLVAULT_IN_TEST' in os.environ:
        print "WARNING: IN TEST MODE, EVERY KEYPAIR GENERATION IS BYPASSED AND USES A PRE-GENERATED AND WORLD-KNOWN KEYPAIR. REMOVE 'SFLVAULT_IN_TEST' FROM YOUR ENVIRONMENT IF YOU ARE DOING THIS ON PRODUCTION"
        eg = ElGamal.ElGamalobj()
        keys = [
            (177089723724552644256797243527295142469255734138493329314329932362154457094059269514887621456192343485606008571733849784882603220703971587460034382850082611103881050702039214183956206957248098956098183898169452181835193285526486693996807247957663965314452283162788463761928354944430848933147875443419511844733534867714246125293090881680286010834371853006350372947758409794906981881841508329191534306452090259107460058479336274992461969572007575859837L,
             2368830913657867259423174096782984007672147302922056255072161233714845396747550413964785336340342087070536608406864241095864284199288769810784864221075742905057068477336098276284927890562488210509136821440679916802167852789973929164278286140181738520594891315446533462206307248550944558426698389577513200698569512147125339722576147002382255876258436727504192479647579172625910816774587488928783787624267035610900290120258307919121453927670441700811482181614216947L,
             5861471316007038922650757021308043193803646029154275389954930654765928019938681282006482343772842302607960473277926921384673235972813815577111985557701858831111694263179407993690846841997398288866685890418702914928188654979371728552059661796422031090374692580710906447170464105162673344042938184790777466702148445760745296149876416417949678454708511011740073066144877868339403040477747772225977519821312965207L,
             1169412825199936698700035513185825593893938895474876750007859746409857305379860678064015124546593449912724002752383066585681624318254362438491372548721947497497739043831382430104856590871057670575051579668363576657397472353061812950884556034822611307705562237354213497368218843244103113882159981178841442771150519161251285978446459307942619668439466357674240712609844734284943761543870187004331653216116937988266963743961096619840352159665738163357566198583064435L
             ),
            (363126185715790250119395282425017818083421673278440118808474954552806007436370887232958142538070938460903011757636551318850215594111019699633958587914824512339681573953775134121488999147928038505883131989323638021781157246124428000084118138446325126739005521403114471077697023469488488105229388102971903306007555362613775010306064798678761753948810755236011346132218974049446116094394433461746597812371697367173395113014824646850943586174124632464143L,
             1989666736598081965365973787349938627625613245335951894925228395719349924579514682166704542464221001327015131231101009506582078440087637470784673000661958376397578391397303146171320274531265903747455382524598808613766406694744319576824028880703970997080651320662468590292703565426391011134523391035995750230341849776175803186815053305823053143914398318121693692044542134832809759905437953710838534372887584358442203447387293183908262967797038874535690090799742911L,
             133850088107174975861015682594827971956767368440585898108600141692889215241539178575381178799995195531301157505453120993980045956642227472649664668888717884598815932243844750408878011387532720932159839454554017574665882963054750224693505390054364096154711586190837517112644639757613967217614109546151313073865262488626822109764294618345504453742784825659007630866924661811701179640013729327586347L,
             742665583685283032188129474839034185107068199926583417281240975739235100098517297493350864258177674271267050862217567671938790648634008735784684115797768392310253433978502694449565453913758801583487678024491118014887051643096970952295790434950566748516670079663712282848262006606082748685002561868381598918739708181310245226480020229450553192469536632519293406262550081671717685585065331112633947328611250435010734072352883491446355872734313855711051794348490960L
             )
        ]
        eg.g, eg.p, eg.x, eg.y = keys[random.randint(0, 1)]
        return eg
    # Otherwise, generate, really :)
    return ElGamal.generate(1536, randfunc)
Ejemplo n.º 40
0
 def initiate_DH(self):
     # send first DH parameter to all users
     print 'Generating Diffie-Hellman parameters'
     self.DH_params = ElGamal.generate(p_size, Random.new().read)
     print 'Generated'
     params_string = str(self.DH_params.y) + '|' + str(
         self.DH_params.g) + '|' + str(self.DH_params.p)
     DH_msg1 = DH_INIT + '|' + params_string
     self.process_outgoing_message(msg_raw=DH_msg1,
                                   originates_from_console=False)
     self.symm_key = number.long_to_bytes(
         random.StrongRandom().getrandbits(128))
     self.save_symm_key()
Ejemplo n.º 41
0
def generate_elgamal(klength, privatekey):
    key = ElGamal.generate(klength, Random.new().read)
    h = SHA.new(privatekey).digest()
    while 1:
        k = random.StrongRandom().randint(1,key.p-1)
        if GCD(k, key.p-1) == 1: break
    sig = key.sign(h,k)
    if key.verify(h,sig):
        print "OK"
        return key, h , sig
    else:
        print "Incorrect signature"
        return None
Ejemplo n.º 42
0
    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---')
Ejemplo n.º 43
0
def make_key_objects(pub_algorithm_type, key_size):
    if pub_algorithm_type == 17:
        secret_key = DSA.generate(key_size)
    elif pub_algorithm_type in (1, 3):
        secret_key = RSA.generate(key_size)
    elif pub_algorithm_type == 20:
        # TODO: This should not be allowed except for testing purposes.
        # XXX: This can take a really long time
        secret_key = ElGamal.generate(key_size, Random.new().read)
    else:
        # TODO: complete
        raise ValueError

    public_key = secret_key.publickey()
    return secret_key, public_key
Ejemplo n.º 44
0
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?
Ejemplo n.º 45
0
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
Ejemplo n.º 46
0
    def subscribe(self):
        print "Subscribing please wait..."
        self.rsa = RSA_gen(4096)
        self.n, self.e, self.d = RSA_keys(self.rsa)
        self.ElGkey = ElGamal.generate(256, Random.new().read)

        self.rsa_sign = RSA_gen(1024)
        self.n_sign, self.e_sign, self.d_sign = RSA_keys(self.rsa_sign)

        self.ust = UST(self.server_pk_n, self.server_pk_e)
        self.ust_lock.acquire()
        self.ust.prepare()

        args = {"blinded_nonce"     :  self.ust.blinded_nonce, 
                "client_username"   :  self.username,
                "client_pk_n"       :  self.n, 
                "client_pk_e"       :  self.e,
                "client_sign_pk_n"  :  self.n_sign,
                "client_sign_pk_e"  :  self.e_sign}
        
        r = send_request(SUBSCRIBE, args)

        if r == ERROR:
            print "ERROR: could not subscribe"
            sys.exit(0)

        self.ust.receive(r['blinded_sign'])
        self.ust_lock.release()

        user = r['user']

        if user['client_pk_n'] == self.n and user['client_pk_e'] == self.e \
            and user['client_sign_pk_n'] == self.n_sign \
            and user['client_sign_pk_e'] == self.e_sign:
            pass
        else:
            print "Username is taken, please try again"
            sys.exit(0)

        self.user_id = user['client_user_id']
        self.user_table_ptr = 0
        self.client_new_conversations_table_ptr = 0

        return
Ejemplo n.º 47
0
 def _construct(y, x=None):
     tup = (elgamal_p, elgamal_g, y, x) if x else (elgamal_p, elgamal_g, y)
     return ElGamal.construct(tup)
Ejemplo n.º 48
0
from Crypto.PublicKey import ElGamal
from Crypto import Random

import cPickle as Pickle

v_priv_key = ElGamal.generate(128, Random.new().read)
v_pub_key = v_priv_key.publickey()

s_priv_key = ElGamal.generate(128, Random.new().read)
s_pub_key = s_priv_key.publickey()

Pickle.dump(v_priv_key, open("vending_key.priv", 'w'))
Pickle.dump(v_pub_key, open("vending_key.pub", 'w'))
Pickle.dump(s_priv_key, open("server_key.priv", 'w'))
Pickle.dump(s_pub_key, open("server_key.pub", 'w'))
Ejemplo n.º 49
0
def getpk(key):
    tup = tuple(map(int, (key['p'], key['g'], key['y'])))
    pk = ElGamal.construct(tup)
    pk.q = int(key['q'])

    return pk
Ejemplo n.º 50
0
 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'])
Ejemplo n.º 51
0
def generate_elgamal_keypair():
    """Return an ElGamal object with newly generated keypair"""
    return ElGamal.generate(1536, randfunc)
Ejemplo n.º 52
-1
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))
Ejemplo n.º 53
-1
 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'])
Ejemplo n.º 54
-1
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)
Ejemplo n.º 55
-1
 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"])
Ejemplo n.º 56
-1
 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'])
Ejemplo n.º 57
-2
 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'])