Generate and set a psk from the security key.
480762
def generate_psk(self, security_key):
        
        if not self._psk:
            # Backup the real identity.
            existing_psk_id = self._psk_id

            # Set the default identity and security key for generation.
            self._psk_id = 'Client_identity'
            self._psk = security_key

            # Ask the Gateway to generate the psk for the identity.
            self._psk = self.request(Gateway().generate_psk(existing_psk_id))

            # Restore the real identity.
            self._psk_id = existing_psk_id

        return self._psk
142764
def create_key_file(service, key):
    """"""
    keyfile = _keyfile_path(service)
    if os.path.exists(keyfile):
        log('Keyfile exists at %s.' % keyfile, level=WARNING)
        return

    with open(keyfile, 'w') as fd:
        fd.write(key)

    log('Created new keyfile at %s.' % keyfile, level=INFO)
617181
def generate_private_key(self):
        
        key_length = self.key_length // 8 + 8
        key = 0

        try:
            key = int.from_bytes(rng(key_length), byteorder='big')
        except:
            key = int(hex(rng(key_length)), base=16)

        self.__private_key = key
1320385
def generate_rsa_key_pair():
    """"""

    key = rsa.generate_private_key(
        backend=default_backend(), public_exponent=65537, key_size=2048)

    public_key = key.public_key().public_bytes(
        serialization.Encoding.OpenSSH,
        serialization.PublicFormat.OpenSSH).decode("utf-8")

    pem = key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption()).decode("utf-8")

    return public_key, pem
40944
def __set_private_key(self, pk):
		
		self.__private_key = pk
		self.__public_key = pk.public_key()
25832
def generate(cls):
        
        return cls(libnacl.randombytes(PrivateKey.SIZE), encoder=encoding.RawEncoder)
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))
128840
def generate_keypair(curve='secp160r1', randfunc=None):
    
    if randfunc is None:
        randfunc = Crypto.Random.new().read
    curve = Curve.by_name(curve)
    raw_privkey = randfunc(curve.order_len_bin)
    privkey = serialize_number(deserialize_number(raw_privkey), SER_COMPACT)
    pubkey = str(passphrase_to_pubkey(privkey))
    return (privkey, pubkey)
63832
private SecretKey generateAESKey(String privateKey, String salt) {
        try {
            byte[] raw = decodeHex(salt);
            KeySpec spec = new PBEKeySpec(privateKey.toCharArray(), raw, iterationCount, keySize);
            SecretKeyFactory factory = SecretKeyFactory.getInstance(PBKDF_2_WITH_HMAC_SHA_1);
            return new SecretKeySpec(factory.generateSecret(spec).getEncoded(), AES_ECB_ALGORITHM);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw new IllegalStateException(e);
        }
    }
778228
public static final void keygen(byte[] P, byte[] s, byte[] k) {
		clamp(k);
		core(P, s, k, null);
	}
776194
def add_key(pub):
    """"""
    global _server_keys
    key = rsa.PublicKey.load_pkcs1(pub)
    _server_keys[_compute_fingerprint(key)] = key
983944
def keypair_setup():
  """"""

  os.system('mkdir -p ' + u.PRIVATE_KEY_LOCATION)

  keypair_name = u.get_keypair_name()
  keypair = u.get_keypair_dict().get(keypair_name, None)
  keypair_fn = u.get_keypair_fn()
  if keypair:
    print("Reusing keypair " + keypair_name)
    # check that local pem file exists and is readable
    assert os.path.exists(
      keypair_fn), "Keypair %s exists, but corresponding .pem file %s is not found, delete keypair %s through console and run again to recreate keypair/.pem together" % (
      keypair_name, keypair_fn, keypair_name)
    keypair_contents = open(keypair_fn).read()
    assert len(keypair_contents) > 0
  else:
    print("Creating keypair " + keypair_name)
    ec2 = u.get_ec2_resource()
    assert not os.path.exists(
      keypair_fn), "previous keypair exists, delete it with 'sudo rm %s' and also delete corresponding keypair through console" % (
      keypair_fn)
    keypair = ec2.create_key_pair(KeyName=keypair_name)

    open(keypair_fn, 'w').write(keypair.key_material)
    os.system('chmod 400 ' + keypair_fn)

  return keypair
1140749
def generate_psk(self, identity):
        
        def process_result(result):
            return result[ATTR_PSK]

        return Command('post', [ROOT_GATEWAY, ATTR_AUTH], {
            ATTR_IDENTITY: identity
        }, process_result=process_result)
880289
def generate_keystore(key_alias, key_folder='./', root_cert='', truststore='', password='', organization='', organization_unit='', locality='', country='', key_size=2048, verbose=True, overwrite=False):

    '''  '''

    title = 'generate_keystore'
    
# import dependencies
    import os
    from subprocess import call, STDOUT, Popen, PIPE
    DEVNULL = open(os.devnull, 'w')

