Example #1
0
def RSA_key_generation(p,q, identity = 'Alice', filename = 'private_key.txt'): 
    N = p * q
    phi_N = (p - 1) * (q - 1)
    e = random.randrange(0, phi_N) # public key
    while True:
        if check_relatively_prime(e, phi_N):
            break
        else:
            e = random.randrange(0, phi_N)
    # e = 65537   
    if check_relatively_prime(e, phi_N) == False:
        print "This e doesnot work"
    d = Ext_Euclidean(e, phi_N) # private key
    # use the private key to sign the public key
    try:
        with open('private_key.txt','r') as infile: # use the private key from file to sign public key
            private_key = file.readlines()
            private_key = int(private_key, 16)
            file.close()
            signature = pow(d, private_key, N)
            signature = hex(signature)
            signature = signature[2:-1]
    except IOError: # file do not exist, use the own private key to sign public key
        signature = pow(e, d, N)
        signature = hex(signature)
        signature = signature[2:-1]
    return N, phi_N, d, e, identity, signature
Example #2
0
def encryptOracle(text):
    from Crypto.Random import random

    preCnt = random.randrange(5,10)
    postCnt = random.randrange(5,10)
    
    text = randNumBytes(preCnt) + text + randNumBytes(postCnt)
    blob = Blob()
    blob.fromStr(text)
    
    
    print len(blob.tostring())
    blob.pkcs7(AES.block_size)
    print len(blob.tostring())
    
    key = randNumBytes(AES.block_size)
    iv  = randNumBytes(AES.block_size)
    
    choice = random.randrange(0,1) 
    if choice == 0:
        ret = encryptCBC(key, iv, blob.tostring())
    else:
        ret = encryptECB(key, blob.tostring())
    
    return ret
Example #3
0
def random_result(votes, num, g, h, p):
    vote_g = []
    vote_p = []
    hash_g = []
    hash_p = []
    for i in range(num):
        vote_g_i = []
        vote_p_i = []
        hash_g_i = []
        hash_p_i = []
        for j in range(len(votes)):
            len_j = len(votes[j])
            ran = random_int.randint(0, len_j - 1)
            m_str = votes[j][ran]
            m = Utils.str_to_message(m_str)
            hm = CryptoHash.get_hash(m, p)
            r = random.randrange(2, p)
            s = random.randrange(2, p)
            vote_g_i.append(pow(g, r, p))
            vote_p_i.append(pow(h, r, p) * m % p)
            hash_g_i.append(pow(g, s, p))
            hash_p_i.append(pow(h, s, p) * hm % p)
        vote_g.append(vote_g_i)
        vote_p.append(vote_p_i)
        hash_g.append(hash_g_i)
        hash_p.append(hash_p_i)
    return [vote_g, vote_p, hash_g, hash_p]
Example #4
0
def randomize_location(lat, lon):
    """randomize location"""
    rnd1 = float("0."+"".join(str(random.randrange(10)) for x in range(32)))
    rnd2 = float("0."+"".join(str(random.randrange(10)) for x in range(32)))
    d_min = 100 # meters
    d_max = 700 # meters
    gamma = 6.35e-6 # meters^-1
    angle = -180 + 360 * rnd1 # degrees
    distance = d_min + (d_max - d_min) * rnd2 # meters

    # don't move when we are at the poles
    if -89 < lat < 89:
        lat = lat + distance * gamma * \
            (1 + (sin(lat))** 2) * sin(angle)
        lon = lon + distance * gamma * \
            (1 + (sin(lat)) ** 2) * cos(angle) / cos(lat)

    # take care at the edges - avoid invalid values
    if lat > 90:
        lat = 90 - ( lat - 90 )
    elif lat < -90:
        lat = -90 - ( lat - (-90) )
    if lon < -180:
        lon += 360
    elif lon > 180:
        lon -= 360

    return lat, lon
Example #5
0
def encrypt(data, pk):
	n, y = pk
	u = randrange(n)
	a = randrange(n)
	c = randrange(n)
	for m in data.hex():
		yield pow(y, int(m, 16), n) * pow(u, r, n) % n
		u = (a*u + c) % n
Example #6
0
def genkey(k):
    p = getPrime(k)
    g = random.randrange(2, p)
    x = random.randrange(1, p - 1)
    h = pow(g, x, p)
    pk = (p, g, h)
    sk = (p, x)
    return (pk, sk)
Example #7
0
def you_thought_it_was_rsa_encryption_but_it_was_me_dio(data, n, e):
	m = randrange(n)
	a = randrange(m)
	b = randrange(m)
	nonce = randrange(m)

	for d in data.hex():
		yield pow(e, int(d, 16), n) * pow(nonce, -1, n) % n
		nonce = (a*nonce + b) % m
Example #8
0
def RandText():
    # Returns a random piece of text.
    words = random.randrange(1, 99)
    txt = []
    for i in range(words):
        # Word length.
        L = random.randrange(1, 99)
        txt.append(Random.new().read(L))
    return b' '.join(txt)
