Generate a new pubkey for a new/existing GPG identity.
11276
def export_public_key(device_type, args):
    """"""
    log.warning('NOTE: in order to re-generate the exact same GPG key later, '
                'run this command with "--time=%d" commandline flag (to set '
                'the timestamp of the GPG key manually).', args.time)
    c = client.Client(device=device_type())
    identity = client.create_identity(user_id=args.user_id,
                                      curve_name=args.ecdsa_curve)
    verifying_key = c.pubkey(identity=identity, ecdh=False)
    decryption_key = c.pubkey(identity=identity, ecdh=True)
    signer_func = functools.partial(c.sign, identity=identity)

    if args.subkey:  # add as subkey
        log.info('adding %s GPG subkey for "%s" to existing key',
                 args.ecdsa_curve, args.user_id)
        # subkey for signing
        signing_key = protocol.PublicKey(
            curve_name=args.ecdsa_curve, created=args.time,
            verifying_key=verifying_key, ecdh=False)
        # subkey for encryption
        encryption_key = protocol.PublicKey(
            curve_name=formats.get_ecdh_curve_name(args.ecdsa_curve),
            created=args.time, verifying_key=decryption_key, ecdh=True)
        primary_bytes = keyring.export_public_key(args.user_id)
        result = encode.create_subkey(primary_bytes=primary_bytes,
                                      subkey=signing_key,
                                      signer_func=signer_func)
        result = encode.create_subkey(primary_bytes=result,
                                      subkey=encryption_key,
                                      signer_func=signer_func)
    else:  # add as primary
        log.info('creating new %s GPG primary key for "%s"',
                 args.ecdsa_curve, args.user_id)
        # primary key for signing
        primary = protocol.PublicKey(
            curve_name=args.ecdsa_curve, created=args.time,
            verifying_key=verifying_key, ecdh=False)
        # subkey for encryption
        subkey = protocol.PublicKey(
            curve_name=formats.get_ecdh_curve_name(args.ecdsa_curve),
            created=args.time, verifying_key=decryption_key, ecdh=True)

        result = encode.create_primary(user_id=args.user_id,
                                       pubkey=primary,
                                       signer_func=signer_func)
        result = encode.create_subkey(primary_bytes=result,
                                      subkey=subkey,
                                      signer_func=signer_func)

    return protocol.armor(result, 'PUBLIC KEY BLOCK')
858151
def gen_signature(priv_path, pub_path, sign_path, passphrase=None):
    '''
    
    '''

    with salt.utils.files.fopen(pub_path) as fp_:
        mpub_64 = fp_.read()

    mpub_sig = sign_message(priv_path, mpub_64, passphrase)
    mpub_sig_64 = binascii.b2a_base64(mpub_sig)
    if os.path.isfile(sign_path):
        return False
    log.trace(
        'Calculating signature for %s with %s',
        os.path.basename(pub_path), os.path.basename(priv_path)
    )

    if os.path.isfile(sign_path):
        log.trace(
            'Signature file %s already exists, please remove it first and '
            'try again', sign_path
        )
    else:
        with salt.utils.files.fopen(sign_path, 'wb+') as sig_f:
            sig_f.write(salt.utils.stringutils.to_bytes(mpub_sig_64))
        log.trace('Wrote signature to %s', sign_path)
    return True
1092942
def grok_keys(config):
    """"""
    key_ids = []
    for key in config['pgp_keys']:
        if key.startswith('keybase:'):
            key_id = from_keybase(key[8:])
            LOG.debug("Encrypting for keybase user %s", key[8:])
        else:
            if not has_gpg_key(key):
                raise aomi.exceptions.GPG("Do not actually have key %s" % key)

            LOG.debug("Encrypting for gpg id %s", key)
            key_id = key

        validate_gpg_fingerprint(key_id)
        key_ids.append(key_id)

    return key_ids
107420
function genPrivKey(){
	var privKey;
	do {
		console.log("generating new priv key");
		privKey = crypto.randomBytes(32);
	}
	while (!ecdsa.privateKeyVerify(privKey));
	return privKey;
}
264028
def create_ssh_pub_key(self, name, key):
        
        self.nova.keypairs.create(name, key)
