本文整理匯總了Python中Crypto.PublicKey.RSA.importKey方法的典型用法代碼示例。如果您正苦於以下問題:Python RSA.importKey方法的具體用法?Python RSA.importKey怎麽用?Python RSA.importKey使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類Crypto.PublicKey.RSA
的用法示例。
在下文中一共展示了RSA.importKey方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: create
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import importKey [as 別名]
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)
示例2: from_string
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import importKey [as 別名]
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)
示例3: testVerify1
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import importKey [as 別名]
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)
示例4: testEncrypt1
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import importKey [as 別名]
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]))
示例5: from_string
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import importKey [as 別名]
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)
示例6: from_string
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import importKey [as 別名]
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)
示例7: check_rsa_key
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import importKey [as 別名]
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)
示例8: testSign1
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import importKey [as 別名]
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]))
示例9: decrypt
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import importKey [as 別名]
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)
示例10: encrypt
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import importKey [as 別名]
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])
示例11: prepare_key
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import importKey [as 別名]
def prepare_key(self, key):
if isinstance(key, RSA._RSAobj):
return key
if isinstance(key, string_types):
if isinstance(key, text_type):
key = key.encode('utf-8')
key = RSA.importKey(key)
else:
raise TypeError('Expecting a PEM- or RSA-formatted key.')
return key
示例12: parseN
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import importKey [as 別名]
def parseN(argv,index):
file = open(argv[index],'r')
fileInput = ''.join(file.readlines()).strip()
try:
fileInput = long(fileInput)
return fileInput
except ValueError:
from Crypto.PublicKey import RSA
return long(RSA.importKey(fileInput).__getattr__('n'))
pass
示例13: import_key
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import importKey [as 別名]
def import_key(key_path: str) -> RSA:
with open(key_path, 'r') as f:
return RSA.importKey(f.read())
示例14: verify_incoming_request
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import importKey [as 別名]
def verify_incoming_request(form_data: dict) -> bool:
"""verify the incoming form_data"""
# copy form data
input_data = form_data.copy()
signature = input_data["p_signature"]
# Remove the p_signature parameter
del input_data["p_signature"]
# Ensure all the data fields are strings
for field in input_data:
input_data[field] = str(input_data[field])
# Sort the data
sorted_data = collections.OrderedDict(sorted(input_data.items()))
# and serialize the fields
serialized_data = phpserialize.dumps(sorted_data)
# verify the data
key = RSA.importKey(public_key_der)
digest = SHA1.new()
digest.update(serialized_data)
verifier = PKCS1_v1_5.new(key)
signature = base64.b64decode(signature)
if verifier.verify(digest, signature):
return True
return False
示例15: decrypt_rsa
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import importKey [as 別名]
def decrypt_rsa(key, data):
rsa_key = RSA.importKey(key)
return rsa_key.decrypt(data)
# XOR