Example #9
0
def RandText():
    # Returns a random piece of text.
    words = random.randrange(1, 99)
    txt = []
    for i in range(words):
        # Word length.
        L = random.randrange(1, 99)
        txt.append(Random.new().read(L))
    return b' '.join(txt)
Example #10
0
def RandPassword():
    # Returns a random password between 1 and 196.
    L = random.randrange(3, 196)
    pwd = []
    for i in range(L):
        # From 'space' to '~'.
        pwd.append( chr(random.randrange(32, 126)).encode() )
    pwd = ''.join(pwd)
    L = len(pwd)
    return pwd
Example #11
0
def RandPassword():
    # Returns a random password between 1 and 128.
    L = random.randrange(1, 128)
    pwd = []
    for i in range(L):
        # From 'space' to '~'.
        pwd.append(chr(random.randrange(32, 126)).encode())
    pwd = b''.join(pwd)
    L = len(pwd)
    return pwd
Example #12
0
def perhaps_rsa_keygen():
	p, q = [getPrime(1024) for _ in range(2)]

	n = p*q
	phi = (p-1)*(q-1)

	e = randrange(n)
	while gcd(e, phi) != 1:
		e = randrange(n)

	return (n, e), (n, pow(e, -1, phi))
def millerRabin(p):
    i=0
    while (p > (1<<i)):
        i+=1
    for k in range(0,10):
        n=random.randrange(1<<i)
        while(euclid(n,p)[0]!=1):
            n=random.randrange(1<<i)
        if modifiedPower(n,(p-1),p) != 1:
            return False
    
    return True
Example #14
0
def encryption_oracle(plaintext: bytes) -> bytes:
    plaintext = bytes(randrange(5, 11)) + plaintext + bytes(randrange(5, 11))
    plaintext = pkcs7(plaintext)

    key = get_random_bytes(16)

    if randrange(2) == 0:
        iv = get_random_bytes(16)
        return encrypt_aes_cbc(key, iv, plaintext)

    cypher = AES.new(key, AES.MODE_ECB)
    return cypher.encrypt(plaintext)
Example #15
0
def encryption_oracle(data):
    rndfile = Random.new()
    mode = random.choice([AES.MODE_ECB, AES.MODE_CBC])
    if mode == AES.MODE_ECB:
        print("Using ECB!")
        crypt = AES.new(rndfile.read(16), mode)
    else:
        print("Using CBC!")
        crypt = AES.new(rndfile.read(16), mode, rndfile.read(16))

    plaintext = rndfile.read(random.randrange(5, 10)) + data + rndfile.read(
        random.randrange(5, 10))
    return crypt.encrypt(pad_pkcs7(plaintext, 16))
Example #16
0
    def __init__(self, prime: int, generator: int, username: str,
                 password: str) -> None:
        self.n = prime
        self.g = generator
        self.I = username

        self.salt = randrange(64)

        self._x = self._integer_hash(self.salt, password)
        self.v = pow(self.g, self._x, self.n)

        self._a = randrange(self.n)
        self.A = pow(self.g, self._a, self.n)
Example #17
0
def make_key_pair(p, q):
    N = p * q
    phi_N = (p - 1) * (q - 1)

    e = random.randrange(0, phi_N)
    while True:
        if check_relatively_prime(e, phi_N):
            break
        else:
            e = random.randrange(0, phi_N)
    # e = 65537
    if check_relatively_prime(e, phi_N) == False:
        print "This e doesnot work"
    d = Ext_Euclidean(e, phi_N)
    return N, phi_N, d, e
Example #18
0
def assigning_keys(p,q, identity = 'Alice'): 
    N = p * q
    phi_N = (p - 1) * (q - 1)
    e = random.randrange(0, phi_N) # public key
    while True:
        if check_relatively_prime(e, phi_N):
            break
        else:
            e = random.randrange(0, phi_N)
    if check_relatively_prime(e, phi_N) == False:
        print "This e doesnot work"
    d = Ext_Euclidean(e, phi_N) # private key
    p = {"identity":identity, "public_key": e, "private_key": d, "order": N}
    people.append(p)
    return e , d, N
Example #19
0
def encrypt(pk, path="message.txt",saveCT="ciphertext.enc"):
    # Generate random x in Zn
    x = random.randrange(2, (pk.n)-1) #random x in Zn
    # Calculate y = RSA(x) as x^e mod N
    y = pow(x, pk.e, pk.n) #y to send with ciphertext
    # Compute symmetric key with Hash function (SHA224)
    k = SHA224.new(repr(x).encode('utf-8')).hexdigest().encode('utf-8') #symmetric key for compute the ciphertext
    print("K: "+str(k))

    # Open file plaintext to cipher
    plaintext = open(path,"rb").read()

    # Count block_size
    bs = Blowfish.block_size
    # Generate a random init vector
    iv = Random.new().read(bs)
    # Initialize Blowfish cipher
    cipher = Blowfish.new(k, Blowfish.MODE_CBC, iv)
    # Calculate Plaintext for padding
    plen = bs - divmod(len(plaintext),bs)[1]
    # Add padding
    padding = [plen]*plen
    padding = struct.pack('b'*plen,*padding)
    # Encrypt adding IV
    ciphertext = iv + cipher.encrypt(plaintext+padding)

    # Save ciphertext to file:
    print("CT-LEN:"+str(len(ciphertext)))
    with open(saveCT, 'wb') as output:
        dill.dump(y, output)
        dill.dump(ciphertext, output)

    return plaintext, ciphertext
