Search in sources :

Example 66 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project perun by CESNET.

the class MuPasswordManagerModule method makeCall.

/**
	 * Makes secure SSL connection to IS MU and perform required password manager action
	 *
	 * @param dataToPass XML request body
	 * @param requestId unique ID of a request
	 * @return InputStream response to be parsed
	 * @throws InternalErrorException
	 * @throws IOException
	 */
private InputStream makeCall(String dataToPass, int requestId) throws InternalErrorException, IOException {
    //prepare sslFactory
    SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    HttpsURLConnection.setDefaultSSLSocketFactory(factory);
    String uri = BeansUtils.getPropertyFromCustomConfiguration("pwchange.mu.is", "uri");
    String login = BeansUtils.getPropertyFromCustomConfiguration("pwchange.mu.is", "login");
    String password = BeansUtils.getPropertyFromCustomConfiguration("pwchange.mu.is", "password");
    URL myurl = new URL(uri);
    HttpURLConnection con = (HttpURLConnection) myurl.openConnection();
    //random number for purpose of creating boundaries in multipart
    String boundary = Long.toHexString(System.currentTimeMillis());
    // Prepare the basic auth, if the username and password was specified
    if (login != null && password != null) {
        String val = (new StringBuffer(login).append(":").append(password)).toString();
        Base64 encoder = new Base64();
        String base64Encoded = new String(encoder.encode(val.getBytes()));
        base64Encoded = base64Encoded.trim();
        String authorizationString = "Basic " + base64Encoded;
        con.setRequestProperty("Authorization", authorizationString);
    }
    con.setAllowUserInteraction(false);
    //set request header if is required (set in extSource xml)
    con.setDoOutput(true);
    con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    try (OutputStream output = con.getOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8), true)) {
        // Send param about return
        writer.append("--" + boundary).append(CRLF);
        writer.append("Content-Disposition: form-data; name=\"out\"").append(CRLF);
        writer.append(CRLF).append("xml").append(CRLF).flush();
        // Send xml file.
        writer.append("--" + boundary).append(CRLF);
        writer.append("Content-Disposition: form-data; name=\"xml\"; filename=\"perun-pwd-manager.xml\"").append(CRLF);
        // Text file itself must be saved in this charset!
        writer.append("Content-Type: text/xml; charset=" + StandardCharsets.UTF_8).append(CRLF);
        writer.append(CRLF).flush();
        writer.append(dataToPass);
        // Important before continuing with writer!
        output.flush();
        // CRLF is important! It indicates end of boundary.
        writer.append(CRLF).flush();
        // End of multipart/form-data.
        writer.append("--" + boundary + "--").append(CRLF).flush();
    }
    int responseCode = con.getResponseCode();
    if (responseCode == 200) {
        return con.getInputStream();
    }
    throw new InternalErrorException("Wrong response code while opening connection on uri '" + uri + "'. Response code: " + responseCode + ". Request ID: " + requestId);
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Base64(org.apache.commons.codec.binary.Base64) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) OutputStreamWriter(java.io.OutputStreamWriter) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) URL(java.net.URL) PrintWriter(java.io.PrintWriter)

Example 67 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project android_frameworks_base by ParanoidAndroid.

the class SSLSocketTest method getKeyManagers.

/**
     * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
     * for the result.
     */
private KeyManager[] getKeyManagers(String keys) throws Exception {
    byte[] bytes = new Base64().decode(keys.getBytes());
    InputStream inputStream = new ByteArrayInputStream(bytes);
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(inputStream, PASSWORD.toCharArray());
    inputStream.close();
    String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
    keyManagerFactory.init(keyStore, PASSWORD.toCharArray());
    return keyManagerFactory.getKeyManagers();
}
Also used : Base64(org.apache.commons.codec.binary.Base64) ByteArrayInputStream(java.io.ByteArrayInputStream) DataInputStream(java.io.DataInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) KeyStore(java.security.KeyStore) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Example 68 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project hadoop by apache.

the class TestCodec method writeSplitTestFile.

/** Write infLen bytes (deflated) to file in test dir using codec.
   * Records are of the form
   * <i><b64 rand><i+i><b64 rand>
   */