1289818
function (uuids) {
    var guid = uuids[0]
    var sharedKey = uuids[1]

    if (!guid || !sharedKey || guid.length !== 36 || sharedKey.length !== 36) {
      throw 'Error generating wallet identifier'
    }

    return { guid: guid, sharedKey: sharedKey }
  }
1134366
def create_public_key_from_json(values):
        """"""
        # currently we only support RSA public keys
        _id = values.get('id')
        if not _id:
            # Make it more forgiving for now.
            _id = ''
            # raise ValueError('publicKey definition is missing the "id" value.')

        if values.get('type') == PUBLIC_KEY_TYPE_RSA:
            public_key = PublicKeyRSA(_id, owner=values.get('owner'))
        else:
            public_key = PublicKeyBase(_id, owner=values.get('owner'), type='EthereumECDSAKey')

        public_key.set_key_value(values)
        return public_key
1168291
def gpg_export_key( appname, key_id, config_dir=None, include_private=False ):
    

    assert is_valid_appname(appname)
    config_dir = get_config_dir( config_dir )
    keydir = get_gpg_home( appname, config_dir=config_dir )
    gpg = gnupg.GPG( homedir=keydir )
    keydat = gpg.export_keys( [key_id], secret=include_private )

    if not keydat:
        log.debug("Failed to export key %s from '%s'" % (key_id, keydir))

    assert keydat
    return keydat
778630
def fingerprint_from_keybase(fingerprint, kb_obj):
    """"""
    if 'public_keys' in kb_obj and \
       'pgp_public_keys' in kb_obj['public_keys']:
        for key in kb_obj['public_keys']['pgp_public_keys']:
            keyprint = fingerprint_from_var(key).lower()
            fingerprint = fingerprint.lower()
            if fingerprint == keyprint or \
               keyprint.startswith(fingerprint) or \
               keyprint.endswith(fingerprint):
                return {
                    'fingerprint': keyprint,
                    'bundle': key
                }

    return None
894875
public static PublicKey createPublicKey(byte[] publicKey) {
    if (publicKey == null) {
      return null;
    }
    
    try {
      KeyFactory fac = KeyFactory.getInstance("RSA");
      EncodedKeySpec spec = new X509EncodedKeySpec(publicKey);
      return fac.generatePublic(spec);
    }
    catch (NoSuchAlgorithmException e) {
      throw new IllegalStateException(e);
    }
    catch (InvalidKeySpecException e) {
      throw new IllegalStateException(e);
    }
  }
557411
def GenerateKeys(config, overwrite_keys=False):
  """"""
  if not hasattr(key_utils, "MakeCACert"):
    raise OpenSourceKeyUtilsRequiredError(
        "Generate keys can only run with open source key_utils.")
  if (config.Get("PrivateKeys.server_key", default=None) and
      not overwrite_keys):
    print(config.Get("PrivateKeys.server_key"))
    raise KeysAlreadyExistError(
        "Config %s already has keys, use --overwrite_keys to "
        "override." % config.parser)

  length = grr_config.CONFIG["Server.rsa_key_length"]
  print("All keys will have a bit length of %d." % length)
  print("Generating executable signing key")
  executable_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=length)
  config.Set("PrivateKeys.executable_signing_private_key",
             executable_key.AsPEM())
  config.Set("Client.executable_signing_public_key",
             executable_key.GetPublicKey().AsPEM())

  print("Generating CA keys")
  ca_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=length)
  ca_cert = key_utils.MakeCACert(ca_key)
  config.Set("CA.certificate", ca_cert.AsPEM())
  config.Set("PrivateKeys.ca_key", ca_key.AsPEM())

  print("Generating Server keys")
  server_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=length)
  server_cert = key_utils.MakeCASignedCert(u"grr", server_key, ca_cert, ca_key)
  config.Set("Frontend.certificate", server_cert.AsPEM())
  config.Set("PrivateKeys.server_key", server_key.AsPEM())

  print("Generating secret key for csrf protection.")
  _GenerateCSRFKey(config)
270311
def pubkey(self, identity, ecdh=False):
        """"""
        with self.device:
            pubkey = self.device.pubkey(ecdh=ecdh, identity=identity)
        return formats.decompress_pubkey(
            pubkey=pubkey, curve_name=identity.curve_name)
