コード例 #1
0
ファイル: solver.py プロジェクト: fengxl3320/ctf-2
def sanity():
    bits = 1024
    p = getStrongPrime(bits / 2)
    q = getStrongPrime(bits / 2)
    n = p * q
    n2 = n * n
    k = getRandomRange(0, n)
    g = (1 + k * n) % n2
    sk1 = LCM(p - 1, q - 1)
    sk2 = inverse(L(pow(g, sk1, n2), n), n)
    pt = getRandomInteger(bits - 1)

    ct = encrypt(pt, g, n, n2)
    mult = 123
    ct20 = pow(ct, mult, n2)
    print(decrypt(ct20, sk1, sk2, n, n2) == (mult * pt) % n)
    divisor = 123
    ct_2 = pow(ct, inverse(divisor, n), n2)
    print(divisor * decrypt(ct_2, sk1, sk2, n, n2) % n == pt)
    add = 123
    ct_add = ct * encrypt(add, g, n, n2)
    print(decrypt(ct_add, sk1, sk2, n, n2) == (pt + add) % n)
    sub = 123
    ct_sub = ct * encrypt(n - sub, g, n, n2)
    print(decrypt(ct_sub, sk1, sk2, n, n2) == (pt - sub) % n)
    ct_comb = pow(ct * encrypt(sub, g, n, n2), mult, n2)
    print(decrypt(ct_comb, sk1, sk2, n, n2) == (mult * (pt + sub)) % n)
    ct_comb2 = pow(ct, mult, n2) * encrypt(sub, g, n, n2)
    print(decrypt(ct_comb2, sk1, sk2, n, n2) == (mult * pt + sub) % n)
コード例 #2
0
ファイル: common.py プロジェクト: Waterdrop-team/writeups
def create_key(lowlimit, uplimit):
    if lowlimit < 0.25 or uplimit < 0.25:
        return (0, 0)
    if lowlimit > 0.4 or uplimit > 0.4:
        return (0, 0)
    Nsize = 1280
    pqsize = Nsize // 2
    N = 0
    while (N.bit_length() != Nsize):
        while True:
            p = number.getStrongPrime(pqsize)
            q = number.getStrongPrime(pqsize)
            if abs(p - q).bit_length() > (Nsize * 0.496):
                break
        N = p * q
    phi = (p - 1) * (q - 1)
    while True:
        d = number.getRandomRange(pow(2, int(Nsize * lowlimit)),
                                  pow(2,
                                      int(Nsize * uplimit) + 1))
        if number.GCD(d, phi) != 1:
            continue
        e = number.inverse(d, phi)
        if number.GCD(e, phi) != 1:
            continue
        break
    return (N, e)
コード例 #3
0
ファイル: p5.py プロジェクト: lewistg/RSA
def main():
	#print getMultInv(23, 120)
	#print getMultInv(15, 26)
	e = 65537
	p = 0
	q = 0 
	phiOfN = 0
	while True:
		p = number.getStrongPrime(512)
		q = number.getStrongPrime(512)
		phiOfN = (p - 1)*(q - 1)
		if getMultInv(e, phiOfN)[0]:
			break
	print "p: " + str(p)
	print "q: " + str(q)

	n = p * q
	print "n: " + str(n)

	multInv = getMultInv(e, phiOfN)
	assert(multInv[0])
	d = multInv[1]
	print "d: " + str(d)

	m = long(raw_input("Message to encrypt: "))
	print "Encrypted message: " + str(modExp(m, e, n))

	msgToDecrypt = long(raw_input("Message to decrypt: "))
	print modExp(msgToDecrypt, d, n)
