def testExportKey14(self): # Export and re-import the encrypted key. It must match. # DER envelope, PKCS#8, PKCS#8 encryption key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) outkey = key.export_key('DER', 'test', pkcs=8) inkey = RSA.importKey(outkey, 'test') self.assertEqual(key.n, inkey.n) self.assertEqual(key.e, inkey.e) self.assertEqual(key.d, inkey.d)
def testDecrypt1(self): # Verify decryption using all test vectors for test in self._testData: # Build the key comps = [ long(rws(test[0][x]),16) for x in ('n','e','d') ] key = RSA.construct(comps) # The real test cipher = PKCS.new(key, test[4]) pt = cipher.decrypt(t2b(test[2])) self.assertEqual(pt, t2b(test[1]))
def testExportKey12(self): # Export and re-import the encrypted key. It must match. # PEM envelope, PKCS#8, old PEM encryption key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) outkey = key.export_key('PEM', 'test', pkcs=8) self.failUnless(tostr(outkey).find('4,ENCRYPTED')!=-1) self.failUnless(tostr(outkey).find('BEGIN PRIVATE KEY')!=-1) inkey = RSA.importKey(outkey, 'test') self.assertEqual(key.n, inkey.n) self.assertEqual(key.e, inkey.e) self.assertEqual(key.d, inkey.d)
def testExportKey13(self): # Export and re-import the encrypted key. It must match. # PEM envelope, PKCS#8, PKCS#8 encryption key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) outkey = key.export_key('PEM', 'test', pkcs=8, protection='PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC') self.failUnless(tostr(outkey).find('4,ENCRYPTED')==-1) self.failUnless(tostr(outkey).find('BEGIN ENCRYPTED PRIVATE KEY')!=-1) inkey = RSA.importKey(outkey, 'test') self.assertEqual(key.n, inkey.n) self.assertEqual(key.e, inkey.e) self.assertEqual(key.d, inkey.d)
def key_from_b64(b64_key): binaryKey = base64.b64decode(b64_key) i = bytes_to_long(binaryKey[:4]) mod = bytes_to_long(binaryKey[4:4+i]) j = bytes_to_long(binaryKey[i+4:i+4+4]) exponent = bytes_to_long(binaryKey[i+8:i+8+j]) key = RSA.construct((mod, exponent)) return key
def deserialize(self): if self.n and self.e: try: for param in self.longs: item = getattr(self, param) if not item or isinstance(item, six.integer_types): continue else: try: val = long(deser(item)) except Exception: raise else: setattr(self, param, val) lst = [self.n, self.e] if self.d: lst.append(self.d) if self.p: lst.append(self.p) if self.q: lst.append(self.q) self.key = RSA.construct(tuple(lst)) else: self.key = RSA.construct(lst) except ValueError as err: raise DeSerializationNotPossible("%s" % err) elif self.x5c: der_cert = base64.b64decode(self.x5c[0].encode("ascii")) if self.x5t: # verify the cert if not b64d(self.x5t.encode("ascii")) == hashlib.sha1(der_cert).digest(): raise DeSerializationNotPossible("The thumbprint ('x5t') does not match the certificate.") self.key = der2rsa(der_cert) self._split() if len(self.x5c) > 1: # verify chain pass else: raise DeSerializationNotPossible()
def testEncrypt1(self): # Verify encryption using all test vectors for test in self._testData: # Build the key comps = [ long(rws(test[0][x]),16) for x in ('n','e') ] key = RSA.construct(comps) # RNG that takes its random numbers from a pool given # at initialization class randGen: def __init__(self, data): self.data = data self.idx = 0 def __call__(self, N): r = self.data[self.idx:N] self.idx += N return r # The real test cipher = PKCS.new(key, test[4], randfunc=randGen(t2b(test[3]))) ct = cipher.encrypt(t2b(test[1])) self.assertEqual(ct, t2b(test[2]))
def privatekeyblob_to_pkcs1(key): ''' parse private key into pkcs#1 format :param key: :return: ''' modulus = bytes_to_long(key['modulus'][::-1]) # n prime1 = bytes_to_long(key['prime1'][::-1]) # p prime2 = bytes_to_long(key['prime2'][::-1]) # q exp1 = bytes_to_long(key['exponent1'][::-1]) exp2 = bytes_to_long(key['exponent2'][::-1]) coefficient = bytes_to_long(key['coefficient'][::-1]) privateExp = bytes_to_long(key['privateExponent'][::-1]) # d if PY3: long = int pubExp = long(key['rsapubkey']['pubexp']) # e # RSA.Integer(prime2).inverse(prime1) # u r = RSA.construct((modulus, pubExp, privateExp, prime1, prime2)) return r
def testExportKey2(self): key = RSA.construct([self.n, self.e]) derKey = key.export_key("DER") self.assertEqual(derKey, self.rsaPublicKeyDER)
def testExportKey9(self): key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) self.assertRaises(ValueError, key.export_key, "invalid-format")
def testExportKey8(self): key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) pemKey = key.export_key("PEM", pkcs=8) self.assertEqual(pemKey, b(self.rsaKeyPEM8))
def testExportKey7(self): key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) derKey = key.export_key("DER", pkcs=8) self.assertEqual(derKey, self.rsaKeyDER8)
from Cryptodome.PublicKey import RSA from Cryptodome.Cipher import PKCS1_OAEP from gmpy2 import * public_key = RSA.importKey(open('../Files/oligarchy.pem', 'r').read()) n = public_key.n e = public_key.e r = 21700996784810065805847020455080940987640304282783092123992896363328128691169420271855815648912121417792054646557156071514079520782530801688062034321252682229729442734741486715339008457753023855600772948737800521010217600436912058582658334252483984244806083617513596479033871117464319239681526924092910597300 c = 85407181759755287105309527383534372436668736072315927293076398182206068631971587183149437554341349819060482477969350837066653250734556920049021810122548703168301872412719117857995283679569989680329696657609285728934732302846152702363240223251805773071022405764521081142920227557091217872210813095318042763847 k = 0 while True: k += 1 phi = r * k pq = n + 1 - phi delta = pq * pq - 4 * n p = (pq + isqrt(delta)) / 2 q = (pq - isqrt(delta)) / 2 if p * q == n: break d = long(invert(e, phi)) private_key = RSA.construct([n, e, d]) ciphertext = hex(c)[2:-1].decode('hex') cipher = PKCS1_OAEP.new(private_key) message = cipher.decrypt(ciphertext) print(message)
def testExportKey15(self): # Verify that that error an condition is detected when trying to # use a password with DER encoding and PKCS#1. key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) self.assertRaises(ValueError, key.export_key, 'DER', 'test', 1)
{ 'shaalg' : lambda x: x, 'result' : lambda x: x }) for count, tv in enumerate(test_vectors_verify): if isinstance(tv, basestring): continue if hasattr(tv, "n"): modulus = tv.n continue if hasattr(tv, "p"): continue hash_module = load_hash_by_name(tv.shaalg.upper()) hash_obj = hash_module.new(tv.msg) public_key = RSA.construct([bytes_to_long(x) for x in modulus, tv.e]) if tv.saltval != b("\x00"): prng = PRNG(tv.saltval) verifier = pss.new(public_key, salt_bytes=len(tv.saltval), rand_func=prng) else: verifier = pss.new(public_key, salt_bytes=0) def positive_test(self, hash_obj=hash_obj, verifier=verifier, signature=tv.s): verifier.verify(hash_obj, signature) def negative_test(self, hash_obj=hash_obj, verifier=verifier, signature=tv.s): self.assertRaises(ValueError, verifier.verify, hash_obj, signature) if tv.result == 'p': setattr(FIPS_PKCS1_Verify_Tests, "test_positive_%d" % count, positive_test) else:
{ 'shaalg' : lambda x: x, 'result' : lambda x: x }) for count, tv in enumerate(test_vectors_verify): if isinstance(tv, str): continue if hasattr(tv, "n"): modulus = tv.n continue if hasattr(tv, "p"): continue hash_module = load_hash_by_name(tv.shaalg.upper()) hash_obj = hash_module.new(tv.msg) public_key = RSA.construct([bytes_to_long(x) for x in (modulus, tv.e)]) # type: ignore if tv.saltval != b("\x00"): prng = PRNG(tv.saltval) verifier = pss.new(public_key, salt_bytes=len(tv.saltval), rand_func=prng) else: verifier = pss.new(public_key, salt_bytes=0) def positive_test(self, hash_obj=hash_obj, verifier=verifier, signature=tv.s): verifier.verify(hash_obj, signature) def negative_test(self, hash_obj=hash_obj, verifier=verifier, signature=tv.s): self.assertRaises(ValueError, verifier.verify, hash_obj, signature) if tv.result == 'p': setattr(FIPS_PKCS1_Verify_Tests_KAT, "test_positive_%d" % count, positive_test) else:
if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m p = 169530237952573748368189799955682467382981190128045440195079928264906866742107349991159212259885000722467900686913850878305620267449769263730115304350546079431887015026437175510788840243478206301763434168031512699332213142859495368291002844907298298139858769109574355617458546385307241287393358156444715347793 q = 152588087402514219857833878620153666945304685640627758617917943381504393210558706803164637632719012980584990911366861074062265597247464995913960044489757238590130973545737766726863067136702127127671612008426543868375658445766104812898282701044498346675255344027978615813725491513556318640569390490700167272861 phi_n = (p - 1)*(q - 1) e2 = generateLargePrime(256) while 'Failure' in str(e2)[:len('Failure')]: e2 = generateLargePrime(256) d2 = modinv(e2, phi_n) key2 = RSA.construct((p*q, e2, d2, p, q)) print "Private Key:\n" print key2.exportKey('PEM') print "Public Key:\n" print key2.publickey().exportKey('PEM')
def testExportKey1(self): key = RSA.construct( [self.n, self.e, self.d, self.p, self.q, self.pInv]) derKey = key.export_key("DER") self.assertEqual(derKey, self.rsaKeyDER)
def test_exportKey(self): key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) self.assertEqual(key.export_key(), key.exportKey())
def testExportKey4(self): key = RSA.construct([self.n, self.e]) pemKey = key.export_key("PEM") self.assertEqual(pemKey, b(self.rsaPublicKeyPEM))
def testExportKey5(self): key = RSA.construct([self.n, self.e]) openssh_1 = key.export_key("OpenSSH").split() openssh_2 = self.rsaPublicKeyOpenSSH.split() self.assertEqual(openssh_1[0], openssh_2[0]) self.assertEqual(openssh_1[1], openssh_2[1])
def __init__(self, der): key = ASN1Parser([x for x in der]) key = [key.getChild(x).value for x in range(1, 4)] key = [self.bytesToNumber(v) for v in key] self._rsa = _RSA.construct(key)