Example #20
0
def encrypt(pk, m, r=None):
    (p, g, h) = pk
    if r is None:
        r = random.randrange(1, p - 1)
    c1 = pow(g, r, p)
    c2 = (m * pow(h, r, p)) % p
    return (c1, c2)
Example #21
0
def key_matrix_generator_Bob(public_key,array_of_images):
    """Key Matrix Generator"""
    key=ECC.import_key(public_key) #importing private key from Alice
    Q=key.pointQ
    P=ECC.EccPoint(x=key._curve.Gx,y=key._curve.Gy, curve='P-256')
    n=32
    k_b = (random.randrange(2**(n-1)+1, 2**n - 1) )
    k_c = (random.randrange(2**(n-1)+1, 2**n - 1))
    ##note call the proper definition, 
    R=k_b*P
    S=k_c*P
    K_0 = k_b*Q
    L = k_c*Q
    K_M=key_matrix_generator(K_0,L,array_of_images)
      # np.savetxt("Matrix.txt",(K_M))
    return K_M,R,S
Example #22
0
    def encrypt(self, s, mac=16):
        """Encrypt a message for private viewing by the holder of the
        Private Key
        """
        # nonce is essentially a secret on the encrypter's side
        # this is a secret exponent < 2^256
        nonce = randrange(1, self.curve().p())
        tmp = BasePoint * nonce
        nonce_point = PubKey(tmp.curve(), tmp.x(), tmp.y())
        tmp = self * nonce
        shared_secret = PubKey(tmp.curve(), tmp.x(), tmp.y())

        # derive a key for making a cipher and checksum using the
        # nonce point and shared secret
        key = nonce_point.kdf(shared_secret)

        # encode the nonce point into the message as the beginning
        header = nonce_point.sec()

        # encrypt the actual message using the AES cipher
        cipher = AES.new(key[:32])
        # because we're using AES block mode, we need multiples of 16
        s = s + '\x00' * (16 - len(s) % 16)
        message = cipher.encrypt(s)

        # add a checksum for validation
        checksum_maker = hmac.new(key[32:], digestmod=hashlib.sha256)
        checksum_maker.update(message)
        checksum = checksum_maker.digest()[:mac]
        return header + message + checksum
Example #23
0
def encrypt(key, path="message.txt", saveCT="ciphertext.enc"):
    b = random.randrange(2, (key.p)-1)
    u = modexp(key.g, b, key.p)
    v = modexp(key.h, b, key.p)

    uv = str(u)+str(v)
    k = SHA224.new(uv.encode('utf-8')).hexdigest().encode('utf-8') #symmetric key for compute the ciphertext with AES
    print("K: "+str(k))

    # Open file plaintext to cipher
    plaintext = open(path,"rb").read()
    #plaintext = encode(plaintext, key.iNumBits)

    bs = Blowfish.block_size
    iv = Random.new().read(bs)
    cipher = Blowfish.new(k, Blowfish.MODE_CBC, iv)
    plen = bs - divmod(len(plaintext),bs)[1]
    padding = [plen]*plen
    padding = struct.pack('b'*plen,*padding)
    ciphertext = iv + cipher.encrypt(plaintext+padding)

    # Save ciphertext to file:
    print("CT-LEN:"+str(len(ciphertext)))
    with open(saveCT, 'wb') as output:
        dill.dump(u, output)
        dill.dump(ciphertext, output)

    return plaintext, ciphertext
Example #24
0
	def encrypt(self,m):
		if type(m) == str:
			m = int(m)
			
		assert Aux.is_int(m)

		pub = Cipher.get_public_key(self)
		assert pub.has_key("n")
		assert pub.has_key("g")

		n = pub["n"]
		n2 = n*n if not pub.has_key("n2") else pub["n2"]
		if not pub.has_key("n2"):
			pub["n2"] = n2
		g = pub["g"]
		r = pub["r"] if pub.has_key("r") else random.randrange(1,n)

		assert abs(m) < n		

		if m < 0:
			g_m__n2 = self.__modinv(pow(g,-m,n2),n2)
		else:
			g_m__n2 = pow(g,m,n2)

		c = g_m__n2*pow(r,n,n2) % n2
		return str(c)
Example #25
0
def genkey():
    while True:
        p = 2
        while size(p) < 512:
            p *= getPrime(randrange(2, 12))
        if isPrime(p + 1):
            return p + 1
