Python Crypto.PublicKey.RSA.importKey() Examples
The following are 30
code examples of Crypto.PublicKey.RSA.importKey().
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: crypt.py From earthengine with MIT License | 6 votes |
def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. """ if is_x509_cert: pemLines = key_pem.replace(' ', '').split() certDer = _urlsafe_b64decode(''.join(pemLines[1:-1])) certSeq = DerSequence() certSeq.decode(certDer) tbsSeq = DerSequence() tbsSeq.decode(certSeq[0]) pubkey = RSA.importKey(tbsSeq[6]) else: pubkey = RSA.importKey(key_pem) return PyCryptoVerifier(pubkey)
Example #2
Source File: crypt.py From billing-export-python with Apache License 2.0 | 6 votes |
def from_string(key, password='notasecret'): """Construct a Signer instance from a string. Args: key: string, private key in PEM format. password: string, password for private key file. Unused for PEM files. Returns: Signer instance. Raises: NotImplementedError if they key isn't in PEM format. """ if key.startswith('-----BEGIN '): pkey = RSA.importKey(key) else: raise NotImplementedError( 'PKCS12 format is not supported by the PyCrpto library. ' 'Try converting to a "PEM" ' '(openssl pkcs12 -in xxxxx.p12 -nodes -nocerts > privatekey.pem) ' 'or using PyOpenSSL if native code is an option.') return PyCryptoSigner(pkey)
Example #3
Source File: crypt.py From billing-export-python with Apache License 2.0 | 6 votes |
def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. Raises: NotImplementedError if is_x509_cert is true. """ if is_x509_cert: raise NotImplementedError( 'X509 certs are not supported by the PyCrypto library. ' 'Try using PyOpenSSL if native code is an option.') else: pubkey = RSA.importKey(key_pem) return PyCryptoVerifier(pubkey)
Example #4
Source File: helpers.py From featherduster with BSD 3-Clause "New" or "Revised" License | 6 votes |
def check_rsa_key(sample): """ Returns a 3-tuple (is_rsa_key, has_private_component, n_bit_length) is_rsa_key - a bool indicating that the sample is, in fact, an RSA key in a format readable by Crypto.PublicKey.RSA.importKey has_private_component - a bool indicating whether or not d was in the analyzed key, or false if the sample is not an RSA key n_bit_length - an int representing the bit length of the modulus found in the analyzed key, or False if the sample is not an RSA key """ is_rsa_key = has_private_component = n_bit_length = False try: rsakey = RSA.importKey(sample.strip()) is_rsa_key = True if rsakey.has_private(): has_private_component = True n_bit_length = bit_length(rsakey.n) # Don't really care why it fails, just want to see if it did except: is_rsa_key = False return (is_rsa_key, has_private_component, n_bit_length)
Example #5
Source File: crypt.py From sndlatr with Apache License 2.0 | 6 votes |
def from_string(key, password='notasecret'): """Construct a Signer instance from a string. Args: key: string, private key in PEM format. password: string, password for private key file. Unused for PEM files. Returns: Signer instance. Raises: NotImplementedError if they key isn't in PEM format. """ if key.startswith('-----BEGIN '): pkey = RSA.importKey(key) else: raise NotImplementedError( 'PKCS12 format is not supported by the PyCrpto library. ' 'Try converting to a "PEM" ' '(openssl pkcs12 -in xxxxx.p12 -nodes -nocerts > privatekey.pem) ' 'or using PyOpenSSL if native code is an option.') return PyCryptoSigner(pkey)
Example #6
Source File: crypt.py From sndlatr with Apache License 2.0 | 6 votes |
def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. Raises: NotImplementedError if is_x509_cert is true. """ if is_x509_cert: # raise NotImplementedError( # 'X509 certs are not supported by the PyCrypto library. ' # 'Try using PyOpenSSL if native code is an option.') key_pem = x509.get_pubkey(key_pem) pubkey = RSA.importKey(key_pem) return PyCryptoVerifier(pubkey)
Example #7
Source File: crypt.py From splunk-ref-pas-code with Apache License 2.0 | 6 votes |
def from_string(key, password='notasecret'): """Construct a Signer instance from a string. Args: key: string, private key in PEM format. password: string, password for private key file. Unused for PEM files. Returns: Signer instance. Raises: NotImplementedError if they key isn't in PEM format. """ if key.startswith('-----BEGIN '): pkey = RSA.importKey(key) else: raise NotImplementedError( 'PKCS12 format is not supported by the PyCrpto library. ' 'Try converting to a "PEM" ' '(openssl pkcs12 -in xxxxx.p12 -nodes -nocerts > privatekey.pem) ' 'or using PyOpenSSL if native code is an option.') return PyCryptoSigner(pkey)
Example #8
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 #9
Source File: crypt.py From earthengine with MIT License | 6 votes |
def from_string(key, password='notasecret'): """Construct a Signer instance from a string. Args: key: string, private key in PEM format. password: string, password for private key file. Unused for PEM files. Returns: Signer instance. Raises: NotImplementedError if they key isn't in PEM format. """ parsed_pem_key = _parse_pem_key(key) if parsed_pem_key: pkey = RSA.importKey(parsed_pem_key) else: raise NotImplementedError( 'PKCS12 format is not supported by the PyCrypto library. ' 'Try converting to a "PEM" ' '(openssl pkcs12 -in xxxxx.p12 -nodes -nocerts > privatekey.pem) ' 'or using PyOpenSSL if native code is an option.') return PyCryptoSigner(pkey)
Example #10
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 #11
Source File: test_pkcs1_15.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def testEncrypt1(self): for test in self._testData: # Build the key key = RSA.importKey(test[0]) # 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) ct = cipher.encrypt(b(test[1])) self.assertEqual(ct, t2b(test[2]))
Example #12
Source File: keybag.py From pyaff4 with Apache License 2.0 | 6 votes |
def create(vek, keySizeBytes, certificatePath): #print("VEK: " + str(binascii.hexlify(vek))) publicKeyPem = open(certificatePath).read() publicKey = RSA.importKey(publicKeyPem) # Convert from PEM to DER lines = publicKeyPem.replace(" ", '').split() publicKeyDer = binascii.a2b_base64(''.join(lines[1:-1])) cert = x509.load_pem_x509_certificate(SmartStr(publicKeyPem), default_backend()) subjectName = cert.subject.rfc4514_string() serial = cert.serial_number cipher = PKCS1_OAEP.new(key=publicKey, hashAlgo=SHA256, mgfunc=lambda x, y: pss.MGF1(x, y, SHA1)) wrapped_key = cipher.encrypt(vek) #print("WrappedKey: " + str(binascii.hexlify(wrapped_key))) return CertEncryptedKeyBag(subjectName, serial, keySizeBytes, wrapped_key)
Example #13
Source File: rsa_helper.py From hacker-scripts with MIT License | 6 votes |
def decrypt(cls, encrypted_file, key_file, out_file='output_dec', passphrase=''): """ 解密 :param out_file: :param encrypted_file: :param key_file: :param passphrase: :return: """ print('decrypt') with open(key_file, "r") as kf: rsa = RSA.importKey(kf.read(), passphrase=passphrase) with open(encrypted_file, 'rb') as df: data = rsa.decrypt(df.read()) print('data:\n') print(data) print('hex:') print(data.encode('hex')) with open(out_file, "wb") as of: of.write(data)
Example #14
Source File: rsa_helper.py From hacker-scripts with MIT License | 6 votes |
def encrypt(cls, raw_file, key_file, out_file='output_enc', passphrase=''): """ 加密 :param out_file: :param raw_file: :param key_file: :param passphrase: :return: """ print('encrypt') with open(key_file, "r") as kf: rsa = RSA.importKey(kf.read(), passphrase=passphrase) with open(raw_file, 'rb') as df: data = rsa.encrypt(df.read(), 0) print('data:') print(data) print('hex:') print(data.encode('hex')) with open(out_file, "wb") as of: of.write(data[0])
Example #15
Source File: crypt.py From splunk-ref-pas-code with Apache License 2.0 | 6 votes |
def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. Raises: NotImplementedError if is_x509_cert is true. """ if is_x509_cert: raise NotImplementedError( 'X509 certs are not supported by the PyCrypto library. ' 'Try using PyOpenSSL if native code is an option.') else: pubkey = RSA.importKey(key_pem) return PyCryptoVerifier(pubkey)
Example #16
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 #17
Source File: test_pkcs1_15.py From earthengine with MIT License | 6 votes |
def testEncrypt1(self): for test in self._testData: # Build the key key = RSA.importKey(test[0]) # 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) ct = cipher.encrypt(b(test[1])) self.assertEqual(ct, t2b(test[2]))
Example #18
Source File: jose.py From jose with BSD 3-Clause "New" or "Revised" License | 5 votes |
def decrypt_oaep(ciphertext, jwk): try: return PKCS1_OAEP.new(RSA.importKey(jwk['k'])).decrypt(ciphertext) except ValueError as e: raise Error(e.args[0])
Example #19
Source File: jose.py From jose with BSD 3-Clause "New" or "Revised" License | 5 votes |
def rsa_sign(s, key, mod=SHA256): key = RSA.importKey(key) hash = mod.new(s) return PKCS1_v1_5_SIG.new(key).sign(hash)
Example #20
Source File: rsa_crack2.py From hacker-scripts with MIT License | 5 votes |
def main(): # rsa.pub 是公钥 with open('challenge/0.key', 'rb') as f: rsa = RSA.importKey(f.read()) # enc 是密文 with open('challenge/0.enc', 'rb') as f2: # 直接获取到n和e # p, q, d 的获取方式也一样 crack(rsa.key.n, rsa.key.e, f2.read())
Example #21
Source File: test_importKey.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def testImportKey9(self): """Verify import of unencrypted PrivateKeyInfo DER SEQUENCE""" key = self.rsa.importKey(self.rsaKeyDER8) self.failUnless(key.has_private()) self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e) self.assertEqual(key.d, self.d) self.assertEqual(key.p, self.p) self.assertEqual(key.q, self.q)
Example #22
Source File: test_importKey.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def testImportKey12(self): """Verify import of RSAPublicKey DER SEQUENCE, encoded with PEM""" der = asn1.DerSequence([17, 3]).encode() pem = der2pem(der) key = self.rsa.importKey(pem) self.assertEqual(key.n, 17) self.assertEqual(key.e, 3) ###
Example #23
Source File: test_importKey.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def testImportKey11(self): """Verify import of RSAPublicKey DER SEQUENCE""" der = asn1.DerSequence([17, 3]).encode() key = self.rsa.importKey(der) self.assertEqual(key.n, 17) self.assertEqual(key.e, 3)
Example #24
Source File: test_importKey.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def testImportKey3bytes(self): """Verify import of RSAPrivateKey DER SEQUENCE, encoded with PEM as byte string""" key = RSA.importKey(b(self.rsaKeyPEM)) self.assertEqual(key.has_private(),True) # assert_ self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e) self.assertEqual(key.d, self.d) self.assertEqual(key.p, self.p) self.assertEqual(key.q, self.q)
Example #25
Source File: jose.py From jose with BSD 3-Clause "New" or "Revised" License | 5 votes |
def encrypt_oaep(plaintext, jwk): return PKCS1_OAEP.new(RSA.importKey(jwk['k'])).encrypt(plaintext)
Example #26
Source File: rsa_wiener.py From featherduster with BSD 3-Clause "New" or "Revised" License | 5 votes |
def rsa_wiener_attack(ciphertexts): options = dict(feathermodules.current_options) options = prepare_options(options, ciphertexts) if options == False: print '[*] Could not process options.' return False answers = [] for ciphertext in ciphertexts: try: key = RSA.importKey(ciphertext) if key.has_private(): continue else: modulus = key.n exponent = key.e except: continue p = ca.wiener(modulus, exponent, minutes=options['minutes_to_wait'], verbose=True) if p != 1: answers.append( (modulus, exponent, ca.derive_d_from_pqe(p,modulus/p,exponent)) ) for answer in answers: key = RSA.construct(answer) print "Found private key:\n%s" % key.exportKey() if len(answers) == 0: return False else: return ['N:{},e:{},d:{}'.format(*answer) for answer in answers]
Example #27
Source File: rsa_fermat.py From featherduster with BSD 3-Clause "New" or "Revised" License | 5 votes |
def fermat_factor_attack(ciphertexts): options = dict(feathermodules.current_options) options = prepare_options(options, ciphertexts) if options == False: print '[*] Could not process options.' return False answers = [] for ciphertext in ciphertexts: try: key = RSA.importKey(ciphertext) if key.has_private(): continue else: modulus = key.n exponent = key.e except: continue factors = ca.fermat_factor(modulus, minutes=options['minutes_to_wait'], verbose=True) if factors[0] != 1: answers.append( (modulus, exponent, ca.derive_d_from_pqe(factors[0],factors[1],exponent)) ) for answer in answers: key = RSA.construct(answer) print "Found private key:\n%s" % key.exportKey() if len(answers) == 0: return False else: return ['N:{},e:{},d:{}'.format(answer) for answer in answers]
Example #28
Source File: default_crypto.py From plugin.video.netflix with MIT License | 5 votes |
def load_crypto_session(self, msl_data=None): try: self.encryption_key = base64.standard_b64decode( msl_data['encryption_key']) self.sign_key = base64.standard_b64decode( msl_data['sign_key']) if not self.encryption_key or not self.sign_key: raise MSLError('Missing encryption_key or sign_key') self.rsa_key = RSA.importKey( base64.standard_b64decode(msl_data['rsa_key'])) except Exception: # pylint: disable=broad-except common.debug('Generating new RSA keys') self.rsa_key = RSA.generate(2048) self.encryption_key = None self.sign_key = None
Example #29
Source File: auth.py From fastmc with BSD 2-Clause "Simplified" License | 5 votes |
def decode_public_key(bytes): """Decodes a public RSA key in ASN.1 format as defined by x.509""" return RSA.importKey(bytes)
Example #30
Source File: util.py From baidu-wangpan-parse with MIT License | 5 votes |
def encrypt_pwd(password, public_key): rsa_key = RSA.importKey(public_key) encryptor = Cipher_pkcs1_v1_5.new(rsa_key) cipher = b64encode(encryptor.encrypt(password.encode('utf-8'))) return cipher.decode('utf-8')