Beispiel #1
0
    def encrypt(self,m,r1=None,r2=None, r3=None):
        ''' Outputs a PPATCCiphertext on m using r1,r2 as the randomness for the
        commitment and r1,r2,r3 as the randomness for the encryption
        '''

        # notations
        q = self.PPATCpp.order
        g = self.PPATCpp.g
        ECG = g.ECG # EFp2
        Jcoord = self.PPATCpp.Jcoord

        if r1 == None:
            r1 = randint(1,int(q))
        if r2 == None:
            r2 = randint(1,int(q))
        if r3 == None:
            r3 = randint(1,int(q))

        # commitment
        d = self.commit(m,r1,r2)

        # encryption
        c1t = oEC.mul_comb2_EFp2(ECG,r2,self.precomp_g,Jcoord)
        c1 = oEC.toEFp2(ECG,c1t,Jcoord)
        #c1 = r2*g
        c2t = oEC.mul_comb2_EFp2(ECG,r3,self.precomp_g,Jcoord)
        c2 = oEC.toEFp2(ECG,c2t,Jcoord)
        #c2 = r3*g
        c31t = oEC.mul_comb2_EFp2(ECG,r1,self.precomp_g1,Jcoord)
        c32t = oEC.mul_comb2_EFp2(ECG,r3,self.precomp_g2,Jcoord)
        c3t = oEC.addEFp2(ECG,c31t,c32t,Jcoord)
        c3 = oEC.toEFp2(ECG,c3t,Jcoord)
        #c3 = (r1*g1)+(r3*g2)

        return PPATCCiphertext(d,c1,c2,c3,self)
Beispiel #2
0
def test_SPEKE():
	password = "******"
	p = getStrongPrime(768)
	h = hashlib.sha1()
	#https://build.opensuse.org/package/view_file?file=pycrypto-2.6-elgamal.patch&package=python-crypto.openSUSE_11.4_Update&project=openSUSE%3AMaintenance%3A564&rev=1fe551f41425aa7d6cb7bca6de778168
	h.update(password)
	print("hash(%s)=%s=%s" % (password, h.hexdigest(), bytes_to_long(h.digest())))
	sq = bytes_to_long(h.digest())**2
	print("hash^2=%s" % sq)
	g = sq % p
	print("g=%s" % g)
	ga = 0
	#choose values sufficiently large, but not too large
	#as this would slow down calculations too much!
	MIN_I = 2**12
	MAX_I = 2**13
	while ga<=2 or ga>=p-2:
		a = random.randint(MIN_I, MAX_I)
		print("a=%s" % a)
		ga = (g**a) % p
		print("(g**a)%%p=%s" % ga)
	gb = 0
	while gb<=2 or gb>=p-2:
		b = random.randint(MIN_I, MAX_I)
		print("b=%s" % b)
		gb = (g**b) % p
		print("(g**b)%%p=%s" % gb)
	ak = (gb**a) % p
	print("aK=%s" % ak)
	bk = (ga**b) % p
	print("bK=%s" % bk)
	assert ak==bk
Beispiel #3
0
    def commit(self,m,r1=None,r2=None):

        q = self.PPATCpp.order
        if r1 == None:
            r1 = randint(1,int(q))
        if r2 == None:
            r2 = randint(1,int(q))

        # notations
        Jcoord = self.PPATCpp.Jcoord
        ECG1 = self.h1.ECG
        ECG2 = self.g1.ECG

        # commitment
        d11t = oEC.mul_comb2_EFp(ECG1,r1,self.precomp_h,Jcoord)
        d12t = oEC.mul_comb2_EFp(ECG1,r2,self.precomp_h1,Jcoord)
        d1t = oEC.addEFp(ECG1,d11t,d12t,Jcoord)
        d1 = oEC.toEFp(ECG1,d1t,Jcoord)
        #d1 = (r1*h)+(r2*h1)
        mp = self.encode(m)
        d21t = oEC.mul_comb2_EFp2(ECG2,r2,self.precomp_g1,Jcoord)
        d2t = oEC.addEFp2(ECG2,mp,d21t,Jcoord)
        d2 = oEC.toEFp2(ECG2,d2t,Jcoord)
        #d2 = mp + r2*g1

        return PPATCCommitment(d1,d2,self)
Beispiel #4
0
def generate_request(**request_parameters):
    '''Generate a token provisioning request.'''
    default_model = 'MacBookPro%d,%d' % (random.randint(1, 12), random.randint(1, 4))
    default_request_parameters = {
        'timestamp':int(time.time()),
        'token_model':'VSST',
        'otp_algorithm':'HMAC-SHA1-TRUNC-6DIGITS',
        'shared_secret_delivery_method':'HTTPS',
        'manufacturer':'Apple Inc.',
        'serial':''.join(random.choice(string.digits + string.ascii_uppercase) for x in range(12)),
        'model':default_model,
        'app_handle':'iMac010200',
        'client_id_type':'BOARDID',
        'client_id':'Mac-' + ''.join(random.choice('0123456789ABCDEF') for x in range(16)),
        'dist_channel':'Symantec',
        'platform':'iMac',
        'os':default_model,
    }

    default_request_parameters.update(request_parameters)
    request_parameters = default_request_parameters

    data_before_hmac = u'%(timestamp)d%(timestamp)d%(client_id_type)s%(client_id)s%(dist_channel)s' % request_parameters
    request_parameters['data'] = base64.b64encode(
        hmac.new(
            HMAC_KEY,
            data_before_hmac.encode('utf-8'),
            hashlib.sha256
            ).digest()
        ).decode('utf-8')

    return REQUEST_TEMPLATE % request_parameters
Beispiel #5
0
    def encrypt(self,m,r=None,s=None):
        ''' Outputs a PPATSCiphertext on m using r as the randomness for the
        commitment and s as the randomness for the encryption
        '''
        #limit = 2**self.maxexp
        #assert m < limit
        #assert m >= 0
        order = self.PPATSpp.order
        if r == None:
            r = randint(1,int(order))
        if s == None:
            s = randint(1,int(order))
        # notations
        g1 = self.g1
        ECG = g1.ECG
        Jcoord = self.PPATSpp.Jcoord

        # commitment part
        d,r = self.commit(m,r)
        #d = (r*h)+(m*h1)

        # encryption part
        c1t = oEC.mul_comb2_EFp2(ECG,s,self.precomp_g,Jcoord)
        c1 = oEC.toEFp2(ECG,c1t,Jcoord)
        #c1 = s*g
        rgt = oEC.mul_comb2_EFp2(ECG,r,self.precomp_g,Jcoord)
        sg1t = oEC.mul_comb2_EFp2(ECG,s,self.precomp_g1,Jcoord)
        c2t = oEC.addEFp2(ECG,rgt,sg1t,Jcoord)
        c2 = oEC.toEFp2(ECG,c2t,Jcoord)
        #c2 = (r*g)+(s*g1)

        return PPATSCiphertext(d,c1,c2,self)
Beispiel #6
0
def generate_key_info():
    """
    This method generates the key-information for RSA encryption and decryption

    :return: RSA-key info
    """

    p = int(random.randint(1000, 5000))
    q = int(random.randint(1000, 5000))
    d = -1

    while not primetest(p):
        p = int(random.randint(1000, 5000))

    while not primetest(q):
        q = int(random.randint(1000, 5000))

    n = p * q
    Yn = (p - 1) * (q - 1)
    e = 0

    while d < 0:
        e = int(random.randint(2, Yn - 1))  # Create a random integer that is between 1<e<Y(n) #test 73
        d = eea(Yn, e)[0]  # eea only returns a negative integer if GCD (Y(n),e) is not 1

    return n, e, d, p, q, Yn