private static Path writeSplitTestFile(FileSystem fs, Random rand, CompressionCodec codec, long infLen) throws IOException {
    final int REC_SIZE = 1024;
    final Path wd = new Path(GenericTestUtils.getTempPath(codec.getClass().getSimpleName())).makeQualified(fs.getUri(), fs.getWorkingDirectory());
    final Path file = new Path(wd, "test" + codec.getDefaultExtension());
    final byte[] b = new byte[REC_SIZE];
    final Base64 b64 = new Base64(0, null);
    DataOutputStream fout = null;
    Compressor cmp = CodecPool.getCompressor(codec);
    try {
        fout = new DataOutputStream(codec.createOutputStream(fs.create(file, true), cmp));
        final DataOutputBuffer dob = new DataOutputBuffer(REC_SIZE * 4 / 3 + 4);
        int seq = 0;
        while (infLen > 0) {
            rand.nextBytes(b);
            // ensures rand printable, no LF
            final byte[] b64enc = b64.encode(b);
            dob.reset();
            dob.writeInt(seq);
            System.arraycopy(dob.getData(), 0, b64enc, 0, dob.getLength());
            fout.write(b64enc);
            fout.write('\n');
            ++seq;
            infLen -= b64enc.length;
        }
        LOG.info("Wrote " + seq + " records to " + file);
    } finally {
        IOUtils.cleanup(LOG, fout);
        CodecPool.returnCompressor(cmp);
    }
    return file;
}
Also used : Path(org.apache.hadoop.fs.Path) Base64(org.apache.commons.codec.binary.Base64) DataOutputStream(java.io.DataOutputStream) DataOutputBuffer(org.apache.hadoop.io.DataOutputBuffer) ZlibCompressor(org.apache.hadoop.io.compress.zlib.ZlibCompressor)

Example 69 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project hadoop by apache.

the class TestKerberosAuthenticationHandler method testRequestWithInvalidKerberosAuthorization.

public void testRequestWithInvalidKerberosAuthorization() throws Exception {
    String token = new Base64(0).encodeToString(new byte[] { 0, 1, 2 });
    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
    Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION)).thenReturn(KerberosAuthenticator.NEGOTIATE + token);
    try {
        handler.authenticate(request, response);
        Assert.fail();
    } catch (AuthenticationException ex) {
    // Expected
    } catch (Exception ex) {
        Assert.fail();
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Base64(org.apache.commons.codec.binary.Base64) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) ServletException(javax.servlet.ServletException)

Example 70 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project hadoop by apache.

the class TestLdapAuthenticationHandler method testRequestWithInvalidAuthorization.

@Test(timeout = 60000)
public void testRequestWithInvalidAuthorization() throws Exception {
    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
    final Base64 base64 = new Base64(0);
    String credentials = "bjones:invalidpassword";
    Mockito.when(request.getHeader(HttpConstants.AUTHORIZATION_HEADER)).thenReturn(base64.encodeToString(credentials.getBytes()));
    Assert.assertNull(handler.authenticate(request, response));
    Mockito.verify(response).setHeader(WWW_AUTHENTICATE, HttpConstants.BASIC);
    Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Base64(org.apache.commons.codec.binary.Base64) HttpServletResponse(javax.servlet.http.HttpServletResponse) Test(org.junit.Test)

Aggregations

Base64 (org.apache.commons.codec.binary.Base64)135 IOException (java.io.IOException)30 Test (org.junit.Test)29 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)12 InputStream (java.io.InputStream)11 HttpServletRequest (javax.servlet.http.HttpServletRequest)11 HttpServletResponse (javax.servlet.http.HttpServletResponse)11 Base64.encodeBase64String (org.apache.commons.codec.binary.Base64.encodeBase64String)11 ByteArrayInputStream (java.io.ByteArrayInputStream)10 HashMap (java.util.HashMap)10 SecretKeySpec (javax.crypto.spec.SecretKeySpec)9 MessageDigest (java.security.MessageDigest)8 File (java.io.File)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)7 URL (java.net.URL)7 Mac (javax.crypto.Mac)7 ServletException (javax.servlet.ServletException)7 X509Certificate (java.security.cert.X509Certificate)6 FileNotFoundException (java.io.FileNotFoundException)5 Signature (java.security.Signature)5