コード例 #4
0
def setup(fileName):
	# Create Strong prime and RSA modulus
	pPrime = number.getStrongPrime(1024)
	qPrime = number.getStrongPrime(1024)
	p = (pPrime-1)/ 2
	q = (qPrime-1)/ 2
	RSAn   = p*q
	RSAN   = pPrime * qPrime
	
	# Choose a generator of QR
	gPerp = generatorOfQR(RSAN)

	# Create Public Key
	xG = number.getRandomInteger(1023)
	xH = number.getRandomInteger(1023)
	xS = number.getRandomInteger(1023)
	xZ = number.getRandomInteger(1023)
	xR = number.getRandomInteger(1023)

	G = safePow(gPerp, xG, RSAN)
	H = safePow(gPerp, xH, RSAN)
	S = safePow(H, xS, RSAN)
	Z = safePow(H, xZ, RSAN)
	R = safePow(H, xR, RSAN)

	# Create Prime Order Group
	( pGroup, qGroup, u) = createPrimeOrderGroup( pPrime, qPrime, RSAN)
	
	pubKey = publicKey()
	pubKey.set( RSAN, gPerp, G, H, S, Z, R, pGroup, qGroup, u)
	prvKey = privateKey()
	prvKey.set( pPrime, qPrime, RSAN, gPerp, G, H, S, Z, R, pGroup, qGroup, u)

	pubKey.write(fileName+".pubkey")
	prvKey.write(fileName+".prvkey")
コード例 #5
0
def getCoprimes(bitsize, e=e):
    p1, p2 = -1, -1
    while p1 == p2:
        p1 = number.getStrongPrime(bitsize, e)
        p2 = number.getStrongPrime(bitsize, e)
        assert (gcd(e, p1 - 1) == 1)
        assert (gcd(e, p2 - 1) == 1)
    return p1, p2