def init():
    # place the victim's cache lines
    victim_counter = phy_assoc*num_sets/2
    tag_range = int(math.pow(2,tag_width) - 1)
    while victim_counter > 0:
        victim_addr = random.randint(0, tag_range)
        victim_way = random.randint(0, phy_assoc-1)
        victim_set = pick_set(victim_way, victim_addr)
        if cache_tag[victim_set][victim_way][0] != -1:
            continue
        else:
            cache_tag[victim_set][victim_way] = [victim_addr, 0]
            victim_counter = victim_counter - 1
    
    # place the victim's cache lines
    attacker_counter = phy_assoc*num_sets/2
    tag_range = int(math.pow(2,tag_width) - 1)
    while attacker_counter > 0:
        attacker_addr = random.randint(0, tag_range)
        attacker_way = random.randint(0, phy_assoc-1)
        attacker_set = pick_set(attacker_way, attacker_addr)
        if cache_tag[attacker_set][attacker_way][0] != -1:
            continue
        else:
            cache_tag[attacker_set][attacker_way] = [attacker_addr, 1]
            attacker_counter = attacker_counter - 1
            
    print "finish initialization"
Beispiel #8
0
def verifiabilityProof2(ppatspk, d, m, r, b=None, u=None, t=None):
    """ This ZK proof ensures that d = r*h+m*h1 is a commitment on m = 0 or 1
    b,u,t are the randomness used in the proof (optional)
    """
    # notations
    order = ppatspk.PPATSpp.order
    h = ppatspk.PPATSpp.h
    h1 = ppatspk.h1
    ECG = h.ECG
    Jcoord = ppatspk.PPATSpp.Jcoord
    # ht = oEC.toTupleEFp(ECG,h,Jcoord)
    nh1t = oEC.toTupleEFp(ECG, -h1, Jcoord)
    ddt = oEC.toTupleEFp(ECG, d.d, Jcoord)
    # assert h*r+h1*m == d.d # commitment is well formed
    assert m == 0 or m == 1  # the proof works only if m = 0 or 1

    if b == None:
        b = randint(1, int(order))
    if u == None:
        u = randint(1, int(order))
    if t == None:
        t = randint(1, int(order))

    hbt = oEC.mul_comb2_EFp(ECG, b, ppatspk.precomp_h, Jcoord)
    hb = oEC.toEFp(ECG, hbt, Jcoord)
    if m == 0:
        u1 = u
        t1 = t
        # commitment

        # w0 = PPATSCommitment(h*b,self)
        w0 = ppat.ppats.PPATSCommitment(hb, ppatspk)
        hu1t = oEC.mul_comb2_EFp(ECG, u1, ppatspk.precomp_h, Jcoord)
        s1 = oEC.addEFp(ECG, ddt, nh1t, Jcoord)
        s1t1 = oEC.mulECP(ECG, s1, -t1, False, Jcoord)
        w1t = oEC.addEFp(ECG, hu1t, s1t1, Jcoord)
        w1v = oEC.toEFp(ECG, w1t, Jcoord)
        w1 = ppat.ppats.PPATSCommitment(w1v, ppatspk)
        # challenge
        t0 = ppatspk.hashf([ppatspk.PPATSpp, ppatspk, d, w0, w1]) - t1
        # response
        u0 = b + r * t0
    if m == 1:
        u0 = u
        t0 = t
        # commitment
        hu0t = oEC.mul_comb2_EFp(ECG, u0, ppatspk.precomp_h, Jcoord)
        ddt0 = oEC.mulECP(ECG, ddt, -t0, False, Jcoord)
        w0t = oEC.addEFp(ECG, hu0t, ddt0, Jcoord)
        w0v = oEC.toEFp(ECG, w0t, Jcoord)
        w0 = ppat.ppats.PPATSCommitment(w0v, ppatspk)
        w1 = ppat.ppats.PPATSCommitment(hb, ppatspk)
        # challenge
        t1 = ppatspk.hashf([ppatspk.PPATSpp, ppatspk, d, w0, w1]) - t0
        # response
        u1 = b + r * t1
    return [u0, u1, t0, t1]

    """
Beispiel #9
0
 def test_geq_proof_on_commitment(self):
     m1 = randint(1,self.maxmessage)
     m2 = randint(1,m1)
     com1, r1 = self.ppatspk.commit(m1)
     com2, r2 = self.ppatspk.commit(m2)
     gproof = nizk.geqProof(self.ppatspk,com1,m1,r1,com2,m2,r2,self.maxexp)
     res = nizk.geqProofCheck(self.ppatspk,com1,com2,gproof,self.maxexp)
     self.assertTrue(res)
Beispiel #10
0
 def test_multiplication_of_cipher_by_scalar(self):
     m1 = randint(1,2**(self.maxexp-10)) # So the multiplication of the cipher can be decrytpted
     cipher1 = self.ppatspk.encrypt(m1)
     a = randint(1,1000)
     cipher2 = self.ppatspk.encrypt(a*m1)
     d1 = self.ppatssk.decrypt(cipher1)
     d2 = self.ppatssk.decrypt(cipher2)
     self.assertTrue(a*d1==d2)
Beispiel #11
0
def rand_padding(s):
    pre_padlen = random.randint(5, 10)
    post_padlen = random.randint(5, 10)

    prefix = random.getrandbits(8 * pre_padlen).to_bytes(pre_padlen, 'big')
    postfix = random.getrandbits(8 * post_padlen).to_bytes(post_padlen, 'big')

    return prefix + s + postfix
Beispiel #12
0
 def test_multiplication_of_commitment_by_a_scalar(self):
     m1 = randint(1,self.maxmessage)
     r1 = randint(1,self.n-1)
     d1,r1 = self.ppatspk.commit(m1,r1)
     a = randint(1,1000)
     d2 = a*d1
     d2p,r2 = self.ppatspk.commit(a*m1,a*r1)
     self.assertTrue(d2==d2p)
Beispiel #13
0
 def generate_and_encode_password(self, size=10):
     N = [random.randint(0,4294967295) for i in range(size)]
     P = [s[N[i]%len(s)] for i, s in enumerate(self.must_set)]
     P.extend(self.All[n%len(self.All)] for n in N[len(self.must_set):])
     n = random.randint(0, fact_map[size-1])
     password = decode2string(n, P)
     N.append(n)
     return password, N
Beispiel #14
0
 def test_addition_of_commitments(self):
     m1 = randint(1,self.maxmessage)
     r1 = randint(1,self.n-1)
     d1,r1 = self.ppatspk.commit(m1,r1)
     m2 = randint(1,self.maxmessage)
     r2 = randint(1,self.n-1)
     d2,r2 = self.ppatspk.commit(m2,r2)
     d3 = d1+d2
     d3p,r3 = self.ppatspk.commit(m1+m2,r1+r2)
     self.assertTrue(d3==d3p)
Beispiel #15
0
def challenge22():
    cur_time = int(time.time()) + random.randint(40, 1000)
    m = Mersenne(cur_time)
    cur_time += random.randint(40, 1000)
    num = m.extract_number()
    for i in range(int(time.time()) - 4000, int(time.time()) + 4000):
        m = Mersenne(i)
        if m.extract_number() == num:
            print("Seed: {0}".format(i))
            return
Beispiel #16
0
 def test_addition_of_ciphers(self):
     m1 = randint(1,2**(self.maxexp-1)) # So the addition of the two can be decrytpted
     cipher1 = self.ppatspk.encrypt(m1)
     m2 = randint(1,2**(self.maxexp-1))
     cipher2 = self.ppatspk.encrypt(m2)
     cipher3 = self.ppatspk.encrypt(m1+m2)
     d1 = self.ppatssk.decrypt(cipher1)
     d2 = self.ppatssk.decrypt(cipher2)
     d3 = self.ppatssk.decrypt(cipher3)
     self.assertTrue(d1+d2==d3)
Beispiel #17
0
    def test_multiplication_of_commtiments_by_triplet(self):
        #q = self.ppatspp.q
        m1 = randint(1,self.maxmessage)
        r1 = randint(1,self.n-1)
        a1,r1 = self.ppatspk.commit(m1,r1)
        m2 = randint(1,self.maxmessage)
        r2 = randint(1,self.n-1)
        a2,r2 = self.ppatspk.commit(m2,r2)
        r3 = randint(1,self.n-1)
        a3,r3 = self.ppatspk.commit(m1*m2,r3)
        proof = nizk.multiplicationProof(self.ppatspk,a1,a2,a3,m1,m2,r1,r2,r3)
        m1p = randint(1,self.maxmessage)
        r1p = randint(1,self.n-1)
        d1,r1p = self.ppatspk.commit(m1p,r1p)
        m2p = randint(1,self.maxmessage)
        r2p = randint(1,self.n-1)
        d2,r2p = self.ppatspk.commit(m2p,r2p)
        g = self.ppatspp.g
        o1 = (r1p-r1)*g
        o2 = (r2p-r2)*g
        openings = (m1p-m1,o1),(m2p-m2,o2)

        d3 = nizk.multiplicationWithTripletAndCheck(self.ppatspk,d1,d2,a1,a2,a3,proof,openings)
        o3 = (r3+m2p*r1-m2*r1+m1p*r2-m1*r2)*g

        self.assertTrue(self.ppatspk.verifyOpening(d3,m1p*m2p,o3))
Beispiel #18
0
 def test_multiplication_of_commitment_proof_and_check(self):
     m1 = randint(1,self.maxmessage)
     r1 = randint(1,self.n-1)
     d1,r1 = self.ppatspk.commit(m1,r1)
     m2 = randint(1,self.maxmessage)
     r2 = randint(1,self.n-1)
     d2,r2 = self.ppatspk.commit(m2,r2)
     r3 = randint(1,100)
     d3,r3 = self.ppatspk.commit(m1*m2,r3)
     proof = nizk.multiplicationProof(self.ppatspk,d1,d2,d3,m1,m2,r1,r2,r3)
     self.assertTrue(nizk.multiplicationProofCheck(self.ppatspk,d1,d2,d3,proof))
Beispiel #19
0
def test_split_into_chunks():
    for _ in xrange(1000):
        whole_size = rand.randint(100, 10000)
        chunk_size = rand.randint(1, 100)
        random_string = random.read(whole_size)
        chunks = split_into_chunks(random_string, chunk_size)
        for c in chunks:
            if c == chunks[-1]:
                assert(len(c) <= chunk_size)
            else:
                assert(len(c) == chunk_size)
Beispiel #20
0
 def generate_and_encode_password(self, size=10):
     N = [random.randint(0, MAX_INT) for i in range(size+1)]
     N[0] +=  (size - N[0] % self.MAX_ALLOWED)
     P = [s[N[i+1]%len(s)] for i,s in enumerate(self.must_set)]
     P.extend(self.All[n%len(self.All)] for n in N[len(self.must_set)+1:])
     n = random.randint(0, MAX_INT) 
     password = self.decode2string(n, P)
     N.append(n)
     extra = hny_config.PASSWORD_LENGTH - len(N);
     N.extend([convert2group(0,1) for x in range(extra)])
     return password, N
Beispiel #21
0
def keygen(k,x=-1,p=-1,q=-1):    
   if (p,q)==(-1,-1):
       (p,q)=getSafePrimes(k)
   g=randint(2,p-2)
   g=powmod(g,2,p)
   if (x==-1):
       x=randint(2,q-1)
   y=powmod(g,x,p)
   common=(g,p,q)
   pk=(common,y)
   sk=(common,x)
   return (pk,sk)
Beispiel #22
0
    def encryptwithCproof(self,m,r1=None,r2=None,r3=None,s=None,s1=None,s2=None,s3=None):
        q = self.PPATCpp.order

        if r1 == None:
            r1 = randint(1,int(q))
        if r2 == None:
            r2 = randint(1,int(q))
        if r3 == None:
            r3 = randint(1,int(q))
        c = self.encrypt(m,r1,r2,r3)
        cproof = nizkproofs.nizkpok.consistencyProof_ppatc(self,c,m,r1,r2,r3,s,s1,s2,s3)
        return c,cproof
Beispiel #23
0
def encryption_oracle(s):
    key = util.randbytes(16)
    cipher = AES.new(key, AES.MODE_ECB)
    if random.randint(0, 1) == 0:
        print('Encrypting with ECB')
    else:
        print('Encrypting with CBC')
        IV = util.randbytes(16)
        cipher = challenge10.CBC(cipher, IV)
    s = util.randbytes(random.randint(5, 10)) + s + util.randbytes(random.randint(5, 10))
    s = util.padPKCS7(s, 16)
    return cipher.encrypt(s)
Beispiel #24
0
def encryption_oracle(s):
    cipher = AES.new(get_rnd_bytes(AES.block_size), AES.MODE_ECB)

    s = get_rnd_bytes(random.randint(5, 10)) + s + get_rnd_bytes(random.randint(5, 10))

    if random.randint(0, 1) == 1:
        print("Encryption Oracle: ECB.")
    else:
        print("Encryption Oracle: CBC.")
        iv = get_rnd_bytes(AES.block_size)
        cipher = c10.CBC(cipher, iv, AES.block_size)

    return cipher.encrypt(s)
Beispiel #25
0
def encryption_oracle(input):
	padded_input = Random.new().read(randint(5,10)) + input + Random.new().read(randint(5,10))
	size = len(padded_input)
	padded_input = pad16(padded_input)
	#print len(padded_input)
	#print padded_input
	
	if randint(0,1):
		print "ECB used"
		return encrypt_ECB(padded_input, generate_AESKey(), "")
	else:
		print "ECB-CBC used"
		return encrypt_CBC(encrypt_ECB, padded_input, generate_AESKey(), Random.new().read(AES.block_size), 16)
Beispiel #26
0
def consistencyProof_ppatc(ppatcpk,c,m,r1,r2,r3,s=None,s1=None,s2=None,s3=None):
    ''' This proof ensures that the commitment part of the ciphertext is
    commiting on the same message that is encrypted in the encryption part
    The proof is a proof of equality between discrete logarithms
    '''

    # notations
    '''
    h = ppatcpk.PPATCpp.h
    ECG1 = h.ECG
    h1 = ppatcpk.h1
    g = ppatcpk.PPATCpp.g
    ECG2 = g.ECG
    Jcoord = ppatcpk.PPATCpp.Jcoord
    g1 = ppatcpk.g1
    g2 = ppatcpk.g2
    '''
    q = ppatcpk.PPATCpp.order

    if s1 == None:
        s1 = randint(1,int(q))
    if s2 == None:
        s2 = randint(1,int(q))
    if s3 == None:
        s3 = randint(1,int(q))
    if s == None:
        s = randint(1,int(q))
    '''
    ms = ppatcpk.encode(s) # ms is a random element of G1

    c1pt = oEC.mul_comb2_EFp2(ECG2,s2,ppatcpk.precomp_g,Jcoord)
    c1p = oEC.toEFp2(ECG2,c1pt,Jcoord)
    c1p = s2*g
    c2p = s3*g
    c3p = s1*g1 + s3*g2
    d1p = s1*h + s2*h1
    d2p = ms + s2*g1
    dp = ppat.ppatc.PPATCCommitment(d1p,d2p,ppatcpk)
    cp = ppat.ppatc.PPATCCiphertext(dp,c1p,c2p,c3p,ppatcpk)
    '''
    cp = ppatcpk.encrypt(s,s1,s2,s3)

    nu = ppatcpk.hashf([ppatcpk.PPATCpp,ppatcpk,c,cp])

    f1 = (s1 + nu*r1)%q
    f2 = (s2 + nu*r2)%q
    f3 = (s3 + nu*r3)%q
    #fm = (mp + nu*m) %q
    fm = (s + nu*m) %q

    return [nu,f1,f2,f3,fm]
Beispiel #27
0
def gen_password_old(length = 10, num_punc = 1, sequence = None):
  """
  Generate a random password, where:

  :var    length      length of password, default 10
  :var    num_punc    minimum number of punctuation characters in pass
  :var    sequence    the sequence to generate from. vary to increase or decrease frequency of each
  """
  sequence = ['LOWERCASE', 'LOWERCASE', 'LOWERCASE', 'LOWERCASE', 'LOWERCASE', 'LOWERCASE', 'UPPERCASE', 'VOWELS', 'NUMBERS', 'PUNC']
  seq = [sequence[randint(0, len(sequence) - 1)] for i in range(0, 100)]
  # print sequence[random.randint(0, len(sequence) - 1)].upper()
  # seq = [LOWERCASE for i in range(0, 10)]
  # print locals()
  return "".join([globals()[i][randint(0, len(globals()[i]) - 1)] for i in seq])[0:length]
Beispiel #28
0
    def set(self, message, extra, views, compress = True):
        extra = extra or ''
        views = views or self._views
        if (views < 1):
            views = 1
        msglen = len(message)
        if self._debug:
            print('message: ' + message)
            print('messagelen: ' + str(msglen))
            print('extra: ' + str(extra))
            print('views: ' + str(views))

        if compress and (msglen > self._mincompsize):
            message = '\x01' + self._deflate(message)
            if self._debug:
                print('compressed: ' + str(len(message)))
        else:
            message = '\x00' + message

        while True:
            uid = uuid.uuid4().bytes
            if not self._cache.has(uid):
                break
        if self._debug:
            print('uid: ' + uid.encode('hex'))

        msgidx = random.randint(0, self._keycount - 1)
        msgiv = Random.new().read(AES.block_size)
        if self._debug:
            print('msgidx: ' + str(msgidx))
            print('msgiv: ' + msgiv.encode('hex'))

        msgcipher = AES.new(self._msgkey[msgidx]['key'], AES.MODE_CFB, msgiv)
        self._msgkey[msgidx]['count'] += 1
        salt = Random.new().read(SHA256.digest_size)
        cryptmsg = self._intpack(msgidx, self._kcsize) + msgiv + msgcipher.encrypt(salt) + msgcipher.encrypt(HMAC.new(salt, message, SHA256).digest()) + msgcipher.encrypt(message)

        if self._cache.set(uid, (HMAC.new(extra, cryptmsg, SHA256).digest() + cryptmsg, views)):
            cryptiv = Random.new().read(AES.block_size)
            cryptidx = random.randint(0, self._keycount - 1)
            if self._debug:
                print('cryptidx: ' + str(cryptidx))
                print('cryptiv: ' + cryptiv.encode('hex'))

            cryptcipher = AES.new(self._cryptkey[cryptidx]['key'], AES.MODE_CFB, cryptiv)
            self._cryptkey[cryptidx]['count'] += 1

            return (base64.urlsafe_b64encode(self._instanceid + self._intpack(cryptidx, self._kcsize) + cryptiv + cryptcipher.encrypt(uid)).rstrip('='), None)
        else:
            return (None, self.ERROR_CACHE_NOTSET)
Beispiel #29
0
def is_case_insensitive_path(root_path, return_file = False):
    if _IS_WIN:
        tmp_file = '~%dHI.tmp' % (random.randint(0, sys.maxint),)
    else:
        tmp_file = '.~%dHI' % (random.randint(0, sys.maxint),)
    orig_path = os.path.join(root_path, tmp_file)
    open(orig_path, 'w').close()
    try:
        does_exist = os.path.exists(os.path.join(root_path, tmp_file.lower()))
        if return_file:
            return (does_exist, orig_path)
        return does_exist
    finally:
        os.unlink(orig_path)
Beispiel #30
0
    def encryptwithCproof(self,m,r=None,s=None,mp=None,rp=None,sp=None):
        ''' Outputs a PPATSCiphertext and a consistency on m using r as the randomness for the
        commitment and s as the randomness for the encryption
         If provided, mp,rp,sp are used for the proof of consistency
        '''
        order = self.PPATSpp.order
        if r == None:
            r = randint(1,int(order))
        if s == None:
            s = randint(1,int(order))

        c = self.encrypt(m,r,s)
        cproof = nizkproofs.nizkpok.consitencyProof(self,c,m,r,s,mp,rp,sp)

        return c,cproof
Beispiel #31
0
 def test_encrypt_with_consistency_check_proof(self):
     m1 = randint(1, self.n - 1)
     #m1 = m1i*P
     c, cproof = self.ppatcpk.encryptwithCproof(m1)
     self.assertTrue(
         nizk.consistencyProofCheck_ppatc(self.ppatcpk, c, cproof))
Beispiel #32
0
def profile_for(email):
    email = email.replace("&", "")
    email = email.replace("=", "")
    return encrypt_encoded_user_cookie(
        User(email, random.randint(10, 99), "user"))
Beispiel #33
0
from Crypto.Random import random

print('random.randint: ', random.randint(10, 20))
print('random.randrange: ', random.randrange(10, 20, 2))
print('random.randint: ', random.getrandbits(3))
print('random.choice: ', random.choice([1, 2, 3, 4, 5]))
print('random.sample: ', random.sample([1, 2, 3, 4, 5], 3))
list = [1, 2, 3, 4, 5]
random.shuffle(list)
print('random.shuffle: ', list)
Beispiel #34
0
    def fillupTree(self, blockList):
        '''
        This method randomly assign blocks to the tree nodes and pad with dummy
        blocks
        We assume here that the tree is empty
        '''
        #Z = self.POTree.Z
        blockL = []
        k = len(blockList)
        t = self.POTree.tLoad
        r1 = t - k  # the number of dummyblocks to create

        t1 = time.time()
        for blockID, block in blockList:
            blockL.append((blockID, block))

        t2 = time.time()

        for i in range(r1):
            blockL.append(('DB' + str(i), None))

        t3 = time.time()

        #print k,t,r1, len(blockDic)
        assert len(
            blockL
        ) == t  # we now have exactly enough blocks to fill up the tree

        new_blockList = []

        tm1, tm2 = 0, 0
        #kBD = blockDic.keys()

        for i in range(t):
            t31 = time.time()
            lBD = len(blockL)
            r2 = randint(0, lBD - 1)
            randomBlockID, randomBlock = blockL.pop(r2)
            #randomBlock = blockDic.pop(randomBlockID)
            new_blockList.append((i, randomBlock))

            t32 = time.time()

            subpath = positionToSubPath(i, self.POTree.nbChildren,
                                        self.POTree.Z, self.POTree.depth,
                                        self.sPD)
            """
            possiblePathsList = possiblePaths(subpath,self.POTree.nbChildren,self.POTree.depth+1)
            l = len(possiblePathsList)
            r2 = randint(0,l-1)
            path = possiblePathsList[r2]
            """
            path = randomPath(subpath, self.POTree.nbChildren,
                              self.POTree.depth + 1)

            self.positionList[i] = (randomBlockID, path)
            self.positionMap[randomBlockID] = (i, path)

            t33 = time.time()

            tm1 += t32 - t31
            tm2 += t33 - t32

            if i % (t // 64) == 0:
                print round((float(i) / t) * 100, 2), '% done'

        t4 = time.time()

        self.POTree.writeBlocks(new_blockList)

        t5 = time.time()

        print 'blockDic insertion:', t2 - t1, '\n dummy block creation:', t3 - t2, '\n tree filling:', t4 - t3, '\n random block extraction:', tm1 / t, '\n path attribution:', tm2 / t, '\n block rerwriting in tree:', t5 - t4
Beispiel #35
0
def get_random_prime(bits=1024):
    return int(gmpy.next_prime(randint(2**(bits - 1), 2**bits)))
Beispiel #36
0
import s34_aux
import socket
from Crypto.Random import get_random_bytes
from Crypto.Random.random import randint

for i in range(3):
    p = 0xffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff
    if i == 0:
        g = 1
    elif i == 1:
        g = p
    else:
        g = p - 1

    a = randint(2, p - 2)
    A = pow(g, a, p)

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(('localhost', 9001))

    conn = s34_aux.Conn(sock)

    conn.sendnum(p)
    conn.sendnum(g)
    conn.sendnum(A)

    B = conn.readnum()

    s = pow(B, a, p)
Beispiel #37
0
 def generateQPKeys(self):
     N2 = self.N * self.N
     self.__a = random.randint(1, N2 // 4)
     # self.__a = random.randint(1, 15)
     self.h1 = util.calculate_expo_mod(self.g, self.__a, N2)
Beispiel #38
0
def convert2group(t, totalC):
    return t + random.randint(0, (MAX_INT-t)/totalC) * totalC
Beispiel #39
0
 def roll(self, limit):
     return randint(1, 10)
Beispiel #40
0
                lon = float(line[6])
                 
                p = str(proj(lat, lon))
         
                xy = p.split(',')
                 
                strOut = ",".join(line[0:5]) + "," + xy[0][1:] + "," + xy[1][1:-1] + "," + ",".join(line[7:])
            except:
                pass

        yield  strOut

    
sc = pyspark.SparkContext()

busCSVFile = sys.argv[1]
runLocal = sys.argv[2] == 'T'
outputDir = sys.argv[3]

if(runLocal): 
    outputDir += str(randint(0, 999))
    subprocess.call('rm -rf ' + outputDir, shell=True)

rddBikeUniqueStations = sc.textFile(busCSVFile) \
                          .mapPartitions(csvParse) \
                          .mapPartitions(lambda itr: toNAD83(itr)) \
                          .filter(lambda x: x != "") \
                          .saveAsTextFile(outputDir, "org.apache.hadoop.io.compress.GzipCodec")
if(runLocal):
    print "Output Dir: " + outputDir
Beispiel #41
0
 def __subloop(self, wsock: socket.socket):
     'This method handles the state transitions for the Start/Stop procedures'
     connid = randint(0, 65535)
     while connid in self.__startdt.keys():
         connid = randint(0, 65535)
     msr = None
     self.__startdt[connid] = False
     wsock.settimeout(RTU_TIMEOUT)
     self.log(f'Initiating state handler with ID {connid:d}')
     while not self.terminate:
         try:
             data = wsock.recv(BUFFER_SIZE)
             data = APDU(data)
             atype = data['APCI'].Type
             if msr is None:  # STOPPED connection as shown in figure 17 from 60870-5-104 IEC:2006
                 if atype in [0x00,
                              0x01]:  # I-frame (0x00) or S-frame (0x01)
                     self.log(
                         f'Received an unexpected frame ({TYPE_APCI[atype]:s}) in "STOPPED connection" state. Terminating thread ...'
                     )
                     self.__terminate = True
                 elif atype == 0x03:  # U-frame (0x03)
                     ut = data['APCI'].UType
                     if ut == 0x01:  # STARTDT act
                         self.log('Received a "STARTDT act" U-frame')
                         data = startdt(True)  # STARTDT actcon
                     elif ut == 0x04:  # STOPDT act
                         self.log('Received a "STOPDT act" U-frame')
                         data = stopdt(True)  # STOPDT actcon
                     else:  # TESTFR act
                         self.log('Received a "TESTFR act" U-frame')
                         data = testfr(True)  # TESTFR actcon
                     # NOTE: If more than one bit is activated, it will be registered as a 'TESTFR act'
                     wsock.send(data)
                     if ut == 0x01:  # Start the connection
                         self._RTU__startdt[
                             connid] = True  # Track the state of the current connection
                         msr = Thread(target=self._RTU__measure,
                                      kwargs={
                                          'wsock': wsock,
                                          'connid': connid
                                      })
                         self.log('Start measuring data ...')
                         msr.start()  # Start measuring
             else:  # STARTED connection as shown in figure 17 from 60870-5-104 IEC:2006
                 if atype == 0x03:  # U-frame (0x03)
                     ut = data['APCI'].UType
                     if ut == 0x01:  # STARTDT act
                         self.log('Received a "STARTDT act" U-frame')
                         data = startdt(True)  # STARTDT actcon
                     elif ut == 0x04:  # STOPDT act
                         self.log('Received a "STOPDT act" U-frame')
                         data = stopdt(True)  # STOPDT actcon
                         self._RTU__startdt[
                             connid] = False  # Change measurement state
                         self.log('Stop measusing data ...')
                         msr.join()  # Stop measuring
                         msr = None
                     else:  # TESTFR act
                         self.log('Received a "TESTFR act" U-frame')
                         data = testfr(True)  # TESTFR actcon
                     wsock.send(data)
                 elif atype == 0x01:  # S-frame (0x01)
                     self.log('Received an S-frame')
                     self.__tx = data['APCI'].Rx
                 else:  # I-frame (0x00)
                     self.log('Received an I-frame. Initiating handler ...')
                     self.__handle_iframe(wsock, data)
             # NOTE: In this particular simulation, we are not considering the 'Pending UNCONFIRMED STOPPED connection' state, as our responses are faster
         except socket.timeout:
             self.log('ERROR: T1 timeout')
             self.__terminate = True  # RTU T1 timeout => terminate connection
         except BrokenPipeError:
             self.log('ERROR: Connection ended unexpectedly')
             self.__terminate = True  # Connection ended unexpectedly.
         except socket.error as e:
             if e.errno != errno.ECONNRESET:
                 self.log(f'ERROR: Unknown socket error: {e.errno:d}')
                 raise  # Other unknown error
             self.__terminate = True
         except IndexError:
             self.log('ERROR: Index error')
     if msr is not None:  # The connection was still measuring
         self.__startdt[connid] = False  # Change measurement state
         msr.join()  # Stop measuring
         msr = None
         self.__startdt.pop(connid)  # Remove the connection tracking
     wsock.close()
Beispiel #42
0
 def encrypt(self) -> bytes:
     iv = Random.get_random_bytes(len(self.key))
     s = self.choices[random.randint(0, len(self.choices) - 1)]
     return block.aes_cbc_encrypt(s, self.key, iv), iv
def generate(length):
    password = ""
    for i in range(length):
        index = random.randint(0, 63)
        password = password + characters[index]
    return password
Beispiel #44
0
def generate_keypair(p=P, q=Q, g=G):

    x = randint(1, q-1)
    y = pow(g, x, p)

    return PublicKey(y), PrivateKey(x)
 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, "11")
     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)
Beispiel #46
0
import json
from binascii import hexlify, unhexlify

from ecpy.curves import curve_secp256k1
from ecpy.point import Point, Generator
from ecpy.ecdsa import ECDSA
from Crypto.Random import random
from Crypto.Cipher import AES
from Crypto.Util import Counter

_curve = curve_secp256k1
Point.set_curve(_curve)
_G = Generator.init(_curve['G'][0], _curve['G'][1])
ECDSA.set_generator(_G)

server_p = random.randint(1, curve_secp256k1['n'] - 1)
server_P = _G * server_p

config = {}
config['receive_dir'] = "recv/"
config['message_dir'] = "messages/"
config['capacity'] = (128 * 1024 * 1024 * 1024)
config['max_file_size'] = (256 * 1024 * 1024)
config['ncache_sleep_interval'] = 30
config['version'] = '0.0.2'

clopts = []
clopts.append({'name': 'rpcuser', 'default': None})
clopts.append({'name': 'rpcpass', 'default': None})
clopts.append({'name': 'rpchost', 'default': '127.0.0.1'})
clopts.append({'name': 'rpcport', 'default': 7765})
Beispiel #47
0
fp2_i = field.ExtensionFieldElem(Fp2, fp2_ip)
xi = (c**2) * fp2_1 + (d**3) * fp2_i  # c**2+(d**3)*A (4+i)
cxi = (c**2) * fp2_1 - (d**3) * fp2_i  # c**2-(d**3)*A
#ixi = 8*fp2bi-8*fp2b1 # 8*A-8
#xi = ixi.invert()
#C2b = EllipticCurve.Curve(fp2b0, 3*ixi,Fp2b) # Y**2 = X**3+3*(8*A-8)
C2 = ellipticCurve.Curve(fp2_0, cxi,
                         Fp2)  # Y**2 = X**3+c**2-(d**3)*A The twisted curve
PInf2 = ellipticCurve.ECPoint(infty=True)
EFp2 = ellipticCurve.ECGroup(Fp2, C2, PInf2)

u0 = EFp2.elem((-d) * fp2_i, c * fp2_1)  #EC point (-d*A,c)
h = 2 * p - n
Q = u0 * h  # Q is a generator of G2 of order n

r = randint(1, int(n))
s = randint(1, int(n))
rP = r * P
sQ = s * Q

##### Fp6 #####
poly3 = field.polynom(Fp2, [fp2_1, fp2_0, fp2_0, -xi])  #X**3-xi
Fp6 = field.ExtensionField(Fp2, poly3)
fp6_0 = Fp6.zero()
fp6_1 = Fp6.one()
fp6_xi = Fp6.elem(xi)  # xi in Fp6

##### Fp12 #####
poly6 = field.polynom(Fp6, [fp6_1, fp6_0, -fp6_xi])  # X**2-xi
Fp12 = field.ExtensionField(Fp6, poly6)
print Fp12, " ...done"
Beispiel #48
0
from nibss.utils.crypt import Crypt
from Crypto.Random import random

iv = ''.join(chr(random.randint(0, 23)) for i in range(16))
aes = ''.join(chr(random.randint(0, 23)) for i in range(16))

responses = {
    "single_bvn": {
        'message': 'OK',
        'data': {
            'ResponseCode': '00',
            'BVN': '12345678901',
            'FirstName': 'Uchenna',
            'MiddleName': 'Chijioke',
            'LastName': 'Nwanyanwu',
            'DateOfBirth': '22-Oct-1970',
            'PhoneNumber': '07033333333',
            'RegistrationDate': '16-Nov-2014',
            'EnrollmentBank': '900',
            'EnrollmentBranch': 'Victoria Island',
            'WatchListed': 'NO'
        }
    },
    "multiple_bvn": {
        "message": "OK",
        "data": {
            "ResponseCode":
            "00",
            "ValidationResponses": [{
                "ResponseCode": "00",
                "BVN": "12345678901",
Beispiel #49
0
 def test_encrypt_open_verify(self):
     m1 = randint(1, self.n - 1)
     #m1 = m1i*P
     cipher1 = self.ppatcpk.encrypt(m1)
     a1 = self.ppatcsk.opens(cipher1)
     self.assertTrue(self.ppatcpk.verify(cipher1, m1, a1))
Beispiel #50
0
 def test_commit_and_verify(self):
     m1 = randint(1, self.n - 1)
     r1 = randint(1, self.n - 1)
     r2 = randint(1, self.n - 1)
     d = self.ppatcpk.commit(m1, r1, r2)
     self.assertTrue(self.ppatcpk.verifyCommitment(d, m1, r1, r2))
Beispiel #51
0
    def queryBlock(self, blockID):
        '''
        This method returns the block stored in the self.POTree which corresponds
        to the blockID
        
        Doing so, the method modifies all the blocks along the path corresponding
        to the block. The blocks are either :
            - rerandomized
            - moved in the stash
            - reassigned in the path
            - replaced by dummy blocks
        '''
        assert not self.isADummyBlock(blockID)

        n = self.POTree.nbChildren
        Z = self.POTree.Z
        position, path = self.positionMap[blockID]
        assert path in self.pathList

        #print 'path', path

        indexesList = pathToIndexList(path, n, Z)

        #print 'indexesList', indexesList

        assert ((position != 'stash') and
                (position in indexesList)) or (position == 'stash')

        l = len(self.pathList)
        r = randint(0, l - 1)
        new_path = self.pathList[r]

        #print 'new_path', new_path

        blockList = self.POTree.getBlocks(indexesList)

        if position == 'stash':
            querriedBlock = self.clientStash[blockID]
            self.clientStash[blockID] = querriedBlock
        else:
            querriedBlock = blockList[indexesList.index(position)]
            self.positionList[position] = blockID, new_path

        self.positionMap[blockID] = position, new_path

        for i in range(len(blockList)):
            block_i = blockList[i]
            pos_i = indexesList[i]
            block_i_ID, path_i = self.positionList[pos_i]

            # Update block position and add it to the stash or to the dummystash
            if self.isADummyBlock(block_i_ID):
                self.dummyStash[block_i_ID] = block_i
                self.positionMap[block_i_ID] = ('dummy stash', path_i)

            else:
                self.clientStash[block_i_ID] = block_i
                self.positionMap[block_i_ID] = ('stash', path_i)

            self.positionList[pos_i] = (None, None)

        new_block_list = self.getCandidates(
            indexesList,
            path)  # seek candidates to greedily refill the path of the tree
        #print len(new_block_list)
        L = []
        #print 'new_block_list',new_block_list
        #print 'dummystash',self.dummyStash

        for position_j, blockID_j in new_block_list:
            if self.isADummyBlock(blockID_j):
                block_j = self.dummyStash.pop(blockID_j)
                L.append((position_j, block_j))
                self.positionMap[blockID_j] = (None, None)
            else:
                block_j = self.clientStash.pop(blockID_j)
                new_block_j = self.rerandomizeBlock(block_j)
                L.append((position_j, new_block_j))

            old_pos, path_j = self.positionMap[blockID_j]
            self.positionList[position_j] = (blockID_j, path_j)
            self.positionMap[blockID_j] = (position_j, path_j)

        self.POTree.writeBlocks(L)

        return querriedBlock
Beispiel #52
0
def oldtrain(solver, test_net, data_arrays, train_data_arrays, options):
    caffe.select_device(options.train_device, False)

    print('====> in training....')

    net = solver.net
    net.debug_info = True

    #pdb.set_trace()
    clwt = None
    test_eval = None
    if options.scale_error == 2:
        clwt = ClassWeight(data_arrays, solver.iter)
        test_eval = TestNetEvaluator(test_net, net, data_arrays, options)

    test_eval2 = None
    if (options.test_net != None):
        test_eval2 = TestNetEvaluator(test_net, net, train_data_arrays,
                                      options)

    input_dims, output_dims, input_padding = get_spatial_io_dims(net)
    fmaps_in, fmaps_out = get_fmap_io_dims(net)

    print('input_dims:', input_dims)
    print('output_dims:', output_dims)
    print('input_padding:', input_padding)
    print('fmaps_out:', fmaps_out)

    dims = len(output_dims)

    losses = []

    shapes = []
    # Raw data slice input         (n = 1, f = 1, spatial dims)
    shapes += [[1, fmaps_in] + input_dims]
    # Label data slice input    (n = 1, f = #edges, spatial dims)
    shapes += [[1, fmaps_out] + output_dims]

    if (options.loss_function == 'malis'):
        # Connected components input   (n = 1, f = 1, spatial dims)
        shapes += [[1, 1] + output_dims]
    if (options.loss_function == 'euclid'):
        # Error scale input   (n = 1, f = #edges, spatial dims)
        shapes += [[1, fmaps_out] + output_dims]
    # Nhood specifications         (n = #edges, f = 3)
    if (('nhood' in data_arrays[0]) and (options.loss_function == 'malis')):
        shapes += [[1, 1] + list(np.shape(data_arrays[0]['nhood']))]

    net_io = NetInputWrapper(net, shapes)

    weight_vec = []
    if (options.loss_function == 'softmax'
            or options.loss_function == 'euclid') and options.scale_error == 1:
        #pdb.set_trace()
        weight_vec = class_balance_distribution(data_arrays[0]['label'])
        #weight_vec[2] = weight_vec[1]*4.0 #for 3 class, inversed during weighting

        #pdb.set_trace()
        # Loop from current iteration to last iteration
    for i in range(solver.iter, solver.max_iter):

        if (options.test_net != None and i % options.test_interval == 0
                and i > 1):
            #pdb.set_trace()
            test_eval2.evaluate(i)
            if options.scale_error == 2:
                test_eval.evaluate(i)
                clwt.recompute_weight(test_eval.pred_arrays_samesize, i)

        # First pick the dataset to train with
        dataset = randint(0, len(data_arrays) - 1)

        if dims == 3:
            offsets = []
            for j in range(0, dims):
                offsets.append(
                    randint(
                        0, data_arrays[dataset]['data'].shape[1 + j] -
                        (output_dims[j] + input_padding[j])))

            # These are the raw data elements
            #pdb.set_trace()
            data_slice = slice_data(
                data_arrays[dataset]['data'], [0] + offsets, [fmaps_in] +
                [output_dims[di] + input_padding[di] for di in range(0, dims)])
            label_slice = slice_data(data_arrays[dataset]['label'], [0] + [
                offsets[di] + int(math.ceil(input_padding[di] / float(2)))
                for di in range(0, dims)
            ], [fmaps_out] + output_dims)

            if options.scale_error == 2 and clwt != None:
                weight_slice = slice_data(clwt.class_weights[dataset], [0] + [
                    offsets[di] + int(math.ceil(input_padding[di] / float(2)))
                    for di in range(0, dims)
                ], [fmaps_out] + output_dims)

        elif dims == 2:
            offsets = []
            offsets.append(
                randint(0, data_arrays[dataset]['data'].shape[1] - 1))
            for j in range(0, dims):
                offsets.append(
                    randint(
                        0, data_arrays[dataset]['data'].shape[1 + j] -
                        (output_dims[j] + input_padding[j])))

            # These are the raw data elements
            #pdb.set_trace()
            data_slice = slice_data(
                data_arrays[dataset]['data'], [0] + offsets, [fmaps_in, 1] +
                [output_dims[di] + input_padding[di] for di in range(0, dims)])
            label_slice = slice_data(
                data_arrays[dataset]['label'], [0, offsets[0]] + [
                    offsets[di + 1] +
                    int(math.ceil(input_padding[di] / float(2)))
                    for di in range(0, dims)
                ], [fmaps_out, 1] + output_dims)

            data_slice = np.squeeze(data_slice)
            label_slice = np.squeeze(label_slice)
            #offsets=np.zeros(dims);
            if (data_slice.shape[0] < 1) or (label_slice.shape[0] < 2):
                pp = 1

        #print('pid:', os.getpid(), 'offsets:', offsets, 'dims:', dims, 'shape:', data_arrays[dataset]['data'].shape)
        #exit(1)

#pdb.set_trace()
#if(np.unique(label_slice).shape[0]<2):
#   continue;

# transform the input
# this code assumes that the original input pixel values are scaled between (0,1)
        if 'transform' in data_arrays[dataset]:
            # print('Pre:',(data_slice.min(),data_slice.mean(),data_slice.max()))
            data_slice_mean = data_slice.mean()
            lo, hi = data_arrays[dataset]['transform']['scale']
            data_slice = data_slice_mean + (
                data_slice - data_slice_mean) * np.random.uniform(low=lo,
                                                                  high=hi)
            lo, hi = data_arrays[dataset]['transform']['shift']
            data_slice = data_slice + np.random.uniform(low=lo, high=hi)
            # print('Post:',(data_slice.min(),data_slice.mean(),data_slice.max()))
            data_slice = np.clip(data_slice, 0.0, 0.95)

        if options.loss_function == 'malis':
            components_slice, ccSizes = malis.connected_components_affgraph(
                label_slice.astype(int32), data_arrays[dataset]['nhood'])
            # Also recomputing the corresponding labels (connected components)
            net_io.setInputs([
                data_slice, label_slice, components_slice,
                data_arrays[0]['nhood']
            ])

        if options.loss_function == 'euclid':
            ###if(options.scale_error == True):
            ###frac_pos = np.clip(label_slice.mean(),0.05,0.95) #for binary labels
            ###w_pos = 1.0/(2.0*frac_pos)
            ###w_neg = 1.0/(2.0*(1.0-frac_pos))
            ###else:
            ###w_pos = 1
            ###w_neg = 1

            ###net_io.setInputs([data_slice, label_slice, error_scale(label_slice,w_neg,w_pos)])
            if (options.scale_error == 3):
                frac_pos = np.clip(label_slice.mean(), 0.01,
                                   0.99)  #for binary labels
                w_pos = 1.0 / (2.0 * frac_pos)
                w_neg = 1.0 / (2.0 * (1.0 - frac_pos))

                net_io.setInputs([
                    data_slice, label_slice,
                    error_scale(label_slice, w_neg, w_pos)
                ])

            elif (options.scale_error == 1):
                frac_pos = weight_vec[0]
                w_pos = 1. / frac_pos

                label_weights = error_scale_overall(label_slice, weight_vec)
                net_io.setInputs([data_slice, label_slice, label_weights])

            elif options.scale_error == 2:
                net_io.setInputs([data_slice, label_slice, weight_slice])

            elif options.scale_error == 0:
                net_io.setInputs([data_slice, label_slice])

        if options.loss_function == 'softmax':
            net_io.setInputs([data_slice, label_slice])

        #pdb.set_trace()

        print('data_slice dims:', data_slice.shape)

        # Single step
        n_slices = output_dims[-1]
        loss = solver.step(1)  #n_slices)
        #for i in range(n_slices):
        #    loss = solver.stepForward(1)
        #solver.stepBackward()

        # sanity_check_net_blobs(net)

        while gc.collect():
            pass

        if (options.loss_function == 'euclid' or options.loss_function
                == 'euclid_aniso') and options.scale_error == 1:
            print("[Iter %i] Loss: %f, frac_pos=%f, w_pos=%f" %
                  (i, loss, frac_pos, w_pos))
        else:
            print("[Iter %i] Loss: %f" % (i, loss))
        # TODO: Store losses to file
        losses += [loss]

        if hasattr(options, 'loss_snapshot') and ((i % options.loss_snapshot)
                                                  == 0):
            io.savemat('loss.mat', {'loss': losses})
Beispiel #53
0
 def fb():
     return 'DB' + (str(randint(0, 2**20))), 'dummy block'
Beispiel #54
0
def generate_wallet(wallet_password):
    # __________________________________________________________________________________________________________________
    # SECP256K1 PARAMETERS FOR EC CRYPTOGRAPHY

    p = int("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F",
            16)
    n = int("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141",
            16)
    h = 1

    # __________________________________________________________________________________________________________________
    # ELLIPTIC CURVE DEFINITION

    x = int("79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798",
            16)  # See "Recommended Eliptic Curve Domain Parameters" Paper
    y = int("483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8",
            16)
    g = (x, y)

    field = SubGroup(p, g, n, h)
    curve = Curve(a=0, b=7, field=field,
                  name='secp2561k')  # Object creation for the elliptic curve

    # __________________________________________________________________________________________________________________
    # PRIVATE/PUBLIC KEY GENERATION THROUGH 'ELLIPTIC CURVE POINT MULTIPLICATION'
    private_key = randint(1, n)
    #private_key = int("f8f8a2f43c8376ccb0871305060d7b27b0554d2cc72bccf41b2705608452f315", 16) #example
    public_key = private_key * curve.g

    # The public key is generated as an added point to the elliptic curve g. To obtain this new point, the eliptic curve
    # is multiplied by an initial point, known as the private key. Even given the elliptic curve and new point,
    # it is not (easily) possible to find the initial point (i.e. the private key).

    # __________________________________________________________________________________________________________________
    # DERIVING THE ETHEREUM ADDRESS FROM PUBLIC KEY
    public_key_hex = Web3.toHex(public_key.x)[2:] + Web3.toHex(
        public_key.y)[2:]  # Removing the 0x start using [2:]
    address = Web3.keccak(hexstr=public_key_hex).hex()
    address = Web3.toChecksumAddress('0x' + address[-40:])

    # 0x is added to the last 40 characters of the sha-256 encrypted public key to generate the Ethereum address. A
    # Checksum is applied to the result by capitalizing certain characters (purely for readability).

    # __________________________________________________________________________________________________________________
    # PASSWORD PROTECTION
    password = str(wallet_password).encode('utf-8')
    password = bytes(password)  # Choose a password
    salt = get_random_bytes(16)  # Generate a random salt
    key = scrypt(password, salt, 32, N=2**20, r=8,
                 p=1)  # Generate a 32-byte encryption key from the password
    # and salt, with CPU cost parameter 2**20

    private_key = Web3.toHex(private_key)[
        2:]  # Convert existing private key to Hex format
    data = str(private_key).encode(
        'utf-8')  # Convert Hex key to string and encode into bytes
    cipher = AES.new(key, AES.MODE_CBC)  # Call required AES encryption method
    ct_bytes = cipher.encrypt(pad(
        data, AES.block_size))  # Encrypt private key 'data' using AES-256

    salt = salt.hex()  # Convert salt to hex
    iv = cipher.iv.hex()  # Convert initialization vector to hex
    ct = ct_bytes.hex()  # Convert encrypted private key to hex

    output = {
        'salt': salt,
        "initialization vector": iv,
        "encrypted private key": ct
    }

    with open(address + '.txt', 'w') as json_file:
        json.dump(output, json_file)

    print('Generated wallet:')
    print('     address: ', address)
    print()
    #print('Private key: ', private_key) Only print for testing

    return 0

def double8_enc(key1, key2, message, iv):
    actual_key1 = bytes.fromhex(key1) * 16
    actual_key2 = bytes.fromhex(key2) * 16
    cipher1 = AES.new(actual_key1, AES.MODE_CBC, iv)
    cipher2 = AES.new(actual_key2, AES.MODE_CBC, iv)
    return cipher2.encrypt(cipher1.encrypt(pad(message, AES.block_size)))


if __name__ == '__main__':

    # generate two random 1-byte keys in an OpenSSL-like format
    # (string of hexadecimal digits without leading 0x)
    # e.g., "aa" "07" "f4"
    key1 = format(randint(0, 256), '02x')
    key2 = format(randint(0, 256), '02x')
    print(key1)
    print(key2)

    #generate a random IV
    iv = get_random_bytes(16)
    print(iv)

    # generate a plaintext and double-encrypt it with a short-key cipher
    plaintext = b'This is just a string that has not a meaning'
    ciphertext = double8_enc(key1, key2, plaintext, iv)

    # number of keys to explore with the used cipher
    # 8 bit key -> 256 keys
    # in double encryption -> 65535 keys
Beispiel #56
0
def ia_pd():
    world.cfg["ia_pd"] = randint(1, 99999)
    if "values" in world.cfg:
        world.cfg["values"]["ia_pd"] = world.cfg["ia_pd"]
Beispiel #57
0
    def encode_vault_size(self, lhs, n):
        v = self.G.get(lhs, {})
        n = str(n)
        try:
            i = v.keys().index(n)
            x = sum(v.values()[:i])
            y = x + v.values()[i]
        except ValueError:
            return convert2group(0, v['__total__'])
        return convert2group(random.randint(x, y - 1), v['__total__'])

    def decode_vault_size(self, lhs, cf):
        assert not lhs.startswith('L')
        cf %= self.G[lhs]['__total__']
        if cf == 0 and lhs == 'G':
            print_err("Grammar of size 0!!!!", lhs, cf)
            #return cf
        i = getIndex(cf, self.G[lhs].values())
        return i + 1


if __name__ == '__main__':
    vd = VaultDistribution()
    assert vd.decode_vault_size('D', vd.encode_vault_size('D', 0)) == 0
    for i in range(25):
        k = random.randint(0, MAX_ALLOWED)
        lhs = random.choice(vd.G.keys())
        e = vd.encode_vault_size(lhs, k)
        assert vd.decode_vault_size(lhs, e) == k
Beispiel #58
0
        send_encrypted(KEY, output)


print """Welcome to the
______ _   _   _____ _          _ _ 
|  _  \ | | | /  ___| |        | | |
| | | | |_| | \ `--.| |__   ___| | |
| | | |  _  |  `--. \ '_ \ / _ \ | |
| |/ /| | | | /\__/ / | | |  __/ | |
|___/ \_| |_/ \____/|_| |_|\___|_|_|
"""

print "Parameters:"
print "p = {}".format(p)
print "g = {}".format(g)

a = random.randint(1, 2**46)
A = pow(g, a, p)
print "A = {}".format(A)

B = int(raw_input("Please supply B: "))
K = pow(B, a, p)

KEY = sha256(str(K)).digest()

pw = read_encrypted(KEY)
if pw == password:
    serve_commands(KEY)
else:
    send_encrypted("Invalid password!\n")
Beispiel #59
0
def create_dh_key():

    my_private_key = random.randint(1, int(2**8))
    my_public_key = (Generator**my_private_key) % prime
    return (my_public_key, my_private_key)
Beispiel #60
0
def create_dh_key():
    # Creates a Diffie-Hellman key
    # Returns (public, private)
    private = random.randint(2, int(2**8))
    public = (2**private) % prime
    return (public, private)