# define system call
    def _call(sys_command, ignore='', prompt_input='', title=''):
        if title and verbose:
            print('%s ... ' % title, end='', flush=True)
        p = Popen(sys_command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
        if prompt_input:
            stdout, stderr = p.communicate(str('%s\n' % prompt_input).encode('utf-8'))
        if p.returncode != 0:
            cmd_err = p.stdout.read().decode()
            if not cmd_err:
                pass
            elif ignore:
                if not cmd_err.find(ignore) > -1:
                    raise Exception(cmd_err)
            else:
                if title and verbose:
                    print('ERROR.')
                raise Exception(cmd_err)
        if title and verbose:
            print('done.')

# verify libraries
    try:
        call('openssl version', shell=True, stdout=DEVNULL)
    except:
        raise Exception('%s requires openssl library. try: sudo apt-get install openssl' % title)
    try:
        _call('keytool -help', ignore='Key and Certificate Management Tool')
    except:
        raise Exception('%s requires keytool library. try: sudo apt-get install openjdk-8-jre' % title)

# validate input
    if not isinstance(key_alias, str):
        raise ValueError('%s(key_alias="...") must be a string datatype.' % title)
    if not key_size in (2048, 4096):
        raise ValueError('%s(key_size=%s must be either 2048 or 4096' % (title, key_size))
    import re
    input_fields = {
        'organization': organization,
        'organization_unit': organization_unit,
        'locality': locality,
        'country': country
    }
    for key, value in input_fields.items():
        if re.findall('[^\w_\-\s]', value):
            raise ValueError('%s(%s="%s") must contain only alphanumeric characters, _, - and spaces.' % (title, key, value))

# construct key folder
    from os import path, makedirs, remove
    if not path.exists(key_folder):
        makedirs(key_folder)
    elif not path.isdir(key_folder):
        raise ValueError('%s(key_folder="%s") must be a directory.' % (title, key_folder))

# validate cert path
    cert_path = path.join(key_folder, '%s.crt' % key_alias)
    if path.exists(cert_path) and not overwrite:
        raise ValueError('%s.crt already exists in %s. to overwrite, set overwrite=true' % (key_alias, key_folder))

# validate root path
    from copy import deepcopy
    root_cert_copy = deepcopy(root_cert)
    if root_cert_copy:
        if not path.exists(root_cert_copy):
            root_cert_copy = path.join(key_folder, root_cert_copy)
            if not path.exists(root_cert_copy):
                raise ValueError('%s(root_cert="%s") is not a valid path.' % (title, root_cert_copy))
        root_node, root_ext = path.splitext(root_cert_copy)
        root_key = root_node + '.key'
        if not root_ext in ('.crt', '.pem'):
            raise ValueError('%s(root_cert="%s") must be a .crt or .pem file type.' % (title, root_cert_copy))
        elif not path.exists(root_key):
            key_path, key_name = path.split(root_key)
            raise ValueError('%s(root_cert="%s") requires a matching private key %s' % (title, root_cert_copy, key_name))
        root_path = root_cert_copy
        key_path = root_path.replace('.crt', '.key')
    else:
        key_path = path.join(key_folder, 'root.key')
        root_path = path.join(key_folder, 'root.crt')
        if path.exists(root_path) and not overwrite:
            raise ValueError('root.crt already exists in %s. to overwrite, set overwrite=true' % key_folder)

# validate truststore path
    truststore_copy = deepcopy(truststore)
    if truststore_copy:
        if not path.exists(truststore_copy):
            truststore_copy = path.join(key_folder, truststore_copy)
            if not path.exists(truststore_copy):
                raise ValueError('%s(truststore="%s") is not a valid path.' % (title, truststore_copy))
        trust_node, trust_ext = path.splitext(truststore_copy)
        if not trust_ext in ('.jks'):
            raise ValueError('%s(truststore="%s") must be a .jks file type.' % (title, truststore_copy))
        truststore_path = truststore_copy
        trust_root, trust_node = path.split(truststore_path)
        trust_alias, trust_ext = path.splitext(trust_node)
    else:
        truststore_path = path.join(key_folder, 'truststore.jks')
        trust_alias = 'truststore'
        if path.exists(truststore_path) and not overwrite:
            raise ValueError('%s.jks already exists in %s. to overwrite, set overwrite=true' % (trust_alias, key_folder))

# format DNAME fields
    if not organization:
        organization = 'None'
    if not organization_unit:
        organization_unit = 'None'
    if not locality:
        locality = 'None'
    if not country:
        country = 'None'

# create root certificate
    if not root_cert_copy:
        subject_args = '/CN=root/OU=%s/O=%s/L=%s/C=%s' % (
            organization_unit,
            organization,
            locality,
            country
        )
        root_subject = '-subj %s' % subject_args.replace(' ', '\ ')
        password_text = '-passout pass:%s' % password
        sys_command = 'openssl req -newkey rsa:%s -x509 -nodes -keyout %s -out %s -days 36500 %s %s' % (key_size, key_path, root_path, root_subject, password_text)
        _call(sys_command, ignore='writing new private key', title='Generating root certificate')

# generate server cert
    server_dname = '-dname "CN=%s, OU=%s, O=%s, L=%s, C=%s"' % (
        key_alias, organization_unit, organization, locality, country
    )
    keystore_path = path.join(key_folder, '%s.jks' % key_alias)
    if path.exists(keystore_path) and not overwrite:
        raise ValueError('%s.jks already exists in %s. to overwrite, set overwrite=true' % (key_alias, key_folder))
    elif path.exists(keystore_path):
        remove(keystore_path)
    sys_command = 'keytool -genkey -keyalg RSA -alias %s -validity 36500 -keystore %s -storepass %s -keypass %s -keysize %s %s' % (key_alias, keystore_path, password, password, key_size, server_dname)
    _call(sys_command, ignore='JKS keystore uses a proprietary format', title='Generating keystore for %s' % key_alias)

# convert cert to pkcs12
    sys_command = 'keytool -importkeystore -srckeystore %s -destkeystore %s -deststoretype pkcs12 -storepass %s -keypass %s' % (keystore_path, keystore_path, password, password)
    _call(sys_command, prompt_input=password, title='Converting keystore to pkcs12 standard')
    remove('%s.old' % keystore_path)

# generate certificate request
    request_path = path.join(key_folder, '%s.csr' % key_alias)
    sys_command = 'keytool -certreq -alias %s -file %s -keystore %s -storepass %s -keypass %s %s' % (
        key_alias, request_path, keystore_path, password, password, server_dname
    )
    _call(sys_command, title='Generating certificate signing request for %s'% key_alias)

# sign server cert with root cert
    cert_path = path.join(key_folder, '%s.crt' % key_alias)
    sys_command = 'openssl x509 -req -CA %s -CAkey %s -in %s -out %s -days 36500 -CAcreateserial -passin pass:%s' % (root_path, key_path, request_path, cert_path, password)
    _call(sys_command, ignore='Getting CA Private Key', title='Signing certificate for %s with root certificate' % key_alias)

# add root cert to server keystore
    root_root, root_node = path.split(root_path)
    root_alias, root_ext = path.splitext(root_node)
    sys_command = 'keytool -importcert -keystore %s -alias %s -file %s -noprompt -keypass %s -storepass %s' % (keystore_path, root_alias, root_path, password, password)
    _call(sys_command, ignore='Certificate was added to keystore', title='Adding root certificate to keystore for %s' % key_alias)

# add server cert to server keystore
    sys_command = 'keytool -importcert -keystore %s -alias %s -file %s -noprompt -keypass %s -storepass %s' % (keystore_path, key_alias, cert_path, password, password)
    _call(sys_command, ignore='Certificate reply was installed in keystore', title='Adding certificate for %s to keystore for %s' % (key_alias, key_alias))

# add root certificate to truststore
    if not truststore_copy:
        if path.exists(truststore_path):
            remove(truststore_path)
        sys_command = 'keytool -importcert -keystore %s -alias %s -file %s -noprompt -keypass %s -storepass %s' % (truststore_path, root_alias, root_path, password, password)
        _call(sys_command, ignore='Certificate was added to keystore', title='Generating truststore for root certificate')

# add server cert to truststore
    sys_command = 'keytool -importcert -keystore %s -alias %s -file %s -noprompt -keypass %s -storepass %s' % (truststore_path, key_alias, cert_path, password, password)
    _call(sys_command, ignore='Certificate was added to keystore', title='Adding certificate for %s to truststore' % key_alias)

# remove .srl files
    from os import listdir
    for file_name in listdir('./'):
        if file_name == '.srl':
            remove(file_name)
    for file_name in listdir(key_folder):
        file_alias, file_ext = path.splitext(file_name)
        if file_ext == '.srl':
            remove(path.join(key_folder, file_name))

    return True
130420
private static Object createKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
        Class keyGenClass = lookupKeyGenClass();
        Object keypair = ClassUtil.newInstance(keyGenClass, "RSA", "SHA1WithRSA");
        ClassUtil.applyMethod(keypair, "generate", 2048);
        return keypair;
    }
710131
def customPRF512(key, amac, smac, anonce, snonce):
    """"""
    A = b"Pairwise key expansion"
    B = b"".join(sorted([amac, smac]) + sorted([anonce, snonce]))

    blen = 64
    i = 0
    R = b''
    while i <= ((blen * 8 + 159) / 160):
        hmacsha1 = hmac.new(key, A + chb(0x00) + B + chb(i), hashlib.sha1)
        i += 1
        R = R + hmacsha1.digest()
    return R[:blen]
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