Example #26
0
    def __init__(self, ip, port, client_nr, clientsocket):
        threading.Thread.__init__(self)
        self.ip = ip
        self.port = port
        self.client_nr = client_nr

        self.csocket = clientsocket

        key = Key()
        self.server_secret = randrange(0, key.q - 1)
        self.shared_prime = key.p
        self.shared_base = key.g
        self.server_DHside = pow(self.shared_base, self.server_secret,
                                 self.shared_prime)

        # Everything is set after establishing session key
        self.sessionKey = 0
        self.enc_key = 0
        self.auth_key = 0

        self.enc = 0
        self.dec = 0
        self.ehmac = 0
        self.dhmac = 0

        self.nonce_iv = 0
        self.nrseq = 0

        print("[+] New thread started for " + ip + ":" + str(port))
Example #27
0
def initializeGame():
    all_players = []
    for player in PLAYERS_COLLECTION.find():
        all_players.append(player)
        
    needed_werewolves = len(all_players) / 3
    
    count = 0
    rand_number_list = []
    while count != needed_werewolves:
        rand = randrange(0, len(all_players))
        if rand in rand_number_list:
            continue
        else:
            rand_number_list.append(rand)
            count += 1
            
    for i in rand_number_list:
        cur_player_id = (all_players[i])["userID"]
        playerDAO.updatePlayer(cur_player_id, "alignment", "Werewolf")
    
    if count > 0:
        GAMES_COLLECTION.update({}, {"$set": {"isActive": True}})
        return True
    else:
        return False
Example #28
0
def encryption_oracle(plaintext):
    plaintext = bytes(randrange(5, 11)) + plaintext + bytes(randrange(5, 11))
    plaintext = pkcs7(plaintext, 16)

    key = bytes(getrandbits(8) for i in range(16))

    if randrange(0,2) == 0:
        iv = bytes(getrandbits(8) for i in range(16))
        cyphertext = encrypt_aes_cbc(plaintext, key, iv)
        #print("CBC")
    else:
        cypher = AES.new(key, AES.MODE_ECB)
        cyphertext = cypher.encrypt(plaintext)
        #print("ECB")

    return cyphertext
Example #29
0
def is_prime(n, k=128):
    """ Test if a number is prime        
        Args:
            n -- int -- the number to test
            k -- int -- the number of tests to do        
    return True if n is prime
    """
    # Test if n is not even.
    # But care, 2 is prime !
    if n == 2 or n == 3:
        return True
    if n <= 1 or n % 2 == 0:
        return False
    # find r and s
    s = 0
    r = n - 1
    while r & 1 == 0:
        s += 1
        r //= 2
    # do k tests
    for _ in range(k):
        a = random.randrange(2, n - 1)
        x = pow(a, r, n)
        if x != 1 and x != n - 1:
            j = 1
            while j < s and x != n - 1:
                x = pow(x, 2, n)
                if x == 1:
                    return False
                j += 1
            if x != n - 1:
                return False    

    return True
Example #30
0
def generate_prime(num_bits):
    k = num_bits
    i = 0
    prime_less_than_1000 = [
        2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67,
        71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139,
        149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223,
        227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293,
        307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383,
        389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
        467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569,
        571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647,
        653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743,
        751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839,
        853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
        947, 953, 967, 971, 977, 983, 991, 997
    ]
    while True:
        p = random.randrange(2**(k - 1), 2**(k))
        check = 0
        for i in prime_less_than_1000:
            if p % i == 0:
                check = 1
        # i = i+1
        if check == 0:
            prime_number_p = prime_test(p)
            if prime_number_p == True:
                #print i
                return p
Example #31
0
 def do_rerand(self, arg: CipherValue,
               public_key: List[int]) -> Tuple[List[int], List[int]]:
     # homomorphically add encryption of zero to re-randomize
     r = randrange(babyjubjub.CURVE_ORDER)
     enc_zero = CipherValue(self._enc_with_rand(0, r, public_key),
                            params=arg.params)
     return self.do_op('+', public_key, arg, enc_zero), [r]
Example #32
0
def create_dh_key():
    # Creates a Diffie-Hellman key
    # Returns (public, private)
	g = 2
	priv = random.randrange(1, prime-1)
	pub = pow(g, priv, prime)
	return (pub, priv)
Example #33
0
    def hashSign(self, m, vi, l1, delta, si):
        # Not used currently, but could be used to verify token parts are valid
        """
        H'(m)
        :param: m  - message (plaintext)
        :param: vi  - verification key share
        :param: l1 - Secondary security parameter
        :param: delta  - n factorial 
        :param: si - secret share
        :returns: (z,c) - pair
        """
        x = self.hash(m)
        r = randrange(0, pow(2, int.bit_length(self.N) + 2 * l1))
        vprime = pow(self.v, r, self.N)
        xtilde = pow(x, 4 * delta, self.N)
        xprime = pow(xtilde, r, self.N)
        xi = pow(x, 4 * delta * si, self.N)

        b = SHAKE256.new()
        # Via Shoup p.215,
        b.update(bytes(self.v % self.N))
        b.update(bytes(xtilde))
        b.update(bytes(vi % self.N))
        b.update(bytes(xi % self.N))
        b.update(bytes(vprime))
        b.update(bytes(xprime))
        c = int(hexlify(b.read(l1)), 16) % self.N
        z = c * si + r

        return (z, c)
