Python rsa.newkeys() Examples

The following are 20 code examples of rsa.newkeys(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rsa , or try the search function .
Example #1
Source File: rsaencrypt.py    From seecode-scanner with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #2
Source File: setup.py    From Mobile-Security-Framework-MobSF with GNU General Public License v3.0 6 votes vote down vote up
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..') 
Example #3
Source File: cli.py    From opsbro with MIT License 6 votes vote down vote up
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 
Example #4
Source File: serve.py    From starctf2018 with MIT License 5 votes vote down vote up
def gen_addr_key_pair():
	pubkey, privkey = rsa.newkeys(384)
	return pubkey_to_address(pubkey), privkey

#<hidden> 
Example #5
Source File: RSA-AES-MD5-DES-DES3-MD5-SHA-HMAC.py    From R-A-M-D-D3-S-M-H with MIT License 5 votes vote down vote up
def __init__(self, number=1024):
        """
        :param number: 公钥、私钥
        """
        self.pubkey, self.privkey = rsa.newkeys(number) 
Example #6
Source File: rsalib.py    From swift_rpc with MIT License 5 votes vote down vote up
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() 
Example #7
Source File: security.py    From marsnake with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #8
Source File: __init__.py    From ops_sdk with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #9
Source File: cli.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
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) 
Example #10
Source File: cli.py    From jarvis with GNU General Public License v2.0 4 votes vote down vote up
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) 
Example #11
Source File: utility.py    From tuijam with MIT License 4 votes vote down vote up
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 
Example #12
Source File: cli.py    From plugin.video.bdyun with GNU General Public License v3.0 4 votes vote down vote up
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) 
Example #13
Source File: cli.py    From opsbro with MIT License 4 votes vote down vote up
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) 
Example #14
Source File: cli.py    From luci-py with Apache License 2.0 4 votes vote down vote up
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) 
Example #15
Source File: cli.py    From xbmc-addons-chinese with GNU General Public License v2.0 4 votes vote down vote up
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) 
Example #16
Source File: cli.py    From xbmc-addons-chinese with GNU General Public License v2.0 4 votes vote down vote up
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) 
Example #17
Source File: cli.py    From bash-lambda-layer with MIT License 4 votes vote down vote up
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) 
Example #18
Source File: cli.py    From baidupan_shell with GNU General Public License v2.0 4 votes vote down vote up
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) 
Example #19
Source File: cli.py    From aqua-monitor with GNU Lesser General Public License v3.0 4 votes vote down vote up
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) 
Example #20
Source File: _licensing.py    From fbs with GNU General Public License v3.0 4 votes vote down vote up
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)