本文整理汇总了Python中cryptography.hazmat.primitives.serialization.load_ssh_public_key方法的典型用法代码示例。如果您正苦于以下问题:Python serialization.load_ssh_public_key方法的具体用法?Python serialization.load_ssh_public_key怎么用?Python serialization.load_ssh_public_key使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cryptography.hazmat.primitives.serialization
的用法示例。
在下文中一共展示了serialization.load_ssh_public_key方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: encryptClientPrivKey
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_ssh_public_key [as 别名]
def encryptClientPrivKey(priv_key):
"""Encrypt the Clients private key (given as a str) with the servers public key"""
with open(_helper.path('res/server.public.key'), "rb") as key_file:
public_key = serialization.load_ssh_public_key(
key_file.read(),
backend=default_backend()
)
key_file.close()
cipher = public_key.encrypt(
bytes(priv_key, 'utf-8'),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA1(),
label=None
)
)
_helper.info("Private Client Key is encrypted")
return cipher
示例2: validate_public_key
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_ssh_public_key [as 别名]
def validate_public_key(value):
"""
Check that the given value is a valid RSA Public key in either PEM or OpenSSH format. If it is invalid,
raises ``django.core.exceptions.ValidationError``.
"""
is_valid = False
exc = None
for load in (load_pem_public_key, load_ssh_public_key):
if not is_valid:
try:
load(value.encode('utf-8'), default_backend())
is_valid = True
except Exception as e:
exc = e
if not is_valid:
raise ValidationError('Public key is invalid: %s' % exc)
示例3: check_public_key
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_ssh_public_key [as 别名]
def check_public_key(data):
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
try:
key = serialization.load_ssh_public_key(
data, default_backend())
return True
except:
return False
示例4: test_export_pubkey
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_ssh_public_key [as 别名]
def test_export_pubkey(self):
""" export a public key and make sure the parameters are the right ones:
since there's very little we can do to check rsa key parameters are right
we pre-exported the public key to an ssh key, which we can load with
cryptography for the sake of comparison """
# export our gpg key, using our functions
key_data = export_pubkey(self.default_keyid, homedir=self.gnupg_home)
our_exported_key = rsa_create_pubkey(key_data)
# load the equivalent ssh key, and make sure that we get the same RSA key
# parameters
ssh_key_basename = "{}.ssh".format(self.default_keyid)
ssh_key_path = os.path.join(self.gnupg_home, ssh_key_basename)
with open(ssh_key_path, "rb") as fp:
keydata = fp.read()
ssh_key = serialization.load_ssh_public_key(keydata,
backends.default_backend())
self.assertEqual(ssh_key.public_numbers().n,
our_exported_key.public_numbers().n)
self.assertEqual(ssh_key.public_numbers().e,
our_exported_key.public_numbers().e)
subkey_keyids = list(key_data["subkeys"].keys())
# We export the whole master key bundle which must contain the subkeys
self.assertTrue(self.signing_subkey_keyid.lower() in subkey_keyids)
# Currently we do not exclude encryption subkeys
self.assertTrue(self.encryption_subkey_keyid.lower() in subkey_keyids)
# However we do exclude subkeys, whose algorithm we do not support
self.assertFalse(self.unsupported_subkey_keyid.lower() in subkey_keyids)
# When passing the subkey keyid we also export the whole keybundle
key_data2 = export_pubkey(self.signing_subkey_keyid,
homedir=self.gnupg_home)
self.assertDictEqual(key_data, key_data2)
示例5: __init__
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_ssh_public_key [as 别名]
def __init__(self, ssh_public_key):
"""
Extracts the useful RSA Public Key information from an SSH Public Key file.
:param ssh_public_key: SSH Public Key file contents. (i.e. 'ssh-rsa AAAAB3NzaC1yc2E..').
"""
super(RSAPublicKey, self).__init__()
self.type = SSHPublicKeyType.RSA
split_ssh_public_key = ssh_public_key.split(' ')
split_key_len = len(split_ssh_public_key)
# is there a key comment at the end?
if split_key_len > 2:
self.key_comment = ' '.join(split_ssh_public_key[2:])
else:
self.key_comment = ''
public_key = serialization.load_ssh_public_key(ssh_public_key.encode('ascii'), default_backend())
ca_pub_numbers = public_key.public_numbers()
if not isinstance(ca_pub_numbers, RSAPublicNumbers):
raise TypeError("Public Key is not the correct type or format")
self.key_size = public_key.key_size
self.e = ca_pub_numbers.e
self.n = ca_pub_numbers.n
key_bytes = base64.b64decode(split_ssh_public_key[1])
fingerprint = hashlib.md5(key_bytes).hexdigest()
self.fingerprint = 'RSA ' + ':'.join(
fingerprint[i:i + 2] for i in range(0, len(fingerprint), 2))
示例6: validate
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_ssh_public_key [as 别名]
def validate(self, request):
"""Validate uploaded test results."""
super(TestResultValidator, self).validate(request)
if request.headers.get('X-Signature') or \
request.headers.get('X-Public-Key'):
try:
sign = binascii.a2b_hex(request.headers.get('X-Signature', ''))
except (binascii.Error, TypeError) as e:
raise api_exc.ValidationError('Malformed signature', e)
try:
key = load_ssh_public_key(
request.headers.get('X-Public-Key', ''),
backend=backends.default_backend()
)
except (binascii.Error, ValueError) as e:
raise api_exc.ValidationError('Malformed public key', e)
verifier = key.verifier(sign, padding.PKCS1v15(), hashes.SHA256())
verifier.update(request.body)
try:
verifier.verify()
except InvalidSignature:
raise api_exc.ValidationError('Signature verification failed')
if self._is_empty_result(request):
raise api_exc.ValidationError('Uploaded results must contain at '
'least one passing test.')
示例7: process_ssh_line
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_ssh_public_key [as 别名]
def process_ssh_line(self, data, name, idx):
"""
Processes single SSH key
:param data:
:param name:
:param idx:
:return:
"""
data = data.strip()
if not contains(data, 'ssh-rsa'):
return
# strip ssh params / adjustments
try:
data = data[to_bytes(data).find(b'ssh-rsa'):]
except Exception as e:
pass
from cryptography.hazmat.primitives.serialization import load_ssh_public_key
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
try:
key_obj = load_ssh_public_key(data, self.get_backend())
self.num_ssh += 1
if not isinstance(key_obj, RSAPublicKey):
return
self.num_rsa += 1
numbers = key_obj.public_numbers()
js = collections.OrderedDict()
js['type'] = 'ssh-rsa'
js['fname'] = name
js['idx'] = idx
js['e'] = '0x%x' % numbers.e
js['n'] = '0x%x' % numbers.n
js['ssh'] = data
if self.has_fingerprint(numbers.n):
logger.warning('Fingerprint found in the SSH key %s idx %s ' % (name, idx))
self.mark_and_add_effort(numbers.n, js)
if self.do_print:
print(json.dumps(js))
return TestResult(js)
except Exception as e:
logger.debug('Exception in processing SSH public key %s idx %s : %s' % (name, idx, e))
self.trace_logger.log(e)
示例8: encrypt_file
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_ssh_public_key [as 别名]
def encrypt_file(self, file_name, client_pub_key):
if not os.path.isfile(file_name):
return
#calculate the MAX_SIZE in GB
file_size = os.path.getsize(file_name) * 0.000000001
if file_size > Config.MAX_SIZE_LIMIT:
return
public_key = serialization.load_ssh_public_key(
bytes(client_pub_key, 'utf-8'),
backend=default_backend()
)
#write the AES encryption key into a seperate file
keyb64 = base64.b64encode(self.key)
ivb64 = base64.b64encode(self.iv)
t = bytes(keyb64.decode(self.encoding) + ";" + ivb64.decode(self.encoding), self.encoding)
cipher = public_key.encrypt(
t,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA1(),
label=None
)
)
cipher = base64.b64encode(cipher)
with open(file_name, 'rb') as fo:
plaintext = fo.read()
enc = self.encrypt(plaintext, self.key)
with open(file_name + ".supergirl", 'wb') as fo:
fo.write(enc)
with open(file_name + ".kryptonian", 'wb') as info:
info.write(cipher)
os.remove(file_name)
示例9: decode_token
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_ssh_public_key [as 别名]
def decode_token(request):
"""Validate request signature.
ValidationError rises if request is not valid.
"""
if not request.headers.get(const.JWT_TOKEN_HEADER):
return
try:
auth_schema, token = request.headers.get(
const.JWT_TOKEN_HEADER).split(' ', 1)
except ValueError:
raise api_exc.ValidationError("Token is not valid")
if auth_schema != 'Bearer':
raise api_exc.ValidationError(
"Authorization schema 'Bearer' should be used")
try:
token_data = jwt.decode(token, algorithms='RS256', verify=False)
except jwt.InvalidTokenError:
raise api_exc.ValidationError("Token is not valid")
openid = token_data.get(const.USER_OPENID)
if not openid:
raise api_exc.ValidationError("Token does not contain user's openid")
pubkeys = db.get_user_pubkeys(openid)
for pubkey in pubkeys:
try:
pubkey_string = '%s %s' % (pubkey['format'], pubkey['pubkey'])
pubkey_obj = serialization.load_ssh_public_key(
pubkey_string.encode('utf-8'),
backend=backends.default_backend()
)
pem_pubkey = pubkey_obj.public_bytes(
serialization.Encoding.PEM,
serialization.PublicFormat.SubjectPublicKeyInfo)
except (ValueError, IndexError, TypeError, binascii.Error):
pass
else:
try:
token_data = jwt.decode(
token, key=pem_pubkey,
options={'verify_signature': True,
'verify_exp': True,
'require_exp': True},
leeway=const.JWT_VALIDATION_LEEWAY)
# NOTE(sslipushenko) If at least one key is valid, let
# the validation pass
return token_data
except jwt.InvalidTokenError:
pass
# NOTE(sslipushenko) If all user's keys are not valid, the validation fails
raise api_exc.ValidationError("Token is not valid")