Formats the raws credentials to store in the cookie.

@param challenge
The challenge response to format.
@return The raw credentials.
@throws GeneralSecurityException
If the credentials cannot be encrypted.
429824
protected String formatCredentials(final ChallengeResponse challenge) throws GeneralSecurityException
    {
        // Data buffer
        final StringBuffer sb = new StringBuffer();
        
        // Indexes buffer
        final StringBuffer isb = new StringBuffer();
        final String timeIssued = Long.toString(System.currentTimeMillis());
        int i = timeIssued.length();
        sb.append(timeIssued);
        
        isb.append(i);
        
        final String identifier = challenge.getIdentifier();
        sb.append('/');
        sb.append(identifier);
        
        i += identifier.length() + 1;
        isb.append(',').append(i);
        
        sb.append('/');
        sb.append(challenge.getSecret());
        
        // Store indexes at the end of the string
        sb.append('/');
        sb.append(isb);
        
        return Base64.encode(
                CryptoUtils.encrypt(this.getEncryptAlgorithm(), this.getEncryptSecretKey(), sb.toString()), false);
    }
1316797
private byte[] validateChallenge(byte[] nonce, byte[] encryptedChallenge)
    throws GeneralSecurityException {

    byte[] challenge = decrypt(encryptedChallenge);
    checkSubArray(appId, challenge, 0);
    checkSubArray(nonce, challenge, appId.length);
    return Arrays.copyOfRange(challenge, appId.length + nonce.length, challenge.length);
  }
860143
public byte[] getUnicodeHash( byte[] challenge ) {
        if( hashesExternal ) {
            return unicodeHash;
        }
        switch (LM_COMPATIBILITY) {
        case 0:
        case 1:
        case 2:
            return getNTLMResponse( password, challenge );
        case 3:
        case 4:
        case 5:
            /*
            if( clientChallenge == null ) {
                clientChallenge = new byte[8];
                RANDOM.nextBytes( clientChallenge );
            }
            return getNTLMv2Response(domain, username, password, null,
                    challenge, clientChallenge);
            */
            return new byte[0];
        default:
            return getNTLMResponse( password, challenge );
        }
    }
480515
public String encrypt(String message) throws GeneralSecurityException {
		byte[] bytes = encryptor.encrypt(message.getBytes());
		return Base64.getEncoder().encodeToString(bytes);
	}
689019
private byte[] getSignature(final Manifest forManifest) throws IOException, GeneralSecurityException {

		final ByteArrayOutputStream bos = new ByteArrayOutputStream();
		final Manifest signatureFile    = new Manifest();
		final Attributes main           = signatureFile.getMainAttributes();
		final MessageDigest md          = MessageDigest.getInstance("SHA1");
		final PrintStream print         = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true, "UTF-8");

		main.putValue("Signature-Version", "1.0");

		// Digest of the entire manifest
		forManifest.write(print);
		print.flush();

		main.putValue("SHA1-Digest-Manifest", new String(Base64.encode(md.digest()), "ASCII"));

		final Map<String, Attributes> entries = forManifest.getEntries();

		for (Map.Entry<String, Attributes> entry : entries.entrySet()) {

			// Digest of the manifest stanza for this entry.
			print.print("Name: " + entry.getKey() + "\r\n");

			for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) {
				print.print(att.getKey() + ": " + att.getValue() + "\r\n");
			}

			print.print("\r\n");
			print.flush();

			final Attributes sfAttr = new Attributes();
			sfAttr.putValue("SHA1-Digest", new String(Base64.encode(md.digest()), "ASCII"));

			signatureFile.getEntries().put(entry.getKey(), sfAttr);
		}

		signatureFile.write(bos);

		return bos.toByteArray();
	}
967681
public void encrypt(byte[] password) throws GeneralSecurityException {

        if (isEncrypted()) {
            return;
        }

        if (this.encAlg == null) {
            setEncryptionAlgorithm("DES-EDE3-CBC");
        }

        if (this.ivData == null) {
            generateIV();
        }

        Key key = getSecretKey(password, this.initializationVector.getIV());

        Cipher cipher = getCipher();
        cipher.init(Cipher.ENCRYPT_MODE, key, this.initializationVector);

        /* encrypt the raw PKCS11 */

        this.keyData = cipher.doFinal(getEncoded(this.intKey));
        this.isEncrypted = true;
        this.encodedKey = null;
    }