コード例 #6
0
    def generate_pair(self, key_size=1024, e=3):
        self.e = e
        p = number.getStrongPrime(N=key_size // 2, e=e)
        q = number.getStrongPrime(N=key_size // 2, e=e)
        self.public_key = p * q

        et = (p - 1) * (q - 1)
        self._private_key = invmod(e, et)
コード例 #7
0
def genprimes_server():
    b = number.getStrongPrime(4096, 6)
    k = number.getStrongPrime(4096, 6)
    n = number.getStrongPrime(4096, 6)
    with open(SERVER_SAV, 'w') as f:
        f.writelines(str(b) + '\n')
        f.writelines(str(k) + '\n')
        f.writelines(str(n) + '\n')
    return True
コード例 #8
0
def getCoprimes(e = 65537):
    bitSize = 512
    p1, p2 = -1, -1
    while p1 == p2:
        p1 = getStrongPrime(bitSize, e)
        p2 = getStrongPrime(bitSize, e)
    assert(GCD(e, p1 - 1) == 1)
    assert(GCD(e, p2 - 1) == 1)
    return p1, p2
コード例 #9
0
def generate_primes(key_size):
    assert key_size > 512, "key_size need to be greater than 512"
    assert key_size % 128 == 0, "key_size need to be a multiple of 128"

    p = number.getStrongPrime(key_size)

    while True:
        q = number.getStrongPrime(key_size)
        if p != q:
            return p, q
コード例 #10
0
def genParams():
    while 1:
        p = getStrongPrime(1024)
        q = getStrongPrime(1024)
        n = p * q
        phi = (p-1) * (q-1)
        try:
            d = gmpy2.invert(e, phi)
            return (n, phi, d)
        except ZeroDivisionError:
            genParams()
コード例 #11
0
	def __init__(self, size):
		#self.e = 65537
		self.e = 3
		if size < 1024:
			p = getPrime(size // 2)
			q = getPrime(size // 2)
		else:
			p = getStrongPrime(size // 2, self.e)
			q = getStrongPrime(size // 2, self.e)
		self.n = p * q
		self.phi = (p - 1) * (q - 1)
		self.d = mod_inv(self.e, self.phi)
コード例 #12
0
ファイル: lab4.py プロジェクト: mrlzla/mzi
def generate_keys(size):
    a = getStrongPrime(size)
    b = getStrongPrime(size)
    n = a * b
    fi = (a - 1) * (b - 1)

    while (True):
        e = 2**(2**random.choice(range(5, int(log(size, 2) - 2)))) + 1
        if egcd(fi, e)[0] == 1:
            break

    d = div_by_mod(1, e, fi)
    return (e, n), (d, n)
コード例 #13
0
def rsa_genkeys(bits, e):
    bits = bits / 2
    et = e
    while GCD(e, et) != 1:
        if bits < 512:
            p, q = getPrime(bits), getPrime(bits)
        else:
            p, q = getStrongPrime(bits, e), getStrongPrime(bits, e)
        et = (p-1) * (q-1)

    n = p * q
    d = invmod(e, et)
    return (e,n), (d,n)
コード例 #14
0
def genRSA_keypair(keysize):

    p = number.getStrongPrime(keysize // 2, e=3)
    q = number.getStrongPrime(keysize // 2, e=3)

    n = (p * q)

    et = (p - 1) * (q - 1)
    e = 3

    d = invmod(e, et)

    return (e, d, n)
コード例 #15
0
ファイル: RSA.py プロジェクト: johndpope/cryptopals
def generate_keys(size=SIZE, e=65537):
    if size < 1024:
        # getStrongPrime can only output >= 512 bit primes
        p = getPrime(size // 2)
        q = getPrime(size // 2)
    else:
        p = getStrongPrime(size // 2, e)
        q = getStrongPrime(size // 2, e)
    n = p * q
    phi = (p - 1) * (q - 1)
    d = util.modinv(e, phi)
    public_key = (e, n)
    private_key = (d, n)
    return public_key, private_key
コード例 #16
0
ファイル: crypto06.py プロジェクト: mteodoro/crypto_challenge
def rsa_genkeys(bits, e):
    bits = bits / 2
    et = e
    while GCD(e, et) != 1:
        if bits < 512:
            #getStrongPrime won't accept bits < 512
            p, q = getPrime(bits), getPrime(bits)
        else:
            p, q = getStrongPrime(bits, e), getStrongPrime(bits, e)
        et = (p-1) * (q-1)

    n = p * q
    d = invmod(e, et)
    return (e,n), (d,n)
コード例 #17
0
ファイル: key_gen.py プロジェクト: liamradley1/RSA-Algorithm
def generateKeys2(n_length):  # Returns a 2048 bit private key with same prime
    if (n_length < 2048):
        raise ValueError(
            "Key length must be at least 2048 to ensure security.")
    e = 65537
    p = number.getStrongPrime(
        int(n_length / 2)
    )  # strong prime false-positive probability as that of the RSA subroutine.
    q = number.getStrongPrime(int(n_length / 2))
    if (p == q):
        q = number.getStrongPrime(n_length)
    n = p * q
    totient = carmichaelFunction(p, q)
    d = modInv(e, totient)
    keys = RSA.construct((n, e, d, p, q))
    return keys
コード例 #18
0
ファイル: mpc.py プロジェクト: zhangji1810/CTF_repo
def paillier_keygen():
    # Returns (pk, sk)
    p = number.getStrongPrime(512)
    q = number.getStrongPrime(512)
    n = p * q
    lam = (p - 1) * (q - 1) / 2
    while True:
        g = random.randrange(n**2)
        if number.GCD(g, n) != 1:
            continue
        mu_inv = L(pow(g, lam, n**2), n)
        if number.GCD(mu_inv, n) != 1:
            continue
        mu = number.inverse(mu_inv, n)
        break
    return (n, g), (lam, mu)
コード例 #19
0
ファイル: chall.py プロジェクト: timmykang/study
def paillier_enc(m, p, noise):
    p = next_prime(p + noise)
    q = getStrongPrime(512)
    n = p * q
    g = (1 + prng.rand() * n) % n**2
    c = pow(g, m, n**2) * pow(prng.rand(), n, n**2) % n**2
    return n, g, c
コード例 #20
0
ファイル: mpc.py プロジェクト: GG00/write-ups-2017
def paillier_keygen():
  # Returns (pk, sk)
  p = number.getStrongPrime(512)
  q = number.getStrongPrime(512)
  n = p*q
  lam = (p-1)*(q-1)/2
  while True:
    g = random.randrange(n**2)
    if number.GCD(g, n) != 1:
      continue
    mu_inv = L(pow(g, lam, n**2), n)
    if number.GCD(mu_inv, n) != 1:
      continue
    mu = number.inverse(mu_inv, n)
    break
  return (n, g), (lam, mu)
コード例 #21
0
 def init_key(self):
     p = number.getStrongPrime(self.ln//2)
     q = number.getStrongPrime(self.ln//2)
     n = p*q
     randlis = [random.randrange(0, 1<<1024) for _ in range(4)]
     rand2lis = list(map(lambda x: pow(x, 2, n) ,randlis))
     h = rand2lis[3]
     r = random.randrange(100)
     g = pow(h, r, n)
     self.n = str(n)
     self.a = str(rand2lis[0])
     self.b = str(rand2lis[1])
     self.c = str(rand2lis[2])
     self.h = str(rand2lis[3])
     self.p = str(p)
     self.g = str(g)
コード例 #22
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
コード例 #23
0
def generate_keys(prime_size = 768):
    p = getStrongPrime(prime_size)
    while mpz(p) % 4 != 3:
        p = getStrongPrime(prime_size)
    
    # Use more bits to prevent factorization    
    q = getStrongPrime(prime_size + 128)
    while mpz(q) % 4 != 3:
        q = getStrongPrime(prime_size + 128)
    
    p = mpz(p)
    q = mpz(q)
    
    n = p * q
     
    keys = {'pub': n, 'priv': (p, q)}
    return keys
コード例 #24
0
def generateKey():
    p = getStrongPrime(N)
    q = (p - 1) // 2
    x = getRandomRange(2, q)
    g = 2
    h = pow(g, x, p)
    pk = (p, q, g, h)
    sk = x
    return (pk, sk)
コード例 #25
0
ファイル: chall.py プロジェクト: yen102/write-up
def paillier_enc(m, p, noise):
    p = next_prime(p + noise)
    q = getStrongPrime(512)
    n = p * q
    key = prng.rand()
    g = (1 + key * n) % n**2
    r = prng.rand()
    c = pow(g, m, n**2) * pow(r, n, n**2) % n**2
    return n, g, c
コード例 #26
0
def keygen():
    y = number.getStrongPrime(1024)
    x = number.getStrongPrime(512)
    good = 0
    while good != 1:
        z = number.getRandomRange(1, x)
        g = mygcd(z, x)
        while g != 1:
            z = number.getRandomRange(1, x)
            g = mygcd(z, x)
        n = x * y * z
        e = (pow(x, 3) + (y * x) + z)
        t = (((x - 1) * (y - 1) * (z - 1)) * (e - 1))
        pk = e
        sk = multiplicative_inverse(e, t)
        if pk != None:
            if testencrypt(pk, sk, n):
                good = 1
    return sk, pk, n
コード例 #27
0
    def generateKey(self, key_size, pq=None):
        if pq is None:
            p = getStrongPrime(key_size)
            q = getStrongPrime(key_size)
        else:
            p, q = pq
        n = p * q

        while True:
            # Keep trying random numbers for e until one is valid.
            e = random.randrange(2**(key_size - 1), 2**key_size)
            if pubkey.GCD(e, (p - 1) * (q - 1)) == 1:
                break

        d = pubkey.inverse(e, (p - 1) * (q - 1))

        self.n = n
        self.e = e
        self.d = d
        self.pq = (p, q)
コード例 #28
0
def paillier_enc(m, p, noise):
    p = next_prime(p + noise)
    q = getStrongPrime(512)
    n = p * q
    # g is much smaller than n**2, so we can retrieve prng.rand() for each
    # share
    g = (1 + prng.rand() * n) % n**2
    # Here we can find all the m from (1 + n)^x = 1 + nx [n^2]
    # <=> (1 + kn)^x = 1 + knx [(kn)^2]
    c = pow(g, m, n**2) * pow(prng.rand(), n, n**2) % n**2
    return n, g, c
コード例 #29
0
ファイル: Diffie-Hellman.py プロジェクト: jvansteeter/CS465
 def run(self):
     g = 5
     p = number.getStrongPrime(512)
     s = number.getRandomInteger(512)
     public = modExp(g, s, p)
     print "p= " + str(p)
     print "s= " + str(s)
     print "public= " + str(public)
     gtp = int(raw_input("g^t mod p: "))
     key = modExp(gtp, s, p)
     print "key= " + str(key)
コード例 #30
0
ファイル: test_number.py プロジェクト: 26618929/pycrypto
 def test_getStrongPrime(self):
     """Util.number.getStrongPrime"""
     self.assertRaises(ValueError, number.getStrongPrime, 256)
     self.assertRaises(ValueError, number.getStrongPrime, 513)
     bits = 512
     x = number.getStrongPrime(bits)
     self.assertNotEqual(x % 2, 0)
     self.assertEqual(x > (1L << bits-1)-1, 1)
     self.assertEqual(x < (1L << bits), 1)
     e = 2**16+1
     x = number.getStrongPrime(bits, e)
     self.assertEqual(number.GCD(x-1, e), 1)
     self.assertNotEqual(x % 2, 0)
     self.assertEqual(x > (1L << bits-1)-1, 1)
     self.assertEqual(x < (1L << bits), 1)
     e = 2**16+2
     x = number.getStrongPrime(bits, e)
     self.assertEqual(number.GCD((x-1)>>1, e), 1)
     self.assertNotEqual(x % 2, 0)
     self.assertEqual(x > (1L << bits-1)-1, 1)
     self.assertEqual(x < (1L << bits), 1)
コード例 #31
0
 def test_getStrongPrime(self):
     """Util.number.getStrongPrime"""
     self.assertRaises(ValueError, number.getStrongPrime, 256)
     self.assertRaises(ValueError, number.getStrongPrime, 513)
     bits = 512
     x = number.getStrongPrime(bits)
     self.assertNotEqual(x % 2, 0)
     self.assertEqual(x > (1 << bits - 1) - 1, 1)
     self.assertEqual(x < (1 << bits), 1)
     e = 2**16 + 1
     x = number.getStrongPrime(bits, e)
     self.assertEqual(number.GCD(x - 1, e), 1)
     self.assertNotEqual(x % 2, 0)
     self.assertEqual(x > (1 << bits - 1) - 1, 1)
     self.assertEqual(x < (1 << bits), 1)
     e = 2**16 + 2
     x = number.getStrongPrime(bits, e)
     self.assertEqual(number.GCD((x - 1) >> 1, e), 1)
     self.assertNotEqual(x % 2, 0)
     self.assertEqual(x > (1 << bits - 1) - 1, 1)
     self.assertEqual(x < (1 << bits), 1)
コード例 #32
0
ファイル: dis.py プロジェクト: xuan2261/ctf
def create_key():
    if not False:

        # 29
        Nsize = NSIZE
        pqsize = Nsize / 2
        N = 0
        while N.bit_length() != Nsize:  # 51, loop
            while True:
                p = number.getStrongPrime(pqsize)
                q = number.getStrongPrime(pqsize)

                if (abs(p - q)).bit_length() > Nsize * 0.496:
                    break
            N = p * q
        phi = (p - 1) * (q - 1)

        limit1 = 0.261
        limit2 = 0.293
        while True:
            d = number.getRandomRange(pow(2, int(Nsize * limit1)),
                                      pow(2,
                                          int(Nsize * limit1) + 5))
            while d.bit_length() < Nsize * limit2:
                ppp = 0
                while not number.isPrime(ppp):
                    ppp = number.getRandomRange(pow(2, 45),
                                                pow(2, 45) + pow(2, 12))

                d *= ppp
            if number.GCD(d, phi) != 1:
                continue
            e = number.inverse(d, phi)
            if number.GCD(e, phi) != 1:
                continue
            break

        zzz = 3
    return (N, e)
コード例 #33
0
    def __init__(self, n, k, prime_size=1024):
        '''	
			n: total number of keys for the voter
			k: the required number of votes
			prime_size: number of bits for the prime number, default:1024
							Must be a multiple of 64
		'''
        self.prime_size = prime_size
        self.p = number.getStrongPrime(prime_size, false_positive_prob=1e-10)
        self.n = n
        self.k = k
        self.values = [[], []]
        self.pubKey = None
コード例 #34
0
def TestOneInput(data):
    if len(data) < 30:
        return

    fdp = atheris.FuzzedDataProvider(data)
    try:
        x = number.getStrongPrime(
            N=fdp.ConsumeIntInRange(0, 9999),
            e=fdp.ConsumeIntInRange(0, 99999999999),
            false_positive_prob=fdp.ConsumeFloat(),
        )
    except ValueError as e:
        pass
コード例 #35
0
def generer_cle_RSA(n):
    # Generation of two 1024bits prime number and N processing
    p = number.getStrongPrime(n)
    q = number.getStrongPrime(n)
    N = p*q

    pk = []
    pk.append(N)
    sk = []
    sk.append(p)
    sk.append(q)

    phiN = (p-1)*(q-1)
    e = 2
    while math.gcd(e, phiN) != 1 :
        e = random.randint(50000,1000000000000)
        
    d = number.inverse(e, phiN)

    pk.append(e)
    sk.append(d)

    return pk, sk
コード例 #36
0
ファイル: crypto05.py プロジェクト: mteodoro/crypto_challenge
def cc39():
    """39. Implement RSA

There are two annoying things about implementing RSA. Both of them
involve key generation; the actual encryption/decryption in RSA is
trivial.

First, you need to generate random primes. You can't just agree on a
prime ahead of time, like you do in DH. You can write this algorithm
yourself, but I just cheat and use OpenSSL's BN library to do the
work.

The second is that you need an "invmod" operation (the multiplicative
inverse), which is not an operation that is wired into your
language. The algorithm is just a couple lines, but I always lose an
hour getting it to work.

I recommend you not bother with primegen, but do take the time to get
your own EGCD and invmod algorithm working.

Now:

- Generate 2 random primes. We'll use small numbers to start, so you
can just pick them out of a prime table. Call them "p" and "q".

- Let n be p * q. Your RSA math is modulo n.

- Let et be (p-1)*(q-1) (the "totient"). You need this value only for
keygen.

- Let e be 3.

- Compute d = invmod(e, et). invmod(17, 3120) is 2753.

Your public key is [e, n]. Your private key is [d, n].

To encrypt: c = m**e%n. To decrypt: m = c**d%n

Test this out with a number, like "42".

Repeat with bignum primes (keep e=3).

Finally, to encrypt a string, do something cheesy, like convert the
string to hex and put "0x" on the front of it to turn it into a
number. The math cares not how stupidly you feed it strings.
"""
    def encrypt(m, e, n):
        m = long(m.encode('hex'), 16)
        return pow(m, e, n)


    def decrypt(c, d, n):
        m = pow(c, d, n)
        m = hex(long(m))
        return m[2:-1].decode('hex')


    bits = 1024
    e = 3
    p, q = getStrongPrime(bits, e), getStrongPrime(bits, e)
    n = p * q
    et = (p-1) * (q-1)
    d = invmod(e, et)

    m = "Cooking MC's like a pound of bacon"
    print 'Encrypting:', m
    c = encrypt(m, e, n)
    print 'c:', c
    m = decrypt(c, d, n)
    print 'Decrypted: ', m
コード例 #37
0
ファイル: crypto05.py プロジェクト: mteodoro/crypto_challenge
def cc40():
    """40. Implement an E=3 RSA Broadcast attack

Assume you're a Javascript programmer. That is, you're using a
naive handrolled RSA to encrypt without padding.

Assume you can be coerced into encrypting the same plaintext
three times, under three different public keys. You can; it's
happened.

Then an attacker can trivially decrypt your message, by:

1. Capturing any 3 of the ciphertexts and their corresponding pubkeys

2. Using the CRT to solve for the number represented by the three
ciphertexts (which are residues mod their respective pubkeys)

3. Taking the cube root of the resulting number

The CRT says you can take any number and represent it as the
combination of a series of residues mod a series of moduli. In the
three-residue case, you have:

result =
  (c_0 * m_s_0 * invmod(m_s_0, n_0)) +
  (c_1 * m_s_1 * invmod(m_s_1, n_1)) +
  (c_2 * m_s_2 * invmod(m_s_2, n_2)) mod N_012

where:

  c_0, c_1, c_2 are the three respective residues mod
  n_0, n_1, n_2

  m_s_n (for n in 0, 1, 2) are the product of the moduli
  EXCEPT n_n --- ie, m_s_1 is n_0 * n_2

  N_012 is the product of all three moduli

To decrypt RSA using a simple cube root, leave off the
final modulus operation; just take the raw accumulated result and
cube-root it.
"""
    #http://stackoverflow.com/a/358134
    def nth_root(x,n):
        """Finds the integer component of the n'th root of x,
        an integer such that y ** n <= x < (y + 1) ** n.
        """
        high = 1
        while high ** n < x:
            high *= 2
        low = high/2
        while low < high:
            mid = (low + high) // 2
            if low < mid and mid**n < x:
                low = mid
            elif high > mid and mid**n > x:
                high = mid
            else:
                return mid
        return mid + 1


    m = "Now that the party is jumping"
    print 'Encrypting:', m
    m = long(m.encode('hex'), 16)
    bits = 1024
    e = 3

    pubkeys = [getStrongPrime(bits, e) * getStrongPrime(bits, e) for _ in xrange(3)]
    captures = [pow(m, e, n) for n in pubkeys]

    c0, c1, c2 = [c % n for c,n in zip(captures, pubkeys)]
    n0, n1, n2 = pubkeys
    ms0 = n1 * n2
    ms1 = n0 * n2
    ms2 = n0 * n1
    N012 = n0 * n1 * n2

    result = ((c0 * ms0 * invmod(ms0, n0)) +
            (c1 * ms1 * invmod(ms1, n1)) +
            (c2 * ms2 * invmod(ms2, n2))) % N012

    m = nth_root(result, 3)
    m = hex(long(m))
    m = m[2:-1].decode('hex')
    print 'Decrypted: ', m
コード例 #38
0
ファイル: cramer-shoup.py プロジェクト: do030b/cryptography
# -*- coding: utf-8 -*-
from Crypto.Util import number


if __name__ == '__main__':
    n_length = 1024

    q = number.getStrongPrime(n_length)

コード例 #39
0
ファイル: encryptMe.py プロジェクト: chris-clm09/rsa
def getPrimeP():
   return number.getStrongPrime(512)
コード例 #40
0
def genprime_client():
    a = number.getStrongPrime(4096, 6)
    with open(CLIENT_SAV, 'wb') as f:
        f.write(str(a).encode('utf-8'))
    return True
コード例 #41
0
ファイル: start.py プロジェクト: dwane-gard/security
    parser.add_option('-e', '--secret', dest='secret', default=512, help='Set how many bits long the secret number will'
                                                                         ' be [default=512]')
    options, args = parser.parse_args()
    alpha_tog = options.alpha
    beta_tog = options.beta
    verbose = options.verbose
    size = int(options.size)
    secret = int(options.secret)

    if alpha_tog is True and beta_tog is True:
        print("[!] Error: can't set both alpha and beta use one per instance")
        exit(1)
    try:
        if alpha_tog is True:
            a = getRandomInteger(secret) # This needs to be large, at least 512bit
            p = getStrongPrime(size)
            g = getStrongPrime(size)

            alpha = Alpha(p, g, a, verbose)
            alpha.exchange()
            alpha.output()
            exit()
        elif beta_tog is True:
            # b = get_random(size)
            b = getRandomInteger(secret) # This needs to be large, at least 512bit
            beta = Beta(b, verbose)
            beta.exchange()
            beta.output()
            exit()
    except PermissionError:
        print("[!] Error: you must have sudo permissions in order to broadcast")
コード例 #42
0
def randomPrime(length):
    return long_to_bytes(getStrongPrime(length, false_positive_prob=1e-40))