Used during setup to get the certification from the keystore and encrypt the auth_value with
the private key
13796
public void setCertificate() throws KeyStoreException, IOException, NoSuchAlgorithmException,
                    CertificateException, NoSuchPaddingException, InvalidKeyException,
                    IllegalBlockSizeException, BadPaddingException, UnrecoverableEntryException {
        KeyStore store = KeyStore.getInstance(this.keystore_type);
        InputStream inputStream=Thread.currentThread().getContextClassLoader().getResourceAsStream(this.keystore_path);
        if(inputStream == null)
            inputStream=new FileInputStream(this.keystore_path);
        store.load(inputStream, this.keystore_password);

        this.cipher = Cipher.getInstance(this.cipher_type);
        this.certificate = (X509Certificate) store.getCertificate(this.cert_alias);

        log.debug("certificate = " + this.certificate.toString());

        this.cipher.init(Cipher.ENCRYPT_MODE, this.certificate);
        this.encryptedToken = this.cipher.doFinal(this.auth_value.getBytes());

        KeyStore.PrivateKeyEntry privateKey = (KeyStore.PrivateKeyEntry) store.getEntry(
                        this.cert_alias, new KeyStore.PasswordProtection(this.cert_password));
        this.certPrivateKey = privateKey.getPrivateKey();

        this.valueSet=true;
    }
934252
def load_pem(cls, private_key, password=None):
        
        # TODO(sam): try to break this in tests
        maybe_path = normpath(private_key)
        if os.path.isfile(maybe_path):
            with open(maybe_path, 'rb') as pkf:
                private_key = pkf.read()
        if not isinstance(private_key, six.binary_type):
            private_key = private_key.encode('utf-8')

        pkey = serialization.load_pem_private_key(
            private_key,
            password=password,
            backend=crypto_backends.default_backend())
        return cls(pkey)
1080196
function loadKeyPair (pub, prv, use) {
  var pubPEM, prvPEM, pubJWK

  try {
    pubPEM = fs.readFileSync(pub).toString('ascii')
  } catch (e) {
    throw new Error('Unable to read the public key from ' + pub)
  }

  try {
    prvPEM = fs.readFileSync(prv).toString('ascii')
  } catch (e) {
    throw new Error('Unable to read the private key from ' + pub)
  }

  try {
    pubJWK = pemjwk.pem2jwk(pubPEM)
  } catch (e) {
    throw new Error('Unable to convert the public key ' + pub + ' to a JWK')
  }

  return {
    pem: {
      pub: pubPEM,
      prv: prvPEM
    },
    jwk: {
      pub: {
        kty: pubJWK.kty,
        use: use,
        alg: 'RS256',
        n: pubJWK.n,
        e: pubJWK.e
      }
    }
  }
}
35208
def load_key(self, key_path, password):
        

        try:
            return paramiko.RSAKey.from_private_key_file(key_path)
        except PasswordRequiredException as ex:
            return paramiko.RSAKey.from_private_key_file(key_path,
                                                         password=password)
759373
def load(self):
        """"""

        private = self.is_private()
        with open_tls_file(self.file_path, 'r', private=private) as fh:
            if private:
                self.x509 = crypto.load_privatekey(self.encoding, fh.read())
            else:
                self.x509 = crypto.load_certificate(self.encoding, fh.read())
            return self.x509
1252910
def get_key_auth_cb(key_filepath):
    """"""

    def auth_cb(ssh):
        key = ssh_pki_import_privkey_file(key_filepath)
        ssh.userauth_publickey(key)

    return auth_cb
256342
def _use_private_key(
            self,
            client_certchain_file: str,
            client_key_file: str,
            client_key_type: OpenSslFileTypeEnum,
            client_key_password: str
    ) -> None:
        
        # Ensure the files exist
        with open(client_certchain_file):
            pass
        with open(client_key_file):
            pass

        self._ssl_ctx.use_certificate_chain_file(client_certchain_file)
        self._ssl_ctx.set_private_key_password(client_key_password)
        try:
            self._ssl_ctx.use_PrivateKey_file(client_key_file, client_key_type.value)
        except OpenSSLError as e:
            if 'bad password read' in str(e) or 'bad decrypt' in str(e):
                raise ValueError('Invalid Private Key')
            else:
                raise

        self._ssl_ctx.check_private_key()