Example #34
0
 def generate_rand_poly(self, round):
     if self.is_member == False:
         raise ValueError('attribute is_member is false')
     coeffs = [randrange(CURVE_ORDER) for i in range(self.threshold)]
     coeffs = [
         self.si,
     ] + coeffs
     self.poly_dict[round] = IntPoly(coeffs)
Example #35
0
    def __init__(self, mod):
        # Mod should be a prime number
        while not sympy.isprime(mod):
            mod -= 1
            if mod == 1:
                print("You done messed up good")
                raise Exception

        a = v = 100
        while math.gcd(a, v) != 1:
            a = random.randrange(mod)
            v = random.randrange(mod)

        self.a = a
        self.v = v
        self.mod = mod
        self.counter = 0
Example #36
0
def testsys(obj):

    plain = random.randrange(0, obj.n)
    plain_enc = obj.encrypt(plain)
    plain_dec = obj.decrypt(plain_enc)

    if (plain_dec == plain):
        print("Encryption and Decryption work")
    else:
        print("Error in encryption or decryption")

    plain2 = random.randrange(0, obj.n)
    plain2_enc = obj.encrypt(plain2)
    plain2_dec = obj.decrypt(plain2_enc)

    sec_add = obj.secure_addition(plain_enc, plain2_enc)
    sec_add_dec = obj.decrypt(sec_add)

    if (sec_add_dec == (plain + plain2) % obj.n):
        print("Secure additon works")
    else:
        print("Error in secure addition")

    scalar = random.randrange(0, obj.n)
    sec_mul = obj.secure_scalar_multiplication(plain_enc, scalar)
    sec_mul_dec = obj.decrypt(sec_mul)

    if (sec_mul_dec == (plain * scalar) % obj.n):
        print("Secure Scalar Multiplication Works")
    else:
        print("Error in secure scalar multiplication")

    if (plain > plain2):
        sec_sub = obj.secure_subtraction(plain_enc, plain2_enc)
        dif = plain - plain2
    else:
        sec_sub = obj.secure_subtraction(plain2_enc, plain_enc)
        dif = plain2 - plain

    sec_sub_dec = obj.decrypt(sec_sub)

    if (sec_sub_dec == dif):
        print("Secure subtraction works")
    else:
        print("Error in secure subtraction")
def generate_prime():
    while 1:
        q=random.randrange(1<<512)
        if millerRabin(q):
            break
    while 1:
        k=random.randrange(1<<10)
        if millerRabin(k*q+1):
            p=q*k+1;
            break
    while 1:
        h=random.randrange(2,p)
        if modifiedPower(h,(p-1)/q,p)!=1:
            g=modifiedPower(h,(p-1)/q,p)
            break
    
    return g,p,q
    
Example #38
0
    def receive_pubkey(self, I: str, A: int) -> dict[str, int]:
        self.client[I]["A"] = A
        self.client[I]["u"] = randrange(16)

        return {
            "s": self.client[I]["s"],
            "B": pow(self.g, self._b, self.n),
            "u": self.client[I]["u"]
        }