580290
def generateCertificate(self, alias,
                            commonName, organizationalUnit,
                            city, state, country,
                            keyalg="RSA", keysize=1024,
                            sigalg="SHA256withRSA",
                            validity=90
                            ):
        
        params = {"f" : "json",
                  "alias" : alias,
                  "commonName" : commonName,
                  "organizationalUnit" : organizationalUnit,
                  "city" : city,
                  "state" : state,
                  "country" : country,
                  "keyalg" : keyalg,
                  "keysize" : keysize,
                  "sigalg" : sigalg,
                  "validity" : validity
                  }
        url = self._url + "/SSLCertificate/ generateCertificate"
        return self._post(url=url,
                          param_dict=params,
                          proxy_port=self._proxy_port,
                          proxy_url=self._proxy_url)
715629
def pubkey(self, identity, ecdh=False):
        """"""
        _verify_support(identity)
        data = self.vk.to_string()
        x, y = data[:32], data[32:]
        prefix = bytearray([2 + (bytearray(y)[0] & 1)])
        return bytes(prefix) + x
1181189
def CreateKey(self, prikey=None):
        
        account = super(UserWallet, self).CreateKey(private_key=prikey)
        self.OnCreateAccount(account)
        contract = WalletContract.CreateSignatureContract(account.PublicKey)
        self.AddContract(contract)
        return account
911473
def generate_certificates(base_dir, *peer_names, pubKeyDir=None,
                          secKeyDir=None, sigKeyDir=None,
                          verkeyDir=None, clean=True):
    ''' '''
    pubKeyDir = pubKeyDir or 'public_keys'
    secKeyDir = secKeyDir or 'private_keys'
    verkeyDir = verkeyDir or 'verif_keys'
    sigKeyDir = sigKeyDir or 'sig_keys'

    # keys_dir = os.path.join(base_dir, 'certificates')
    e_keys_dir = os.path.join(base_dir, '_enc')
    s_keys_dir = os.path.join(base_dir, '_sig')

    public_keys_dir = os.path.join(base_dir, pubKeyDir)
    secret_keys_dir = os.path.join(base_dir, secKeyDir)
    ver_keys_dir = os.path.join(base_dir, verkeyDir)
    sig_keys_dir = os.path.join(base_dir, sigKeyDir)

    # Create directories for certificates, remove old content if necessary
    for d in [e_keys_dir, s_keys_dir, public_keys_dir, secret_keys_dir,
              ver_keys_dir, sig_keys_dir]:
        if clean and os.path.exists(d):
            shutil.rmtree(d)
        os.makedirs(d, exist_ok=True)

    # create new keys in certificates dir
    for peer_name in peer_names:
        createEncAndSigKeys(e_keys_dir, s_keys_dir, peer_name)

    # move public keys to appropriate directory
    for keys_dir, pkdir, skdir in [
        (e_keys_dir, public_keys_dir, secret_keys_dir),
        (s_keys_dir, ver_keys_dir, sig_keys_dir)
    ]:
        moveKeyFilesToCorrectLocations(keys_dir, pkdir, skdir)

    shutil.rmtree(e_keys_dir)
    shutil.rmtree(s_keys_dir)

    print('Public keys in {}'.format(public_keys_dir))
    print('Private keys in {}'.format(secret_keys_dir))
    print('Verification keys in {}'.format(ver_keys_dir))
    print('Signing keys in {}'.format(sig_keys_dir))
371735
def gen_keys(keysize=2048):
    '''
    
    '''
    # Mandate that keys are at least 2048 in size
    if keysize < 2048:
        keysize = 2048
    tdir = tempfile.mkdtemp()

    salt.crypt.gen_keys(tdir, 'minion', keysize)
    priv_path = os.path.join(tdir, 'minion.pem')
    pub_path = os.path.join(tdir, 'minion.pub')
    with salt.utils.files.fopen(priv_path) as fp_:
        priv = salt.utils.stringutils.to_unicode(fp_.read())
    with salt.utils.files.fopen(pub_path) as fp_:
        pub = salt.utils.stringutils.to_unicode(fp_.read())
    shutil.rmtree(tdir)
    return priv, pub