1181665
public Credential generateCredential() throws OAuthException {
    GoogleCredential credential = Strings.isNullOrEmpty(this.jsonKeyFilePath)
        ? generateCredentialFromClientSecrets()
        : generateCredentialFromKeyFile();
    try {
      if (!oAuth2Helper.callRefreshToken(credential)) {
        throw new OAuthException(
            "Credential could not be refreshed. A newly generated refresh token or "
            + "secret key may be required.");
      }
    } catch (IOException e) {
      throw new OAuthException("Credential could not be refreshed.", e);
    }
    return credential;
  }
1067192
public Credential getCredentialFromMetadataServiceAccount()
      throws IOException, GeneralSecurityException {
    logger.atFine().log("getCredentialFromMetadataServiceAccount()");
    Credential cred =
        new ComputeCredentialWithRetry(
            new ComputeCredential.Builder(getStaticHttpTransport(), JSON_FACTORY)
                .setRequestInitializer(new CredentialHttpRetryInitializer()));
    try {
      cred.refreshToken();
    } catch (IOException e) {
      throw new IOException(
          "Error getting access token from metadata server at: " + cred.getTokenServerEncodedUrl(),
          e);
    }
    return cred;
  }
165132
public void decrypt(byte[] password) throws GeneralSecurityException {
        if (!isEncrypted()) {
            return;
        }

        byte[] enc = Base64.decode(this.encodedKey);

        SecretKeySpec key = getSecretKey(password, this.initializationVector.getIV());

        Cipher cipher = getCipher();
        cipher.init(Cipher.DECRYPT_MODE, key, this.initializationVector);
        enc = cipher.doFinal(enc);

        this.intKey = getKey(this.keyAlg, enc);
        this.keyData = enc;
        this.isEncrypted = false;
        this.encodedKey = null;
    }
801287
private function _generateResponse($challenge, $password)
    {
        // XXX: as I don't support mandatory extension, I would fail on them.
        // And I simply ignore any optional extension.
        $matches = [];
        $server_message_regexp = "#^r=([\x21-\x2B\x2D-\x7E]+),s=((?:[A-Za-z0-9/+]{4})*(?:[A-Za-z0-9]{3}=|[A-Xa-z0-9]{2}==)?),i=([0-9]*)(,[A-Za-z]=[^,])*$#";
        if (!isset($this->cnonce, $this->gs2_header)
            || !preg_match($server_message_regexp, $challenge, $matches))
        {
            return false;
        }
        $nonce = $matches[1];
        $salt = base64_decode($matches[2]);
        if (!$salt)
        {
            // Invalid Base64.
            return false;
        }
        $i = intval($matches[3]);

        $cnonce = substr($nonce, 0, strlen($this->cnonce));
        if ($cnonce <> $this->cnonce)
        {
            // Invalid challenge! Are we under attack?
            return false;
        }

        $channel_binding = 'c=' . base64_encode($this->gs2_header); // TODO: support channel binding.
        $final_message = $channel_binding . ',r=' . $nonce; // XXX: no extension.

        // TODO: $password = $this->normalize($password); // SASLprep profile of stringprep.
        $saltedPassword = $this->hi($password, $salt, $i);
        $this->saltedPassword = $saltedPassword;
        $clientKey = call_user_func($this->hmac, $saltedPassword, "Client Key", TRUE);
        $storedKey = call_user_func($this->hash, $clientKey, TRUE);
        $authMessage = $this->first_message_bare . ',' . $challenge . ',' . $final_message;
        $this->authMessage = $authMessage;
        $clientSignature = call_user_func($this->hmac, $storedKey, $authMessage, TRUE);
        $clientProof = $clientKey ^ $clientSignature;
        $proof = ',p=' . base64_encode($clientProof);

        return $final_message . $proof;
    }
62785
protected LoginContext getLoginContext(final UsernamePasswordCredential credential) throws GeneralSecurityException {
        val callbackHandler = new UsernamePasswordCallbackHandler(credential.getUsername(), credential.getPassword());
        if (this.loginConfigurationFile != null && StringUtils.isNotBlank(this.loginConfigType)
            && this.loginConfigurationFile.exists() && this.loginConfigurationFile.canRead()) {
            final Configuration.Parameters parameters = new URIParameter(loginConfigurationFile.toURI());
            val loginConfig = Configuration.getInstance(this.loginConfigType, parameters);
            return new LoginContext(this.realm, null, callbackHandler, loginConfig);
        }
        return new LoginContext(this.realm, callbackHandler);
    }