Example #39
0
def genkey():
    g = 2
    while True:
        p = 2
        for _ in range(50):
            p *= getPrime(randrange(38, 42))
        if isPrime(p + 1):
            if pow(g, p // 2, p + 1) == p:
                return g, p + 1
Example #40
0
def random_string(length=-1, charset=string.ascii_letters):
    """
    Returns a random string of "length" characters.
    If no length is specified, resulting string is in between 6 and 15 characters.
    A character set can be specified, defaulting to just alpha letters.
    """
    if length == -1: length = random.randrange(6, 16)
    random_string = ''.join(random.choice(charset) for x in range(length))
    return random_string
Example #41
0
 def __init__(self, username, password, **kwargs):
     super(UserModel, self).__init__(**kwargs)
     salt = get_random_bytes(randrange(96, 128)).hex()
     self.username = username
     self.password = SHA256.new(password.encode() +
                                salt.encode()).hexdigest()
     self.salt = salt
     db.session.add(self)
     db.session.commit()
Example #42
0
def RandPassword():
    # Returns a random password between 1 and 196.
    L = random.randrange(1, 19)
    pwd = []
    for i in range(L):
        pwd.append(random.choice('0123456456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'))
    pwd = b''.join(pwd)
    L = len(pwd)
    return pwd
Example #43
0
def random_string(length=-1, charset=string.ascii_letters):
    """
    Returns a random string of "length" characters.
    If no length is specified, resulting string is in between 6 and 15 characters.
    A character set can be specified, defaulting to just alpha letters.
    """
    if length == -1: length = random.randrange(6,16)
    random_string = ''.join(random.choice(charset) for x in range(length))
    return random_string
Example #44
0
 def __init__(self, stm=None, stp=None, S=None):
     if stm or stp:
         self._stm = stm
         self._stp = stp
     else:
         Krsa = _RSA.generate(self._size)
         S = S or _random.randrange(3, Krsa.n)
         assert 3 <= S <= Krsa.n
         self._stm = None
         self._stp = self._STP(Krsa.n, Krsa.e, Krsa.d, S)
 def __remove_corrupt_machine_guid_xattr(self, fd, xattr_name):
     try:
         fremovexattr(fd, xattr_name)
     except OSError as e:
         if e.errno in ENOATTR_LIST:
             TRACE('!! Corrupt local guid xattr already gone! (probably racing)')
             sleeptime = random.randrange(100, 501) / 1000.0
             TRACE('!! Sleeping %d ms before restarting to avoid colliding with other instances', sleeptime * 1000)
             raise RaceDetected
         elif e.errno == errno.EACCES:
             TRACE("!! Can't remove corrupt local guid xattr: access denied")
             raise
         else:
             unhandled_exc_handler()
             raise
     else:
         sleeptime = random.randrange(50, 201) / 1000.0
         TRACE('!! Sleeping %d ms before continuing to avoid colliding with other instances', sleeptime * 1000)
         time.sleep(sleeptime)
    def report_client_timing(self, timing_report):
        url = timing_report['url'].split('?')[0]
        percent = min(self.timing_report_percent_url.get(url, 100), REPORT_PERCENT_URL.get(url, 100), self.timing_report_percent)
        if percent == 0:
            return
        if percent < 100:
            if random.randrange(10000) >= percent * 100:
                return
        if url in ('retrieve_batch', 'retrieve_batch_parallel', 'store_batch', 'store_batch_parallel'):
            for limit in ('download_hash_batch_max', 'download_hash_batch_max_size', 'download_hash_batch_parallel_connections', 'upload_hash_batch_max', 'upload_hash_batch_max_size', 'upload_hash_batch_parallel_connections'):
                timing_report[limit] = self.dropbox_app.sync_engine.server_limits.get(limit)

        report('timing', **timing_report)
Example #47
0
def randnum(x, y):
    """
    Generate a random int between x (inclusive) and y (exclusive)

    Args:
        x (int): inclusive lower bound
        y (int): exclusive upper bound

    Returns:
        int: random number
    """
    assert isinstance(x, int)
    assert isinstance(y, int)
    assert y - x < 2147483648, "Range too large" # 2 ** 31
    return random.randrange(x, y)
Example #48
0
def cryptString(secret, plain):
    '''只有CM在使用,以后不要再使用'''
    obj = Blowfish.new(secret, Blowfish.MODE_ECB)
    randstring = str.join(
        '', random.sample('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890', 12))
    split = random.randrange(10) + 1
    s = randstring[:split] + ':valid:' + plain + ':valid:' + randstring[split:]
    length = len(s)

    l = length + 8 - (length % 8)
    padded = s + " " * (8 - length % 8)

    ciph = obj.encrypt(padded[:l])
    try:
        return b32encode(ciph)
    except NameError:
        return encodestring(ciph)
Example #49
0
def generate_keys(prime = None, generator = None):
    """
     generates the private and public keys according to the Diffie-Hellman Protocol.
    
     Generates the public and private keys according to the Diffie-Hellman Protocol.
     The number q used to generate the private key is (prime - 1) / 2,
     i.e a n-1-bit number, this definition is taken from RFC 2412
    """  
    
    if prime is None:
        prime = return_prime()
    if generator is None:
        generator = 2
    
    q = (prime - 1) // 2
    private_key = random.randrange(1, q)
    public_key = pow(generator, private_key, prime)
    
    return private_key, public_key
Example #50
0
def gen_masterpwd(length=128, public=None):
    """ Generates a random masterkey password and optionaly encrypt it

    Keywords arguments:
    length      -- The length of the masterkey password we want (default 128)
    public      -- The public key file to use to encrypt the masterkey password (default None)
    """

    items = string.printable.replace(' ', '')
    master = []

    for i in range(length):
        master.append(items[rand.randrange(0, len(items))])

    symbols = "".join(rand.sample(string.punctuation, 2))
    master.append(symbols)

    master = "".join(master)

    if public is not None:
        try:
            pub_file = open(public, 'r')

        except Exception as err:
            log.error("[gen_masterpwd] {}".format(err))

        else:
            pub_key = pub_file.read()
            rsa_key = rsa.importKey(pub_key)
            cipher = pkcs.new(rsa_key)
            try:
                ciph = cipher.encrypt(master.encode('utf-8'))
            except Exception as err:
                log.error("[gen_masterpwd] Error while encrypting the master password : {}".format(err))
            else:
                return base64.b64encode(ciph)
        finally:
            pub_file.close()

    else:
        return master
Example #51
0
 
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done = True # Flag that we are done so we exit this loop
 
    # Set the screen background
    screen.fill(BLACK)
 
    # Process each snow flake in the list
    for i in range(len(snow_list)):
     
        # Draw the snow flake
        pygame.draw.circle(screen, WHITE, snow_list[i], 2)
         
        # Move the snow flake down one pixel
        snow_list[i][1] += randrange(1,5)
         
        # If the snow flake has moved off the bottom of the screen
        if snow_list[i][1] > 400:
            # Reset it just above the top
            y = random.randrange(-50, -10)
            snow_list[i][1] = y
            # Give it a new x position
            x = random.randrange(0, 400)
            snow_list[i][0] = x
             
    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()
    clock.tick(20)
             
# Be IDLE friendly. If you forget this line, the program will 'hang'
Example #52
0
 def runTest(self):
     """Crypto.Random.new()"""
     # Import the Random module and try to use it
     from Crypto import Random
     randobj = Random.new()
     x = randobj.read(16)
     y = randobj.read(16)
     self.assertNotEqual(x, y)
     z = Random.get_random_bytes(16)
     self.assertNotEqual(x, z)
     self.assertNotEqual(y, z)
     # Test the Random.random module, which
     # implements a subset of Python's random API
     # Not implemented:
     # seed(), getstate(), setstate(), jumpahead()
     # random(), uniform(), triangular(), betavariate()
     # expovariate(), gammavariate(), gauss(),
     # longnormvariate(), normalvariate(),
     # vonmisesvariate(), paretovariate()
     # weibullvariate()
     # WichmannHill(), whseed(), SystemRandom()
     from Crypto.Random import random
     x = random.getrandbits(16*8)
     y = random.getrandbits(16*8)
     self.assertNotEqual(x, y)
     # Test randrange
     if x>y:
         start = y
         stop = x
     else:
         start = x
         stop = y
     for step in range(1,10):
         x = random.randrange(start,stop,step)
         y = random.randrange(start,stop,step)
         self.assertNotEqual(x, y)
         self.assertEqual(start <= x < stop, True)
         self.assertEqual(start <= y < stop, True)
         self.assertEqual((x - start) % step, 0)
         self.assertEqual((y - start) % step, 0)
     for i in range(10):
         self.assertEqual(random.randrange(1,2), 1)
     self.assertRaises(ValueError, random.randrange, start, start)
     self.assertRaises(ValueError, random.randrange, stop, start, step)
     self.assertRaises(TypeError, random.randrange, start, stop, step, step)
     self.assertRaises(TypeError, random.randrange, start, stop, "1")
     self.assertRaises(TypeError, random.randrange, "1", stop, step)
     self.assertRaises(TypeError, random.randrange, 1, "2", step)
     self.assertRaises(ValueError, random.randrange, start, stop, 0)
     # Test randint
     x = random.randint(start,stop)
     y = random.randint(start,stop)
     self.assertNotEqual(x, y)
     self.assertEqual(start <= x <= stop, True)
     self.assertEqual(start <= y <= stop, True)
     for i in range(10):
         self.assertEqual(random.randint(1,1), 1)
     self.assertRaises(ValueError, random.randint, stop, start)
     self.assertRaises(TypeError, random.randint, start, stop, step)
     self.assertRaises(TypeError, random.randint, "1", stop)
     self.assertRaises(TypeError, random.randint, 1, "2")
     # Test choice
     seq = list(range(10000))
     x = random.choice(seq)
     y = random.choice(seq)
     self.assertNotEqual(x, y)
     self.assertEqual(x in seq, True)
     self.assertEqual(y in seq, True)
     for i in range(10):
         self.assertEqual(random.choice((1,2,3)) in (1,2,3), True)
     self.assertEqual(random.choice([1,2,3]) in [1,2,3], True)
     if sys.version_info[0] is 3:
         self.assertEqual(random.choice(bytearray(b('123'))) in bytearray(b('123')), True)
     self.assertEqual(1, random.choice([1]))
     self.assertRaises(IndexError, random.choice, [])
     self.assertRaises(TypeError, random.choice, 1)
     # Test shuffle. Lacks random parameter to specify function.
     # Make copies of seq
     seq = list(range(500))
     x = list(seq)
     y = list(seq)
     random.shuffle(x)
     random.shuffle(y)
     self.assertNotEqual(x, y)
     self.assertEqual(len(seq), len(x))
     self.assertEqual(len(seq), len(y))
     for i in range(len(seq)):
        self.assertEqual(x[i] in seq, True)
        self.assertEqual(y[i] in seq, True)
        self.assertEqual(seq[i] in x, True)
        self.assertEqual(seq[i] in y, True)
     z = [1]
     random.shuffle(z)
     self.assertEqual(z, [1])
     if sys.version_info[0] == 3:
         z = bytearray(b('12'))
         random.shuffle(z)
         self.assertEqual(b('1') in z, True)
         self.assertRaises(TypeError, random.shuffle, b('12'))
     self.assertRaises(TypeError, random.shuffle, 1)
     self.assertRaises(TypeError, random.shuffle, "1")
     self.assertRaises(TypeError, random.shuffle, (1,2))
     # 2to3 wraps a list() around it, alas - but I want to shoot
     # myself in the foot here! :D
     # if sys.version_info[0] == 3:
         # self.assertRaises(TypeError, random.shuffle, range(3))
     # Test sample
     x = random.sample(seq, 20)
     y = random.sample(seq, 20)
     self.assertNotEqual(x, y)
     for i in range(20):
        self.assertEqual(x[i] in seq, True)
        self.assertEqual(y[i] in seq, True)
     z = random.sample([1], 1)
     self.assertEqual(z, [1])
     z = random.sample((1,2,3), 1)
     self.assertEqual(z[0] in (1,2,3), True)
     z = random.sample("123", 1)
     self.assertEqual(z[0] in "123", True)
     z = random.sample(list(range(3)), 1)
     self.assertEqual(z[0] in range(3), True)
     if sys.version_info[0] == 3:
             z = random.sample(b("123"), 1)
             self.assertEqual(z[0] in b("123"), True)
             z = random.sample(bytearray(b("123")), 1)
             self.assertEqual(z[0] in bytearray(b("123")), True)
     self.assertRaises(TypeError, random.sample, 1)
Example #53
0
 def sign(self, data):
     # 2 <= K <= q
     K = random.randrange(2, self.priv.q)
     r, s = self.priv.sign(data, K)
     return long_to_bytes(r, 20) + long_to_bytes(s, 20)
Example #54
0
#!/usr/bin/env python3
# Byte-at-a-time ECB decryption (harder)

from base64 import b64decode
from Crypto.Random.random import getrandbits, randrange
from Crypto.Cipher import AES
from m09 import pkcs7, de_pkcs7
from m11 import detect_ecb
from m12 import blocksize

RANDOM_KEY = bytes(getrandbits(8) for i in range(16))
RANDOM_PREFIX = bytes(getrandbits(8) for i in range(randrange(16)))

def oracle(plaintext = b'', prefix = RANDOM_PREFIX):
    unknown_string = b64decode(open("data/12.txt", "r").read())
    plaintext = pkcs7(prefix + plaintext + unknown_string, 16)
    cypher = AES.new(RANDOM_KEY, AES.MODE_ECB)
    return cypher.encrypt(plaintext)

def decrypt(cyphertext):
    cypher = AES.new(RANDOM_KEY, AES.MODE_ECB)
    return de_pkcs7(cypher.decrypt(cyphertext))

def len_prefix(oracle): 
    for i in range(32, 48):
        c = oracle(i * b'A')
        for b in range(len(c) // 16 - 1):
            if c[(b+1)*16:(b+2)*16] == c[(b+2)*16:(b+3)*16]:
                return 48 - i + 16 * b
    return 0
Example #55
0
def generate_random_latitude():
    """
    creates a random coordinate
    """
    return str(90 - float(random.randrange(10000000))/10000000 * 180)
	def rndKey(self):
		intKey1 = random.randrange( 0xFFFFFFFFFFFFFFFF )
		intKey2 = random.randrange( 0xFFFFFFFFFFFFFFFF )
		self.__key = pack( '<QQ', intKey1, intKey2 )
		self.__iv = Random.new().read( AES.block_size )
Example #57
0
 def test_encrypt_and_decrypt(self):
     s = long_to_bytes(randrange(2**1024))
     secret = self.public_key.encrypt(s)
     length = len(s)
     self.assertEquals(s, self.private_key.decrypt(secret)[:length])
Example #58
0
 def test_invalid_decrypt(self):
     s = long_to_bytes(randrange(2**1024))
     secret = self.public_key.encrypt(s)
     with self.assertRaises(Exception):
         self.private_key.decrypt(secret[:-1])
Example #59
0
'''
Created on Jan 25, 2016

@author: y2joshi
'''
import sys, os
import time
from Crypto.Random.random import randrange

if __name__ == '__main__':
    traceLength = int(sys.argv[1])
    uniqueEvents = int(sys.argv[2])
    noOfTraces = int(sys.argv[3])
    traceDir = sys.argv[4]
    for i in range(0,noOfTraces):
        try:
            if not os.path.isdir(traceDir):
                os.makedirs(traceDir)
            outFile = open(traceDir + "/trace" + str(i),"w")
            outFile.write("traceTimes,traceEvents\n")
            for j in range(0,traceLength):
                evt = randrange(1,uniqueEvents+1,1)
                tm= time.time()
                outFile.write(str(tm)+","+str(evt)+"\n")
                #time.sleep(0.0005)
        finally:
            outFile.close()    
        
Example #60
0
def generate_random_longitude():
    """
    creates a random coordinate
    """
    return str(180 - float(random.randrange(10000000))/10000000 * 360)