當前位置: 首頁>>代碼示例>>Python>>正文


Python rsa.newkeys方法代碼示例

本文整理匯總了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..') 
開發者ID:MobSF,項目名稱:Mobile-Security-Framework-MobSF,代碼行數:27,代碼來源:setup.py

示例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 
開發者ID:naparuba,項目名稱:opsbro,代碼行數:25,代碼來源:cli.py

示例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 
開發者ID:seecode-audit,項目名稱:seecode-scanner,代碼行數:23,代碼來源:rsaencrypt.py

示例4: __init__

# 需要導入模塊: import rsa [as 別名]
# 或者: from rsa import newkeys [as 別名]
def __init__(self, number=1024):
        """
        :param number: 公鑰、私鑰
        """
        self.pubkey, self.privkey = rsa.newkeys(number) 
開發者ID:inlike,項目名稱:R-A-M-D-D3-S-M-H,代碼行數:7,代碼來源:RSA-AES-MD5-DES-DES3-MD5-SHA-HMAC.py

示例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> 
開發者ID:sixstars,項目名稱:starctf2018,代碼行數:7,代碼來源:serve.py

示例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() 
開發者ID:rfyiamcool,項目名稱:swift_rpc,代碼行數:13,代碼來源:rsalib.py

示例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 
開發者ID:turingsec,項目名稱:marsnake,代碼行數:7,代碼來源:security.py

示例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 
開發者ID:ss1917,項目名稱:ops_sdk,代碼行數:10,代碼來源:__init__.py

示例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) 
開發者ID:mherrmann,項目名稱:fbs,代碼行數:49,代碼來源:_licensing.py

示例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) 
開發者ID:Deltares,項目名稱:aqua-monitor,代碼行數:55,代碼來源:cli.py

示例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) 
開發者ID:deadblue,項目名稱:baidupan_shell,代碼行數:56,代碼來源:cli.py

示例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 
開發者ID:cfangmeier,項目名稱:tuijam,代碼行數:44,代碼來源:utility.py


注:本文中的rsa.newkeys方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。