Python Crypto.PublicKey.RSA.construct() Examples
The following are 30
code examples of Crypto.PublicKey.RSA.construct().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
Crypto.PublicKey.RSA
, or try the search function
.
Example #1
Source File: keys.py From BitTorrent with GNU General Public License v3.0 | 7 votes |
def getPrivateKeyObject_agentv3(data, passphrase): if passphrase: raise BadKeyError("agent v3 key should not be encrypted") keyType, data = common.getNS(data) if keyType == 'ssh-dss': p, data = common.getMP(data) q, data = common.getMP(data) g, data = common.getMP(data) y, data = common.getMP(data) x, data = common.getMP(data) return DSA.construct((y,g,p,q,x)) elif keyType == 'ssh-rsa': e, data = common.getMP(data) d, data = common.getMP(data) n, data = common.getMP(data) u, data = common.getMP(data) p, data = common.getMP(data) q, data = common.getMP(data) return RSA.construct((n,e,d,p,q,u)) else: raise BadKeyError("unknown key type %s" % keyType)
Example #2
Source File: keys.py From BitTorrent with GNU General Public License v3.0 | 7 votes |
def getPrivateKeyObject_lsh(data, passphrase): #assert passphrase == '' data = ''.join(data) sexp = sexpy.parse(data) assert sexp[0] == 'private-key' kd = {} for name, data in sexp[1][1:]: kd[name] = common.getMP(common.NS(data))[0] if sexp[1][0] == 'dsa': assert len(kd) == 5, len(kd) return DSA.construct((kd['y'], kd['g'], kd['p'], kd['q'], kd['x'])) elif sexp[1][0] == 'rsa-pkcs1': assert len(kd) == 8, len(kd) return RSA.construct((kd['n'], kd['e'], kd['d'], kd['p'], kd['q'])) else: raise BadKeyError('unknown lsh key type %s' % sexp[1][0])
Example #3
Source File: test_keys.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def test_keyObjectSetRSAPublic(self): """ Setting the L{keys.Key.keyObject} property to a PyCrypto public RSA key instance updates the internal key. """ key = keys.Key.fromString(keydata.publicDSA_openssh) newPyCryptoKey = Crypto.PublicKey.RSA.construct(( keydata.RSAData['n'], keydata.RSAData['e'], )) self.assertEqual('DSA', key.type()) key.keyObject = newPyCryptoKey [warning] = self.flushWarnings([ KeyKeyObjectTests.test_keyObjectSetRSAPublic]) self.assertIs(warning['category'], DeprecationWarning) self.assertEqual('RSA', key.type()) self.assertEqual({ 'n': keydata.RSAData['n'], 'e': keydata.RSAData['e'], }, key.data())
Example #4
Source File: test_keys.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def getDSAKey(self): """ Return a PyCrypto DSA key to support the tests. @return: The DSA key to support the tests. @rtype: C{Crypto.PublicKey.DSA} """ # Use lazy import as PyCrypto will be deprecated. from Crypto.PublicKey import DSA return DSA.construct(( keydata.DSAData['y'], keydata.DSAData['g'], keydata.DSAData['p'], keydata.DSAData['q'], keydata.DSAData['x'], ))
Example #5
Source File: test_pkcs1_oaep.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
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 key._randfunc = randGen(t2b(test[3])) cipher = PKCS.new(key, test[4]) ct = cipher.encrypt(t2b(test[1])) self.assertEqual(ct, t2b(test[2]))
Example #6
Source File: test_pkcs1_15.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def testSign1(self): for i in range(len(self._testData)): row = self._testData[i] # Build the key if isStr(row[0]): key = RSA.importKey(row[0]) else: comps = [ long(rws(row[0][x]),16) for x in ('n','e','d') ] key = RSA.construct(comps) h = row[3].new() # Data to sign can either be in hex form or not try: h.update(t2b(row[1])) except: h.update(b(row[1])) # The real test signer = PKCS.new(key) self.failUnless(signer.can_sign()) s = signer.sign(h) self.assertEqual(s, t2b(row[2]))
Example #7
Source File: test_pkcs1_15.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def testVerify1(self): for i in range(len(self._testData)): row = self._testData[i] # Build the key if isStr(row[0]): key = RSA.importKey(row[0]).publickey() else: comps = [ long(rws(row[0][x]),16) for x in ('n','e') ] key = RSA.construct(comps) h = row[3].new() # Data to sign can either be in hex form or not try: h.update(t2b(row[1])) except: h.update(b(row[1])) # The real test verifier = PKCS.new(key) self.failIf(verifier.can_sign()) result = verifier.verify(h, t2b(row[2])) self.failUnless(result)
Example #8
Source File: test_pkcs1_pss.py From earthengine with MIT License | 6 votes |
def testSign1(self): for i in range(len(self._testData)): # Build the key comps = [ long(rws(self._testData[i][0][x]),16) for x in ('n','e','d') ] key = MyKey(RSA.construct(comps)) # Hash function h = self._testData[i][4].new() # Data to sign h.update(t2b(self._testData[i][1])) # Salt test_salt = t2b(self._testData[i][3]) key._randfunc = lambda N: test_salt # The real test signer = PKCS.new(key) self.failUnless(signer.can_sign()) s = signer.sign(h) self.assertEqual(s, t2b(self._testData[i][2]))
Example #9
Source File: test_pkcs1_15.py From earthengine with MIT License | 6 votes |
def testVerify1(self): for i in range(len(self._testData)): row = self._testData[i] # Build the key if isStr(row[0]): key = RSA.importKey(row[0]).publickey() else: comps = [ long(rws(row[0][x]),16) for x in ('n','e') ] key = RSA.construct(comps) h = row[3].new() # Data to sign can either be in hex form or not try: h.update(t2b(row[1])) except: h.update(b(row[1])) # The real test verifier = PKCS.new(key) self.failIf(verifier.can_sign()) result = verifier.verify(h, t2b(row[2])) self.failUnless(result)
Example #10
Source File: test_pkcs1_oaep.py From earthengine with MIT License | 6 votes |
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 key._randfunc = randGen(t2b(test[3])) cipher = PKCS.new(key, test[4]) ct = cipher.encrypt(t2b(test[1])) self.assertEqual(ct, t2b(test[2]))
Example #11
Source File: utils.py From snapy with MIT License | 6 votes |
def encryptPassword(email, password): gdpk = "AAAAgMom/1a/v0lblO2Ubrt60J2gcuXSljGFQXgcyZWveWLEwo6prwgi3iJIZdodyhKZQrNWp5nKJ3srRXcUW+F1BD3baEVGcmEgqaLZUNBjm057pKRI16kB0YppeGx5qIQ5QjKzsR8ETQbKLNWgRY0QRNVz34kMJR3P/LgHax/6rmf5AAAAAwEAAQ==" binaryKey = b64decode(gdpk).encode('hex') half = binaryKey[8:264] modulus = long(half, 16) half = binaryKey[272:278] exponent = long(half, 16) sha1hash = sha1(b64decode(gdpk)).digest() signature = "00" + sha1hash[:4].encode('hex') key = RSA.construct((modulus, exponent)) cipher = PKCS1_OAEP.new(key) plain = email + "\x00" + password encrypted = cipher.encrypt(plain).encode('hex') ste = signature + encrypted output = unhexlify(ste) encryptedPassword = b64encode(output).encode('ascii').replace("+","-").replace("/","_") return encryptedPassword
Example #12
Source File: test_pkcs1_pss.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def testVerify1(self): for i in range(len(self._testData)): # Build the key comps = [ long(rws(self._testData[i][0][x]),16) for x in ('n','e') ] key = MyKey(RSA.construct(comps)) # Hash function h = self._testData[i][4].new() # Data to sign h.update(t2b(self._testData[i][1])) # Salt test_salt = t2b(self._testData[i][3]) # The real test key._randfunc = lambda N: test_salt verifier = PKCS.new(key) self.failIf(verifier.can_sign()) result = verifier.verify(h, t2b(self._testData[i][2])) self.failUnless(result)
Example #13
Source File: test_pkcs1_pss.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def testSign1(self): for i in range(len(self._testData)): # Build the key comps = [ long(rws(self._testData[i][0][x]),16) for x in ('n','e','d') ] key = MyKey(RSA.construct(comps)) # Hash function h = self._testData[i][4].new() # Data to sign h.update(t2b(self._testData[i][1])) # Salt test_salt = t2b(self._testData[i][3]) key._randfunc = lambda N: test_salt # The real test signer = PKCS.new(key) self.failUnless(signer.can_sign()) s = signer.sign(h) self.assertEqual(s, t2b(self._testData[i][2]))
Example #14
Source File: test_pkcs1_15.py From earthengine with MIT License | 6 votes |
def testSign1(self): for i in range(len(self._testData)): row = self._testData[i] # Build the key if isStr(row[0]): key = RSA.importKey(row[0]) else: comps = [ long(rws(row[0][x]),16) for x in ('n','e','d') ] key = RSA.construct(comps) h = row[3].new() # Data to sign can either be in hex form or not try: h.update(t2b(row[1])) except: h.update(b(row[1])) # The real test signer = PKCS.new(key) self.failUnless(signer.can_sign()) s = signer.sign(h) self.assertEqual(s, t2b(row[2]))
Example #15
Source File: test_pkcs1_pss.py From earthengine with MIT License | 6 votes |
def testVerify1(self): for i in range(len(self._testData)): # Build the key comps = [ long(rws(self._testData[i][0][x]),16) for x in ('n','e') ] key = MyKey(RSA.construct(comps)) # Hash function h = self._testData[i][4].new() # Data to sign h.update(t2b(self._testData[i][1])) # Salt test_salt = t2b(self._testData[i][3]) # The real test key._randfunc = lambda N: test_salt verifier = PKCS.new(key) self.failIf(verifier.can_sign()) result = verifier.verify(h, t2b(self._testData[i][2])) self.failUnless(result)
Example #16
Source File: test_keys.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def test_keyObjectSetDSAPublic(self): """ Setting the L{keys.Key.keyObject} property to a PyCrypto public DSA key instance updates the internal key. """ key = keys.Key.fromString(keydata.publicRSA_openssh) newPyCryptoKey = Crypto.PublicKey.DSA.construct(( keydata.DSAData['y'], keydata.DSAData['g'], keydata.DSAData['p'], keydata.DSAData['q'], )) self.assertEqual('RSA', key.type()) key.keyObject = newPyCryptoKey self.assertEqual('DSA', key.type()) self.assertEqual({ 'y': keydata.DSAData['y'], 'g': keydata.DSAData['g'], 'p': keydata.DSAData['p'], 'q': keydata.DSAData['q'], }, key.data())
Example #17
Source File: test_keys.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def test_constructorPyCrypto(self): """ Passing a PyCrypto key object to L{keys.Key} is deprecated. """ pycryptoKey = Crypto.PublicKey.RSA.construct(( keydata.RSAData['n'], keydata.RSAData['e'])) key = self.callDeprecated( (Version('Twisted', 16, 0, 0), 'passing a cryptography key object'), keys.Key, pycryptoKey) self.assertEqual('RSA', key.type()) self.assertEqual({ 'n': keydata.RSAData['n'], 'e': keydata.RSAData['e'], }, key.data())
Example #18
Source File: example.py From Crypton with MIT License | 6 votes |
def signer(M): message = M p = getPrime(512) q = getPrime(512) n = p*q phin = (p-1)*(q-1) e = 65537 assert GCD(e, phin) == 1 key = RSA.construct((long(n), long(e))) h = MD5.new(M) M = PKCS1_v1_5.EMSA_PKCS1_V1_5_ENCODE(h, size(key.n)/8) print "Padded M: ", M.encode("hex") M = bytes_to_long(M) d = inverse(e, phin) s = pow(M, d, n) s = long_to_bytes(s) return (key, s, message)
Example #19
Source File: crypto_extras.py From chepy with GNU General Public License v3.0 | 6 votes |
def construct_private_key( n: int, e: int, d: int, format: str = "PEM", passphrase: str = None ) -> str: # pragma: no cover """Construct a private key given n, e and d Args: n (int): n e (int): e d (int): d format (str, optional): Supports PEM, DER and OpenSSH. Defaults to "PEM". passphrase (str, optional): [description]. Defaults to None. Returns: str: Private key """ valid_formats = ["PEM", "DER", "OpenSSH"] assert format in valid_formats, "Valid formats are {}".format( " ".join(valid_formats) ) priv = RSA.construct((n, e, d)) return priv.export_key(format=format, passphrase=passphrase)
Example #20
Source File: rsa.py From CryptoAttacks with MIT License | 6 votes |
def common_primes(keys): """Find common prime in keys modules Args: keys(list): RSAKeys Returns: list: RSAKeys for which factorization of n was found """ priv_keys = [] for pair in itertools.combinations(keys, 2): prime = gmpy2.gcd(pair[0].n, pair[1].n) if prime != 1: log.success("Found common prime in: {}, {}".format(pair[0].identifier, pair[1].identifier)) for key_no in range(2): if pair[key_no] not in priv_keys: d = int(invmod(pair[key_no].e, (prime - 1) * (pair[key_no].n // prime - 1))) new_key = RSAKey.construct(int(pair[key_no].n), int(pair[key_no].e), int(d), identifier=pair[key_no].identifier + '-private') new_key.texts = pair[key_no].texts[:] priv_keys.append(new_key) else: log.debug("Key {} already in priv_keys".format(pair[key_no].identifier)) return priv_keys
Example #21
Source File: rsa.py From CryptoAttacks with MIT License | 6 votes |
def wiener(key): """Wiener small private exponent attack If d < (1/3)*(N**(1/4)), d can be effectively recovered using continuous fractions Args: key(RSAKey): public rsa key to break Returns: NoneType/RSAKey: None if didn't break key, private key otherwise """ en_fractions = continued_fractions(key.e, key.n) for k, d in convergents(en_fractions): if k != 0 and (key.e * d - 1) % k == 0: phi = (key.e * d - 1) // k """ p**2 - p*(n - phi + 1) + n == 0 """ b = key.n - phi + 1 delta = b * b - 4 * key.n if delta > 0: sqrt_delta = gmpy2.isqrt(delta) if sqrt_delta * sqrt_delta == delta and sqrt_delta % 2 == 0: log.debug("Found private key (d={}) for {}".format(d, key.identifier)) new_key = RSAKey.construct(key.n, key.e, d, identifier=key.identifier + '-private') new_key.texts = key.texts[:] return new_key return None
Example #22
Source File: crypto.py From HuaweiB525Router with MIT License | 6 votes |
def rsa_encrypt(rsae, rsan, data): if (data is None or data == ''): return '' N = int(rsan,16) E = int(rsae,16) b64data = base64.b64encode(data) pubkey = construct((N, E)) cipher = PKCS1_v1_5.new(pubkey) blocks = int(math.ceil(len(b64data) / 245.0)) result = [] for i in range(blocks): block = b64data[i*245:(i+1)*245] d = cipher.encrypt(block) result.append(d) result = hexlify(''.join(result)) if ((len(result) & 1) == 0): return result else: return '0'+result
Example #23
Source File: PemToXml.py From PemToXml with GNU General Public License v2.0 | 6 votes |
def privKeyPEM(xmlPrivateKeyFile): with open (xmlPrivateKeyFile, 'rb') as pkFile: xmlPrivateKey = pkFile.read() rsaKeyValue = minidom.parseString(xmlPrivateKey) modulus = GetLong(rsaKeyValue.getElementsByTagName('Modulus')[0].childNodes) exponent = GetLong(rsaKeyValue.getElementsByTagName('Exponent')[0].childNodes) d = GetLong(rsaKeyValue.getElementsByTagName('D')[0].childNodes) p = GetLong(rsaKeyValue.getElementsByTagName('P')[0].childNodes) q = GetLong(rsaKeyValue.getElementsByTagName('Q')[0].childNodes) qInv = GetLong(rsaKeyValue.getElementsByTagName('InverseQ')[0].childNodes) privateKey = RSA.construct((modulus, exponent, d, p, q, qInv)) fileName = basename(xmlPrivateKeyFile) with open (fileName+'.pem', 'w') as pkFile: pkFile.write(privateKey.exportKey()) return # # Parser args #
Example #24
Source File: keys.py From python-for-android with Apache License 2.0 | 6 votes |
def _fromString_BLOB(Class, blob): """ Return a public key object corresponding to this public key blob. The format of a RSA public key blob is:: string 'ssh-rsa' integer e integer n The format of a DSA public key blob is:: string 'ssh-dss' integer p integer q integer g integer y @type blob: C{str} @return: a C{Crypto.PublicKey.pubkey.pubkey} object @raises BadKeyError: if the key type (the first string) is unknown. """ keyType, rest = common.getNS(blob) if keyType == 'ssh-rsa': e, n, rest = common.getMP(rest, 2) return Class(RSA.construct((n, e))) elif keyType == 'ssh-dss': p, q, g, y, rest = common.getMP(rest, 4) return Class(DSA.construct((y, g, p, q))) else: raise BadKeyError('unknown blob type: %s' % keyType)
Example #25
Source File: keys.py From python-for-android with Apache License 2.0 | 6 votes |
def _fromString_PRIVATE_BLOB(Class, blob): """ Return a private key object corresponding to this private key blob. The blob formats are as follows: RSA keys:: string 'ssh-rsa' integer n integer e integer d integer u integer p integer q DSA keys:: string 'ssh-dss' integer p integer q integer g integer y integer x @type blob: C{str} @return: a C{Crypto.PublicKey.pubkey.pubkey} object @raises BadKeyError: if the key type (the first string) is unknown. """ keyType, rest = common.getNS(blob) if keyType == 'ssh-rsa': n, e, d, u, p, q, rest = common.getMP(rest, 6) rsakey = Class(RSA.construct((n, e, d, p, q, u))) return rsakey elif keyType == 'ssh-dss': p, q, g, y, x, rest = common.getMP(rest, 5) dsakey = Class(DSA.construct((y, g, p, q, x))) return dsakey else: raise BadKeyError('unknown blob type: %s' % keyType)
Example #26
Source File: keys.py From python-for-android with Apache License 2.0 | 6 votes |
def _fromString_PUBLIC_LSH(Class, data): """ Return a public key corresponding to this LSH public key string. The LSH public key string format is:: <s-expression: ('public-key', (<key type>, (<name, <value>)+))> The names for a RSA (key type 'rsa-pkcs1-sha1') key are: n, e. The names for a DSA (key type 'dsa') key are: y, g, p, q. @type data: C{str} @return: a C{Crypto.PublicKey.pubkey.pubkey} object @raises BadKeyError: if the key type is unknown """ sexp = sexpy.parse(base64.decodestring(data[1:-1])) assert sexp[0] == 'public-key' kd = {} for name, data in sexp[1][1:]: kd[name] = common.getMP(common.NS(data))[0] if sexp[1][0] == 'dsa': return Class(DSA.construct((kd['y'], kd['g'], kd['p'], kd['q']))) elif sexp[1][0] == 'rsa-pkcs1-sha1': return Class(RSA.construct((kd['n'], kd['e']))) else: raise BadKeyError('unknown lsh key type %s' % sexp[1][0])
Example #27
Source File: keys.py From BitTorrent with GNU General Public License v3.0 | 6 votes |
def getPublicKeyObject(data): """ Return a C{Crypto.PublicKey.pubkey.pubkey} corresponding to the SSHv2 public key data. data is in the over-the-wire public key format. @type data: C{str} @rtype: C{Crypto.PublicKey.pubkey.pubkey} """ keyKind, rest = common.getNS(data) if keyKind == 'ssh-rsa': e, rest = common.getMP(rest) n, rest = common.getMP(rest) return RSA.construct((n, e)) elif keyKind == 'ssh-dss': p, rest = common.getMP(rest) q, rest = common.getMP(rest) g, rest = common.getMP(rest) y, rest = common.getMP(rest) return DSA.construct((y, g, p, q)) else: raise BadKeyError('unknown key type %s' % keyKind)
Example #28
Source File: rsakey.py From imoocc with GNU General Public License v2.0 | 5 votes |
def sign_ssh_data(self, rpool, data): digest = SHA.new(data).digest() rsa = RSA.construct((long(self.n), long(self.e), long(self.d))) sig = util.deflate_long(rsa.sign(self._pkcs1imify(digest), '')[0], 0) m = Message() m.add_string('ssh-rsa') m.add_string(sig) return m
Example #29
Source File: rsakey.py From imoocc with GNU General Public License v2.0 | 5 votes |
def verify_ssh_sig(self, data, msg): if msg.get_string() != 'ssh-rsa': return False sig = util.inflate_long(msg.get_string(), True) # verify the signature by SHA'ing the data and encrypting it using the # public key. some wackiness ensues where we "pkcs1imify" the 20-byte # hash into a string as long as the RSA key. hash_obj = util.inflate_long(self._pkcs1imify(SHA.new(data).digest()), True) rsa = RSA.construct((long(self.n), long(self.e))) return rsa.verify(hash_obj, (sig,))
Example #30
Source File: util.py From orisi with MIT License | 5 votes |
def construct_pubkey_from_data(rsa_data): key = RSA.construct(( long(rsa_data['n']), long(rsa_data['e']))) return key