本文整理匯總了Python中Crypto.PublicKey.RSA.generate方法的典型用法代碼示例。如果您正苦於以下問題:Python RSA.generate方法的具體用法?Python RSA.generate怎麽用?Python RSA.generate使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類Crypto.PublicKey.RSA
的用法示例。
在下文中一共展示了RSA.generate方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: create_rsa_pair
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import generate [as 別名]
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()
示例2: create_cred_keys
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import generate [as 別名]
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)
示例3: clean_studio_edits
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import generate [as 別名]
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)
示例4: setUp
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import generate [as 別名]
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
示例5: test_jwe
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import generate [as 別名]
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.')
示例6: test_jwe_decrypt_compliant_incorrect_jwk
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import generate [as 別名]
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.")
示例7: __init__
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import generate [as 別名]
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)]
示例8: __init__
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import generate [as 別名]
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()
示例9: generate_service_key
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import generate [as 別名]
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)
示例10: generate_key_pair
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import generate [as 別名]
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())
示例11: _setup_rsa_keys
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import generate [as 別名]
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()))
示例12: test_rsa_provider_init_invalid_keys
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import generate [as 別名]
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時拋出異常
示例13: test_rsa_provider_init_invalid_passphrase
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import generate [as 別名]
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加/解密
示例14: test_should_return_for_pycrypto_stored_key_without_passphrase
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import generate [as 別名]
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.
示例15: test_should_raise_for_pycrypto_stored_key_no_container
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import generate [as 別名]
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)