Python Crypto.PublicKey.RSA.generate() Examples
The following are 30
code examples of Crypto.PublicKey.RSA.generate().
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: render.py From calm-dsl with Apache License 2.0 | 8 votes |
def create_cred_keys(dir_name): # Will create key via name centos/centos_pub key = RSA.generate(2048) # Write private key private_key = key.export_key("PEM") private_key_filename = os.path.join(dir_name, "centos") with open(private_key_filename, "wb") as fd: fd.write(private_key) os.chmod(private_key_filename, 0o600) # Write public key public_key = key.publickey().export_key("OpenSSH") public_key_filename = os.path.join(dir_name, "centos_pub") with open(public_key_filename, "wb") as fd: fd.write(public_key) os.chmod(public_key_filename, 0o600)
Example #2
Source File: ib.py From infrabox with MIT License | 7 votes |
def _setup_rsa_keys(): private_key_path = '/tmp/ib/run/rsa/id_rsa' public_key_path = '/tmp/ib/run/rsa/id_rsa.pub' key = RSA.generate(2048) if not os.path.exists(private_key_path): logger.warn('Private key does not exist: %s', private_key_path) logger.warn('Recreating it') if not os.path.exists(os.path.dirname(private_key_path)): os.makedirs(os.path.dirname(private_key_path)) with open(private_key_path, 'w+') as s: s.write(str(key.exportKey())) if not os.path.exists(public_key_path): logger.warn('Public key does not exist: %s', public_key_path) logger.warn('Recreating it') if not os.path.exists(os.path.dirname(public_key_path)): os.makedirs(os.path.dirname(public_key_path)) with open(public_key_path, 'w+') as s: s.write(str(key.publickey().exportKey()))
Example #3
Source File: rsakey.py From imoocc with GNU General Public License v2.0 | 6 votes |
def generate(bits, progress_func=None): """ Generate a new private RSA key. This factory function can be used to generate a new host key or authentication key. @param bits: number of bits the generated key should be. @type bits: int @param progress_func: an optional function to call at key points in key generation (used by C{pyCrypto.PublicKey}). @type progress_func: function @return: new private key @rtype: L{RSAKey} """ rsa = RSA.generate(bits, rng.read, progress_func) key = RSAKey(vals=(rsa.e, rsa.n)) key.d = rsa.d key.p = rsa.p key.q = rsa.q return key
Example #4
Source File: gitlab_tools.py From gitlab-tools with GNU General Public License v3.0 | 6 votes |
def create_rsa_pair(user_id: int) -> None: user = User.query.filter_by(id=user_id, is_rsa_pair_set=False).first() if user: # check if priv and pub keys exists private_key_path = get_user_private_key_path(user, flask.current_app.config['USER']) public_key_path = get_user_public_key_path(user, flask.current_app.config['USER']) key = RSA.generate(4096) with open(private_key_path, 'wb') as content_file: os.chmod(private_key_path, 0o0600) content_file.write(key.exportKey('PEM')) pubkey = key.publickey() with open(public_key_path, 'wb') as content_file: content_file.write(pubkey.exportKey('OpenSSH')) user.is_rsa_pair_set = True db.session.add(user) db.session.commit()
Example #5
Source File: bounty_create_handler.py From orisi with MIT License | 6 votes |
def get_public_key(self, pwtxid): key = RSAKeyPairs(self.oracle.db).get_by_pwtxid(pwtxid) if key: return key['public'] random_generator = Random.new().read new_keypair = RSA.generate(KEY_SIZE, random_generator) public_key = json.dumps({'n':new_keypair.n, 'e':new_keypair.e}) whole_key_serialized = json.dumps({ 'n':new_keypair.n, 'e':new_keypair.e, 'd':new_keypair.d, 'p':new_keypair.p, 'q':new_keypair.q, 'u':new_keypair.u}) RSAKeyPairs(self.oracle.db).save({ 'pwtxid': pwtxid, 'public': public_key, 'whole': whole_key_serialized}) return public_key
Example #6
Source File: rsakey.py From imoocc with GNU General Public License v2.0 | 6 votes |
def generate(bits, progress_func=None): """ Generate a new private RSA key. This factory function can be used to generate a new host key or authentication key. @param bits: number of bits the generated key should be. @type bits: int @param progress_func: an optional function to call at key points in key generation (used by C{pyCrypto.PublicKey}). @type progress_func: function @return: new private key @rtype: L{RSAKey} """ rsa = RSA.generate(bits, rng.read, progress_func) key = RSAKey(vals=(rsa.e, rsa.n)) key.d = rsa.d key.p = rsa.p key.q = rsa.q return key
Example #7
Source File: test_lti_consumer.py From xblock-lti-consumer with GNU Affero General Public License v3.0 | 6 votes |
def setUp(self): super(TestLtiConsumer1p3XBlock, self).setUp() self.xblock_attributes = { 'lti_version': 'lti_1p3', 'lti_1p3_launch_url': 'http://tool.example/launch', 'lti_1p3_oidc_url': 'http://tool.example/oidc', # We need to set the values below because they are not automatically # generated until the user selects `lti_version == 'lti_1p3'` on the # Studio configuration view. 'lti_1p3_client_id': str(uuid.uuid4()), 'lti_1p3_block_key': RSA.generate(2048).export_key('PEM'), } self.xblock = make_xblock('lti_consumer', LtiConsumerXBlock, self.xblock_attributes) # pylint: disable=unused-argument
Example #8
Source File: lti_xblock.py From xblock-lti-consumer with GNU Affero General Public License v3.0 | 6 votes |
def clean_studio_edits(self, data): """ This is a handler to set hidden Studio variables for LTI 1.3. These variables shouldn't be editable by the user, but need to be automatically generated for each instance: * lti_1p3_client_id: random uuid (requirement: must be unique) * lti_1p3_block_key: PEM export of 2048-bit RSA key. TODO: Remove this once the XBlock Fields API support using a default computed value. """ if data.get('lti_version') == 'lti_1p3': # Check if values already exist before populating # to avoid overwriting these keys on every edit. if not self.lti_1p3_client_id: data['lti_1p3_client_id'] = str(uuid.uuid4()) if not self.lti_1p3_block_key: data['lti_1p3_block_key'] = RSA.generate(2048).export_key('PEM') return super(LtiConsumerXBlock, self).clean_studio_edits(data)
Example #9
Source File: service_keys.py From quay with Apache License 2.0 | 6 votes |
def generate_service_key( service, expiration_date, kid=None, name="", metadata=None, rotation_duration=None ): private_key = RSA.generate(2048) jwk = RSAKey(key=private_key.publickey()).serialize() if kid is None: kid = canonical_kid(jwk) key = create_service_key( name, kid, service, jwk, metadata or {}, expiration_date, rotation_duration=rotation_duration, ) return (private_key, key)
Example #10
Source File: tests.py From jose with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_jwe(self): bad_key = {'k': RSA.generate(2048).exportKey('PEM')} jwe = legacy_encrypt(claims, rsa_pub_key) token = jose.serialize_compact(jwe) jwt = jose.decrypt(jose.deserialize_compact(token), rsa_priv_key) self.assertEqual(jwt.claims, claims) self.assertNotIn(jose._TEMP_VER_KEY, claims) # invalid key try: jose.decrypt(jose.deserialize_compact(token), bad_key) self.fail() except jose.Error as e: self.assertEqual(e.message, 'Incorrect decryption.')
Example #11
Source File: test_dogtag.py From sgx-kms with Apache License 2.0 | 6 votes |
def test_get_public_key(self): test_public_key = RSA.generate(2048).publickey() key_info = dogtag_key.KeyInfo() key_info.public_key = test_public_key.exportKey('DER') self.keyclient_mock.get_key_info.return_value = key_info secret_metadata = { dogtag_import.DogtagKRAPlugin.ALG: sstore.KeyAlgorithm.RSA, dogtag_import.DogtagKRAPlugin.BIT_LENGTH: 2048, dogtag_import.DogtagKRAPlugin.KEY_ID: 'key1', dogtag_import.DogtagKRAPlugin.CONVERT_TO_PEM: 'true' } result = self.plugin.get_secret(sstore.SecretType.PUBLIC, secret_metadata) self.assertEqual(test_public_key.exportKey('PEM').encode('utf-8'), result.secret)
Example #12
Source File: tests.py From jose with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_jwe_decrypt_compliant_incorrect_jwk(self): jwk_for_decrypt = {'k': RSA.generate(2048).exportKey('PEM')} legacy_patch = mock.patch.object( jose, 'legacy_decrypt', wraps=jose.legacy_decrypt ) spec_patch = mock.patch.object( jose, 'spec_compliant_decrypt', wraps=jose.spec_compliant_decrypt ) with legacy_patch as legacy_mock, spec_patch as spec_mock: with self.assertRaises(jose.Error) as decryption_error: jose.decrypt( jose.deserialize_compact(SPEC_COMPLIANT_TOKEN), jwk_for_decrypt) self.assertEqual(legacy_mock.call_count, 1) self.assertEqual(spec_mock.call_count, 1) self.assertEqual(decryption_error.exception.message, "Incorrect decryption.")
Example #13
Source File: test_certificate_resources.py From sgx-kms with Apache License 2.0 | 6 votes |
def test_should_raise_for_pycrypto_stored_key_no_container(self): self.order_meta.update(self.stored_key_meta) private_key = RSA.generate(2048, None, None, 65537) public_key = private_key.publickey() self.private_key_value = private_key.exportKey('PEM', None, 8) self.public_key_value = public_key.exportKey() self.store_plugin.get_secret.side_effect = self.stored_key_side_effect self.result.status = cert_man.CertificateStatus.WAITING_FOR_CA container_repo.delete_project_entities(self.project.id) self.assertRaises(excep.StoredKeyContainerNotFound, cert_res.issue_certificate_request, self.order, self.project, self.result_follow_on)
Example #14
Source File: test_certificate_resources.py From sgx-kms with Apache License 2.0 | 6 votes |
def test_should_return_for_pycrypto_stored_key_without_passphrase(self): self.order_meta.update(self.stored_key_meta) private_key = RSA.generate(2048, None, None, 65537) public_key = private_key.publickey() self.private_key_value = base64.b64encode( private_key.exportKey('PEM', None, 8)) self.public_key_value = base64.b64encode(public_key.exportKey()) self.store_plugin.get_secret.side_effect = self.stored_key_side_effect self._test_should_return_waiting_for_ca( cert_res.issue_certificate_request) self._verify_issue_certificate_plugins_called() self.assertIsNotNone( self.order.order_barbican_meta['generated_csr']) # TODO(alee-3) Add tests to validate the request based on the validator # code that dave-mccowan is adding.
Example #15
Source File: test_crypto.py From aliyun-oss-python-sdk with MIT License | 6 votes |
def test_rsa_provider_init_invalid_passphrase(self): private_key = RSA.generate(2048) public_key = private_key.publickey() passphrase = random_string(6) invalid_passphrase = random_string(8) with open('./rsa-test.private_key.pem', 'wb') as f: f.write(private_key.exportKey(passphrase=passphrase)) with open('./rsa-test.public_key.pem', 'wb') as f: f.write(public_key.exportKey(passphrase=passphrase)) self.assertRaises(ClientError, LocalRsaProvider, dir='./', key='rsa-test', passphrase=invalid_passphrase) silently_remove('./rsa-test.public_key.pem') silently_remove('./rsa-test.private_key.pem') private_key_str = RsaKey.exportKey(private_key, passphrase=passphrase) public_key_str = RsaKey.exportKey(public_key, passphrase=passphrase) self.assertRaises(ClientError, RsaProvider, key_pair={'private_key': private_key_str, 'public_key': public_key_str}, passphrase=invalid_passphrase) # 测试基本key, start加/解密
Example #16
Source File: test_crypto.py From aliyun-oss-python-sdk with MIT License | 6 votes |
def test_rsa_provider_init_invalid_keys(self): private_key = RSA.generate(2048) public_key = private_key.publickey() # 这个地方修改private_key的内容 private_key = random_string(2048) with open('./rsa-test.private_key.pem', 'wb') as f: f.write(oss2.to_bytes(private_key)) with open('./rsa-test.public_key.pem', 'wb') as f: f.write(public_key.exportKey()) self.assertRaises(ClientError, LocalRsaProvider, dir='./', key='rsa-test') silently_remove('./rsa-test.public_key.pem') silently_remove('./rsa-test.private_key.pem') self.assertRaises(ClientError, RsaProvider, key_pair={'private_key': private_key, 'public_key': public_key}) # 测试当keys存在时,使用错误的passpass初始化LocalRsaProvider时抛出异常
Example #17
Source File: adbwrapper.py From inception with GNU General Public License v3.0 | 6 votes |
def __init__(self): super(Adb, self).__init__(None) self.busybox = False if not os.path.exists(InceptionConstants.PATH_RSA_KEY): logger.warning("%s does not exist, going to generate RSA keys" % InceptionConstants.PATH_RSA_KEY) if not os.path.exists(os.path.dirname(InceptionConstants.PATH_RSA_KEY)): os.makedirs(os.path.dirname(InceptionConstants.PATH_RSA_KEY)) private = RSA.generate(1024) public = private.publickey() with open(InceptionConstants.PATH_RSA_KEY, 'w') as privateKeyFile: privateKeyFile.write(private.exportKey()) with open(InceptionConstants.PATH_RSA_KEY + ".pub", "w") as publicKeyFile: publicKeyFile.write(public.exportKey()) self.rsaKeys = [M2CryptoSigner(InceptionConstants.PATH_RSA_KEY)]
Example #18
Source File: key_manager.py From cryptocurrency-samplecode with Apache License 2.0 | 6 votes |
def __init__(self, privatekey_text = None, pass_phrase= None): print('Initializing KeyManager...') if privatekey_text: self.import_key_pair(privatekey_text, pass_phrase) else: random_gen = Crypto.Random.new().read self._private_key = RSA.generate(2048, random_gen) self._public_key = self._private_key.publickey() self._signer = PKCS1_v1_5.new(self._private_key) if pass_phrase is not None: my_pem = self.export_key_pair(pass_phrase) my_pem_hex = binascii.hexlify(my_pem).decode('ascii') # とりあえずファイル名は固定 path = 'my_server_key_pair.pem' f1 = open(path,'a') f1.write(my_pem_hex) f1.close()
Example #19
Source File: test_dogtag.py From sgx-kms with Apache License 2.0 | 6 votes |
def test_get_private_key(self): test_key = RSA.generate(2048) key_data = dogtag_key.KeyData() key_data.data = test_key.exportKey('DER') self.keyclient_mock.retrieve_key.return_value = key_data secret_metadata = { dogtag_import.DogtagKRAPlugin.ALG: sstore.KeyAlgorithm.RSA, dogtag_import.DogtagKRAPlugin.BIT_LENGTH: 2048, dogtag_import.DogtagKRAPlugin.KEY_ID: 'key1', dogtag_import.DogtagKRAPlugin.CONVERT_TO_PEM: 'true' } result = self.plugin.get_secret(sstore.SecretType.PRIVATE, secret_metadata) self.assertEqual(test_key.exportKey('PEM').encode('utf-8'), result.secret)
Example #20
Source File: key_manager.py From cryptocurrency-samplecode with Apache License 2.0 | 6 votes |
def __init__(self, privatekey_text = None, pass_phrase= None): print('Initializing KeyManager...') if privatekey_text: self.import_key_pair(privatekey_text, pass_phrase) else: random_gen = Crypto.Random.new().read self._private_key = RSA.generate(2048, random_gen) self._public_key = self._private_key.publickey() self._signer = PKCS1_v1_5.new(self._private_key) if pass_phrase is not None: my_pem = self.export_key_pair(pass_phrase) my_pem_hex = binascii.hexlify(my_pem).decode('ascii') # とりあえずファイル名は固定 path = 'my_server_key_pair.pem' f1 = open(path,'a') f1.write(my_pem_hex) f1.close()
Example #21
Source File: generatekeypair.py From quay with Apache License 2.0 | 6 votes |
def generate_key_pair(filename, kid=None): private_key = RSA.generate(2048) jwk = RSAKey(key=private_key.publickey()).serialize() if kid is None: kid = canonical_kid(jwk) print(("Writing public key to %s.jwk" % filename)) with open("%s.jwk" % filename, mode="w") as f: f.truncate(0) f.write(json.dumps(jwk)) print(("Writing key ID to %s.kid" % filename)) with open("%s.kid" % filename, mode="w") as f: f.truncate(0) f.write(kid) print(("Writing private key to %s.pem" % filename)) with open("%s.pem" % filename, mode="w") as f: f.truncate(0) f.write(private_key.exportKey())
Example #22
Source File: protocol_fixtures.py From quay with Apache License 2.0 | 5 votes |
def jwk(): return RSAKey(key=RSA.generate(2048))
Example #23
Source File: test_jwtutil.py From quay with Apache License 2.0 | 5 votes |
def private_key(): return RSA.generate(2048)
Example #24
Source File: ssh.py From quay with Apache License 2.0 | 5 votes |
def generate_ssh_keypair(): """ Generates a new 2048 bit RSA public key in OpenSSH format and private key in PEM format. """ key = RSA.generate(2048) public_key = key.publickey().exportKey("OpenSSH") private_key = key.exportKey("PEM") return (public_key, private_key)
Example #25
Source File: encryptor.py From fluxclient with GNU Affero General Public License v3.0 | 5 votes |
def new_keyobj(cls, size=4096): ref = RSA.generate(size) return cls(ref)
Example #26
Source File: test_external_jwt_authn.py From quay with Apache License 2.0 | 5 votes |
def _generate_certs(): public_key = NamedTemporaryFile(delete=True) key = RSA.generate(1024) private_key_data = key.exportKey("PEM") pubkey = key.publickey() public_key.write(pubkey.exportKey("OpenSSH")) public_key.seek(0) return (public_key, private_key_data)
Example #27
Source File: PyCrypto_RSAKey.py From python-for-android with Apache License 2.0 | 5 votes |
def generate(bits): key = PyCrypto_RSAKey() def f(numBytes): return bytesToString(getRandomBytes(numBytes)) key.rsa = RSA.generate(bits, f) return key
Example #28
Source File: ckeygen.py From python-for-android with Apache License 2.0 | 5 votes |
def generateDSAkey(options): from Crypto.PublicKey import DSA print 'Generating public/private dsa key pair.' key = DSA.generate(int(options['bits']), randbytes.secureRandom) _saveKey(key, options)
Example #29
Source File: main.py From cryptovenom with GNU General Public License v3.0 | 5 votes |
def genKeys(bits): print('\033[1;34m[*]\033[0m Generating keys of ' + bits + ' bits.') random_generator = Random.new().read key = RSA.generate(int(bits), random_generator) privatekey = key.exportKey("PEM") publickey = key.publickey().exportKey("PEM") keys = [privatekey, publickey] return keys
Example #30
Source File: PyCrypto_RSAKey.py From python-for-android with Apache License 2.0 | 5 votes |
def generate(bits): key = PyCrypto_RSAKey() def f(numBytes): return bytesToString(getRandomBytes(numBytes)) key.rsa = RSA.generate(bits, f) return key