745782
static public byte[] getPreNTLMResponse( String password, byte[] challenge ) {
        byte[] p14 = new byte[14];
        byte[] p21 = new byte[21];
        byte[] p24 = new byte[24];
        byte[] passwordBytes;
        try {
            passwordBytes = password.toUpperCase().getBytes( ServerMessageBlock.OEM_ENCODING );
        } catch( UnsupportedEncodingException uee ) {
            throw new RuntimeException("Try setting jcifs.smb1.encoding=US-ASCII", uee);
        }
        int passwordLength = passwordBytes.length;

        // Only encrypt the first 14 bytes of the password for Pre 0.12 NT LM
        if( passwordLength > 14) {
            passwordLength = 14;
        }
        System.arraycopy( passwordBytes, 0, p14, 0, passwordLength );
        E( p14, S8, p21);
        E( p21, challenge, p24);
        return p24;
    }
442572
public static SSLContext buildSSLContext(HttpClientConfig config) throws IOException, GeneralSecurityException {

    KeyManagerFactory kmf = null;
    if (isSslKeyManagerEnabled(config)) {
      kmf = getKeyManagerFactory(config.getKeyStorePath(),
          new StoreProperties(config.getKeyStorePassword(), config.getKeyManagerType(),
              config.getKeyStoreType(), config.getKeyStoreProvider()));
    }
    TrustManagerFactory tmf = null;
    if (isSslTrustStoreEnbaled(config)) {
      tmf = getTrustManagerFactory(config.getTrustStorePath(), new StoreProperties(config.getTrustStorePassword(),
          config.getTrustManagerType(), config.getTrustStoreType(), config.getTrustStoreProvider()));
    }

    SSLContext sslContext = SSLContext.getInstance(config.getSslContextType());
    sslContext.init(kmf != null ? kmf.getKeyManagers() : null,
        tmf != null ? tmf.getTrustManagers() : null,
        null);

    return sslContext;
  }
668637
private AWSCredentials credentials(JsonNode credentialsJson) {
        String accessKeyId = getText(credentialsJson, "AccessKeyId");
        String secretAccessKey = getText(credentialsJson, "SecretAccessKey");
        String sessionToken = getText(credentialsJson, "SessionToken");

        ValidationUtils.assertStringNotEmpty(accessKeyId, "AccessKeyId");
        ValidationUtils.assertStringNotEmpty(accessKeyId, "SecretAccessKey");

        if (sessionToken != null) {
            return new BasicSessionCredentials(accessKeyId, secretAccessKey, sessionToken);
        } else {
            return new BasicAWSCredentials(accessKeyId, secretAccessKey);
        }
    }
704195
public char[] getPublicKey() throws GeneralSecurityException, IOException {
        if (publicKey != null) {
            return publicKey;
        }

        KeyPair keys = getKeyPair();
        EdDSAPublicKey pubKey = (EdDSAPublicKey) keys.getPublic();
        byte[] pubBytes = pubKey.getAbyte();

        return encode(this.type, pubBytes);
    }
962440
static public byte[] getPreNTLMResponse ( CIFSContext tc, String password, byte[] challenge ) throws GeneralSecurityException {
        byte[] p14 = new byte[14];
        byte[] p21 = new byte[21];
        byte[] p24 = new byte[24];
        byte[] passwordBytes = Strings.getOEMBytes(password, tc.getConfig());
        int passwordLength = passwordBytes.length;

        // Only encrypt the first 14 bytes of the password for Pre 0.12 NT LM
        if ( passwordLength > 14 ) {
            passwordLength = 14;
        }
        System.arraycopy(passwordBytes, 0, p14, 0, passwordLength);
        NtlmUtil.E(p14, NtlmUtil.S8, p21);
        NtlmUtil.E(p21, challenge, p24);
        return p24;
    }
340637
public CredentialResolver build() throws IOException, GeneralSecurityException {
        final KeyStore ks = KeyStore.getInstance(type);
        try (InputStream is = open()) {
            ks.load(is, password != null ? password.toCharArray() : null);
        }
        return new KeyStoreCredentialResolver(ks, keyPasswords);
    }