712419
protected void createKeystore() {

		java.security.cert.Certificate signingCert = null;
		PrivateKey  caPrivKey  = null;

		if(_caCert == null || _caPrivKey == null)
		{
			try
			{
				log.debug("Keystore or signing cert & keypair not found.  Generating...");

				KeyPair caKeypair = getRSAKeyPair();
				caPrivKey = caKeypair.getPrivate();
				signingCert = CertificateCreator.createTypicalMasterCert(caKeypair);

				log.debug("Done generating signing cert");
				log.debug(signingCert);

				_ks.load(null, _keystorepass);

				_ks.setCertificateEntry(_caCertAlias, signingCert);
				_ks.setKeyEntry(_caPrivKeyAlias, caPrivKey, _keypassword, new java.security.cert.Certificate[] {signingCert});

				File caKsFile = new File(root, _caPrivateKeystore);

				OutputStream os = new FileOutputStream(caKsFile);
				_ks.store(os, _keystorepass);

				log.debug("Wrote JKS keystore to: " +
						caKsFile.getAbsolutePath());

				// also export a .cer that can be imported as a trusted root
				// to disable all warning dialogs for interception

				File signingCertFile = new File(root, EXPORTED_CERT_NAME);

				FileOutputStream cerOut = new FileOutputStream(signingCertFile);

				byte[] buf = signingCert.getEncoded();

				log.debug("Wrote signing cert to: " + signingCertFile.getAbsolutePath());

				cerOut.write(buf);
				cerOut.flush();
				cerOut.close();

				_caCert = (X509Certificate)signingCert;
				_caPrivKey  = caPrivKey;
			}
			catch(Exception e)
			{
				log.error("Fatal error creating/storing keystore or signing cert.", e);
				throw new Error(e);
			}
		}
		else
		{
			log.debug("Successfully loaded keystore.");
			log.debug(_caCert);

		}

	}
696052
def decrypt_key(key, password):
    
    private = serialization.load_pem_private_key(key, password=password, backend=default_backend())
    return private.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption())
837600
public synchronized PrivateKey getPrivateKeyForLocalCert(final X509Certificate cert)
	throws CertificateEncodingException, KeyStoreException, UnrecoverableKeyException,
	NoSuchAlgorithmException
	{
		String thumbprint = ThumbprintUtil.getThumbprint(cert);

		return (PrivateKey)_ks.getKey(thumbprint, _keypassword);
	}
1190378
private SSLContext getSSLContext(String truststorePath,
                                     String truststorePassword,
                                     String keystorePath, 
                                     String keystorePassword) throws Exception {

        FileInputStream tsf = new FileInputStream(truststorePath);
        KeyStore ts = KeyStore.getInstance("JKS");
        ts.load(tsf, truststorePassword.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ts);

        FileInputStream ksf = new FileInputStream(keystorePath);
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(ksf, keystorePassword.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, keystorePassword.toCharArray());

        SSLContext ctx = SSLContext.getInstance("SSL");
        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
        return ctx;
    }
1026018
def decrypt(self, pkey, cert, flags=0):
        
        if not pkey.cansign:
            raise ValueError("Specified keypair has no private part")
        if pkey != cert.pubkey:
            raise ValueError("Certificate doesn't match private key")
        bio = Membio()
        res = libcrypto.CMS_decrypt(self.ptr, pkey.key, cert.cert, None,
                                    bio.bio, flags)
        if res <= 0:
            raise CMSError("decrypting CMS")
        return str(bio)
318647
def encrypt(self, binary, use_sign=True):
        
        token = rsa.encrypt(binary, self.his_pubkey)  # encrypt it
        if use_sign:
            self.sign = rsa.sign(binary, self.my_privkey, "SHA-1")  # sign it
        return token
520074
def load_pkcs12(self, key):
        
        self.x509 = key.get_certificate().to_cryptography()
        self.public_key = key.get_certificate().to_cryptography().public_key()
        self.private_key = key.get_privatekey().to_cryptography_key()
620753
def load_private_key(self, priv_key):
        """"""
        with open(priv_key) as fd:
            self._private_key = paramiko.RSAKey.from_private_key(fd)
925167
def _get_private_key_obj(private_key, passphrase=None):
    '''
    
    '''
    private_key = _text_or_file(private_key)
    private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
    rsaprivkey = M2Crypto.RSA.load_key_string(
        private_key, callback=_passphrase_callback(passphrase))
    evpprivkey = M2Crypto.EVP.PKey()
    evpprivkey.assign_rsa(rsaprivkey)
    return evpprivkey
3958
def rsa_sha1_signature
      private_key = OpenSSL::PKey::RSA.new(@attributes['consumer_secret'])
      Base64.encode64(private_key.sign(OpenSSL::Digest::SHA1.new, signature_base)).gsub(/\n/, '')
    end