本文整理汇总了Python中rsa.newkeys方法的典型用法代码示例。如果您正苦于以下问题:Python rsa.newkeys方法的具体用法?Python rsa.newkeys怎么用?Python rsa.newkeys使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rsa
的用法示例。
在下文中一共展示了rsa.newkeys方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_secret
# 需要导入模块: import rsa [as 别名]
# 或者: from rsa import newkeys [as 别名]
def generate_secret():
"""Generate rsa keys for authentication."""
import rsa
print('[*] Generating secret, please hang on.')
# Generate keys, taken from
# https://stuvel.eu/python-rsa-doc/usage.html#generating-keys
(pubkey, privkey) = rsa.newkeys(2048)
# Save private and pub key
priv_key_file = open(CONFIG['MobSF']['priv_key'], 'w')
priv_key_file.write(privkey.save_pkcs1().decode('utf-8'))
priv_key_file.close()
pub_key_file = open(CONFIG['MobSF']['pub_key'], 'w')
pub_key_file.write(pubkey.save_pkcs1().decode('utf-8'))
pub_key_file.close()
print((
'[!] Please move the private key file\n'
'\t{}\n'
'\tto MobSF to the path specified in settings.py\n'
'\t(default: Mobile-Security-Framework-MobSF/'
'MobSF/windows_vm_priv_key.asc)'
.format(CONFIG['MobSF']['priv_key'])
))
input('Please press any key when done..')
示例2: do_keygen
# 需要导入模块: import rsa [as 别名]
# 或者: from rsa import newkeys [as 别名]
def do_keygen():
k = uuid.uuid1().hex[:16]
cprint('UDP Encryption key: (aka encryption_key)', end='')
cprint(base64.b64encode(k), color='green')
cprint('')
try:
import rsa
except ImportError:
logger.error('Missing python-rsa module for RSA keys generation, please install it')
return
pubkey, privkey = rsa.newkeys(2048)
cprint("Private RSA key (2048). (aka master_key_priv for for file mfkey.priv)")
s_privkey = privkey.save_pkcs1()
cprint(s_privkey, color='green')
cprint('')
cprint("Public RSA key (2048). (aka master_key_pub for file mfkey.pub)")
s_pubkey = pubkey.save_pkcs1()
cprint(s_pubkey, color='green')
cprint('')
# Sort threads by user time, if same, sort by name
示例3: generate_pem
# 需要导入模块: import rsa [as 别名]
# 或者: from rsa import newkeys [as 别名]
def generate_pem(self, save_path, nbits=2048):
"""
:param save_path: 保存路径
:param nbits:
:return:
"""
make_dir(save_path)
self.public_key, self.private_key = rsa.newkeys(nbits)
public_pem = os.path.join(save_path, 'public.pem')
private_pem = os.path.join(save_path, 'private.pem')
try:
with open(public_pem, 'w+') as fp:
fp.write(self.public_key.save_pkcs1().decode())
with open(private_pem, 'w+') as fp:
fp.write(self.private_key.save_pkcs1().decode())
except Exception as ex:
logger.error(ex)
return public_pem, private_pem
示例4: __init__
# 需要导入模块: import rsa [as 别名]
# 或者: from rsa import newkeys [as 别名]
def __init__(self, number=1024):
"""
:param number: 公钥、私钥
"""
self.pubkey, self.privkey = rsa.newkeys(number)
示例5: gen_addr_key_pair
# 需要导入模块: import rsa [as 别名]
# 或者: from rsa import newkeys [as 别名]
def gen_addr_key_pair():
pubkey, privkey = rsa.newkeys(384)
return pubkey_to_address(pubkey), privkey
#<hidden>
示例6: create_key
# 需要导入模块: import rsa [as 别名]
# 或者: from rsa import newkeys [as 别名]
def create_key():
(pubkey, privkey) = rsa.newkeys(1024)
pub = pubkey.save_pkcs1()
pubfile = open('public.pem','w+')
pubfile.write(pub)
pubfile.close()
pri = privkey.save_pkcs1()
prifile = open('private.pem','w+')
prifile.write(pri)
prifile.close()
示例7: on_initializing
# 需要导入模块: import rsa [as 别名]
# 或者: from rsa import newkeys [as 别名]
def on_initializing(self, *args, **kwargs):
(self.pubkey, self.privkey) = rsa.newkeys(1024)
self.server_pubkey = rsa.PublicKey.load_pkcs1(self.read_server_publickey())
return True
示例8: create_new_keys
# 需要导入模块: import rsa [as 别名]
# 或者: from rsa import newkeys [as 别名]
def create_new_keys(cls, num=4096): # 可以加密数据长度 4096/8 - 11
public_key, private_key = rsa.newkeys(num)
with open('public.pem', 'w+') as f:
f.write(public_key.save_pkcs1().decode())
with open('private.pem', 'w+') as f:
f.write(private_key.save_pkcs1().decode())
return public_key, private_key
示例9: init_licensing
# 需要导入模块: import rsa [as 别名]
# 或者: from rsa import newkeys [as 别名]
def init_licensing():
"""
Generate public/private keys for licensing
"""
require_existing_project()
try:
import rsa
except ImportError:
_LOG.error(
'Please install Python library `rsa`. Eg. via:\n'
' pip install rsa'
)
return
nbits = _prompt_for_nbits()
print('')
pubkey, privkey = rsa.newkeys(nbits)
pubkey_args = {'n': pubkey.n, 'e': pubkey.e}
privkey_args = {
attr: getattr(privkey, attr) for attr in ('n', 'e', 'd', 'p', 'q')
}
update_json(path(SECRET_JSON), {
'licensing_privkey': privkey_args,
'licensing_pubkey': pubkey_args
})
try:
with open(path(BASE_JSON)) as f:
user_base_settings = json.load(f)
except FileNotFoundError:
user_base_settings = {}
public_settings = user_base_settings.get('public_settings', [])
if 'licensing_pubkey' not in public_settings:
public_settings.append('licensing_pubkey')
update_json(path(BASE_JSON), {'public_settings': public_settings})
updated_base_json = True
else:
updated_base_json = False
message = 'Saved a public/private key pair for licensing to:\n %s.\n' \
% SECRET_JSON
if updated_base_json:
message += 'Also added "licensing_pubkey" to "public_settings" in' \
'\n %s.\n' \
'(This lets your app read the public key when it runs.)\n' \
% BASE_JSON
message += '\nFor details on how to implement licensing for your ' \
'application, see:\n '\
' https://build-system.fman.io/manual#licensing.'
_LOG.info(message)
示例10: keygen
# 需要导入模块: import rsa [as 别名]
# 或者: from rsa import newkeys [as 别名]
def keygen():
"""Key generator."""
# Parse the CLI options
parser = OptionParser(usage='usage: %prog [options] keysize',
description='Generates a new RSA keypair of "keysize" bits.')
parser.add_option('--pubout', type='string',
help='Output filename for the public key. The public key is '
'not saved if this option is not present. You can use '
'pyrsa-priv2pub to create the public key file later.')
parser.add_option('-o', '--out', type='string',
help='Output filename for the private key. The key is '
'written to stdout if this option is not present.')
parser.add_option('--form',
help='key format of the private and public keys - default PEM',
choices=('PEM', 'DER'), default='PEM')
(cli, cli_args) = parser.parse_args(sys.argv[1:])
if len(cli_args) != 1:
parser.print_help()
raise SystemExit(1)
try:
keysize = int(cli_args[0])
except ValueError:
parser.print_help()
print('Not a valid number: %s' % cli_args[0], file=sys.stderr)
raise SystemExit(1)
print('Generating %i-bit key' % keysize, file=sys.stderr)
(pub_key, priv_key) = rsa.newkeys(keysize)
# Save public key
if cli.pubout:
print('Writing public key to %s' % cli.pubout, file=sys.stderr)
data = pub_key.save_pkcs1(format=cli.form)
with open(cli.pubout, 'wb') as outfile:
outfile.write(data)
# Save private key
data = priv_key.save_pkcs1(format=cli.form)
if cli.out:
print('Writing private key to %s' % cli.out, file=sys.stderr)
with open(cli.out, 'wb') as outfile:
outfile.write(data)
else:
print('Writing private key to stdout', file=sys.stderr)
sys.stdout.write(data)
示例11: keygen
# 需要导入模块: import rsa [as 别名]
# 或者: from rsa import newkeys [as 别名]
def keygen():
'''Key generator.'''
# Parse the CLI options
parser = OptionParser(usage='usage: %prog [options] keysize',
description='Generates a new RSA keypair of "keysize" bits.')
parser.add_option('--pubout', type='string',
help='Output filename for the public key. The public key is '
'not saved if this option is not present. You can use '
'pyrsa-priv2pub to create the public key file later.')
parser.add_option('-o', '--out', type='string',
help='Output filename for the private key. The key is '
'written to stdout if this option is not present.')
parser.add_option('--form',
help='key format of the private and public keys - default PEM',
choices=('PEM', 'DER'), default='PEM')
(cli, cli_args) = parser.parse_args(sys.argv[1:])
if len(cli_args) != 1:
parser.print_help()
raise SystemExit(1)
try:
keysize = int(cli_args[0])
except ValueError:
parser.print_help()
print('Not a valid number: %s' % cli_args[0], file=sys.stderr)
raise SystemExit(1)
print('Generating %i-bit key' % keysize, file=sys.stderr)
(pub_key, priv_key) = rsa.newkeys(keysize)
# Save public key
if cli.pubout:
print('Writing public key to %s' % cli.pubout, file=sys.stderr)
data = pub_key.save_pkcs1(format=cli.form)
with open(cli.pubout, 'wb') as outfile:
outfile.write(data)
# Save private key
data = priv_key.save_pkcs1(format=cli.form)
if cli.out:
print('Writing private key to %s' % cli.out, file=sys.stderr)
with open(cli.out, 'wb') as outfile:
outfile.write(data)
else:
print('Writing private key to stdout', file=sys.stderr)
sys.stdout.write(data)
示例12: lookup_keys
# 需要导入模块: import rsa [as 别名]
# 或者: from rsa import newkeys [as 别名]
def lookup_keys(*key_ids):
import base64
import yaml
import rsa
import requests
from tuijam import CONFIG_FILE
keys = [None] * len(key_ids)
# First, check if any are in configuration file
with open(CONFIG_FILE, "r") as f:
cfg = yaml.safe_load(f)
for idx, id_ in enumerate(key_ids):
try:
keys[idx] = cfg[id_]
except KeyError:
pass
# Next, if any unspecified in config file, ask the server for them
to_query = {}
for idx, (id_, key) in enumerate(zip(key_ids, keys)):
if key is None:
# keep track of position of each key so output order matches
to_query[id_] = idx
if to_query:
(pub, priv) = rsa.newkeys(512) # Generate new RSA key pair. Do not reuse keys!
host = cfg.get("key_server", "https://tuijam.fangmeier.tech")
res = requests.post(
host, json={"public_key": pub.save_pkcs1().decode(), "ids": list(to_query)}
)
for id_, key_encrypted in res.json().items():
# On the server, the api key is encrypted with the public RSA key,
# and then base64 encoded to be delivered. Reverse that process here.
key_decrypted = rsa.decrypt(
base64.decodebytes(key_encrypted.encode()), priv
).decode()
keys[to_query[id_]] = key_decrypted
return keys