Search in sources :

Example 61 with Base64.encodeBase64String

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

the class TTextProtocolTest method setUp.

/**
 * Load a file containing a serialized thrift message in from disk
 * @throws IOException
 */
@Before
public void setUp() throws IOException {
    fileContents = Resources.toString(Resources.getResource(getClass(), "/com/twitter/common/thrift/text/TTextProtocol_TestData.txt"), Charsets.UTF_8);
    base64Encoder = new Base64();
}
Also used : Base64(org.apache.commons.codec.binary.Base64) Before(org.junit.Before)

Example 62 with Base64.encodeBase64String

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

the class KerberosRealm method authenticate.

/**
 * It enforces the the Kerberos SPNEGO authentication sequence returning an
 * {@link AuthenticationToken} only after the Kerberos SPNEGO sequence has
 * completed successfully.
 *
 * @param request  the HTTP client request.
 * @param response the HTTP client response.
 * @return an authentication token if the Kerberos SPNEGO sequence is complete
 * and valid, <code>null</code> if it is in progress (in this case the handler
 * handles the response to the client).
 * @throws IOException             thrown if an IO error occurred.
 * @throws AuthenticationException thrown if Kerberos SPNEGO sequence failed.
 */
public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response) throws IOException, AuthenticationException {
    AuthenticationToken token = null;
    String authorization = request.getHeader(KerberosAuthenticator.AUTHORIZATION);
    if (authorization == null || !authorization.startsWith(KerberosAuthenticator.NEGOTIATE)) {
        response.setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        if (authorization == null) {
            LOG.trace("SPNEGO starting for url: {}", request.getRequestURL());
        } else {
            LOG.warn("'" + KerberosAuthenticator.AUTHORIZATION + "' does not start with '" + KerberosAuthenticator.NEGOTIATE + "' :  {}", authorization);
        }
    } else {
        authorization = authorization.substring(KerberosAuthenticator.NEGOTIATE.length()).trim();
        final Base64 base64 = new Base64(0);
        final byte[] clientToken = base64.decode(authorization);
        try {
            final String serverPrincipal = KerberosUtil.getTokenServerName(clientToken);
            if (!serverPrincipal.startsWith("HTTP/")) {
                throw new IllegalArgumentException("Invalid server principal " + serverPrincipal + "decoded from client request");
            }
            token = Subject.doAs(serverSubject, (PrivilegedExceptionAction<AuthenticationToken>) () -> runWithPrincipal(serverPrincipal, clientToken, base64, response));
        } catch (PrivilegedActionException ex) {
            if (ex.getException() instanceof IOException) {
                throw (IOException) ex.getException();
            } else {
                throw new AuthenticationException(ex.getException());
            }
        } catch (Exception ex) {
            throw new AuthenticationException(ex);
        }
    }
    return token;
}
Also used : AuthenticationToken(org.apache.hadoop.security.authentication.server.AuthenticationToken) Base64(org.apache.commons.codec.binary.Base64) PrivilegedActionException(java.security.PrivilegedActionException) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) IOException(java.io.IOException) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) GSSException(org.ietf.jgss.GSSException) AuthorizationException(org.apache.shiro.authz.AuthorizationException)

Example 63 with Base64.encodeBase64String

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

the class ExtSourceISMU method querySource.

protected List<Map<String, String>> querySource(String query, String searchString, int maxResults) {
    try {
        HttpURLConnection http = getHttpConnection(query, searchString);
        // Prepare the basic auth, if the username and password was specified
        if (getAttributes().get("user") != null && getAttributes().get("password") != null) {
            String val = getAttributes().get("user") + ":" + getAttributes().get("password");
            Base64 encoder = new Base64();
            String base64Encoded = new String(encoder.encode(val.getBytes()));
            // Java bug : http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459815
            base64Encoded = base64Encoded.trim();
            String authorizationString = "Basic " + base64Encoded;
            http.setRequestProperty("Authorization", authorizationString);
        }
        http.setAllowUserInteraction(false);
        http.setRequestMethod("GET");
        http.connect();
        InputStream is = http.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;
        List<Map<String, String>> subjects = new ArrayList<>();
        while ((line = reader.readLine()) != null) {
            Map<String, String> map = new HashMap<>();
            // Each line looks like:
            // UCO  ;;          ;"title before. title before. firstName lastName, title after
            // 39700;;“RNDr. Michal Procházka";Procházka;Michal;
            // Parse the line
            String[] entries = line.split(";");
            // Get the UCO
            if (entries[0].equals("")) {
                // skip this subject, because it doesn't have UCO defined
                continue;
            }
            String login = entries[0];
            if (login.isEmpty())
                login = null;
            map.put("login", login);
            String name = entries[2];
            // Remove "" from name
            name = name.replaceAll("^\"|\"$", "");
            // entries[3] contains name of the user, so parse it to get titleBefore, firstName, lastName and titleAfter in separate fields
            map.putAll(Utils.parseCommonName(name));
            // Add additional userExtSource for MU IdP with loa 2
            map.put(ExtSourcesManagerImpl.USEREXTSOURCEMAPPING + "1", "https://idp2.ics.muni.cz/idp/shibboleth|cz.metacentrum.perun.core.impl.ExtSourceIdp|" + login + "@muni.cz|2");
            subjects.add(map);
        }
        return subjects;
    } catch (Exception e) {
        throw new InternalErrorException(e);
    }
}
Also used : Base64(org.apache.commons.codec.binary.Base64) InputStreamReader(java.io.InputStreamReader) HashMap(java.util.HashMap) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) ExtSourceUnsupportedOperationException(cz.metacentrum.perun.core.api.exceptions.ExtSourceUnsupportedOperationException) IOException(java.io.IOException) HttpURLConnection(java.net.HttpURLConnection) BufferedReader(java.io.BufferedReader) HashMap(java.util.HashMap) Map(java.util.Map)

Example 64 with Base64.encodeBase64String

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

the class ISServiceCallerImpl 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
 */
public InputStream makeCall(String dataToPass, int requestId) throws IOException {
    // prepare sslFactory
    SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    HttpsURLConnection.setDefaultSSLSocketFactory(factory);
    // we want to log what we send
    StringBuilder logBuilder = new StringBuilder();
    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 = login + ":" + password;
        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);
    log.trace("[IS Request {}] Content-Type: multipart/form-data; boundary={}", requestId, 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);
        logBuilder.append("--" + boundary).append(CRLF);
        writer.append("Content-Disposition: form-data; name=\"out\"").append(CRLF);
        logBuilder.append("Content-Disposition: form-data; name=\"out\"").append(CRLF);
        writer.append(CRLF).append("xml").append(CRLF).flush();
        logBuilder.append(CRLF).append("xml").append(CRLF);
        // Send xml file.
        writer.append("--" + boundary).append(CRLF);
        logBuilder.append("--" + boundary).append(CRLF);
        writer.append("Content-Disposition: form-data; name=\"xml\"; filename=\"perun-pwd-manager.xml\"").append(CRLF);
        logBuilder.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);
        logBuilder.append("Content-Type: text/xml; charset=" + StandardCharsets.UTF_8).append(CRLF);
        writer.append(CRLF).flush();
        logBuilder.append(CRLF);
        writer.append(dataToPass);
        logBuilder.append("\n--File content is logged separately--\n");
        // Important before continuing with writer!
        output.flush();
        // CRLF is important! It indicates end of boundary.
        writer.append(CRLF).flush();
        logBuilder.append(CRLF);
        // End of multipart/form-data.
        writer.append("--" + boundary + "--").append(CRLF).flush();
        logBuilder.append("--" + boundary + "--").append(CRLF);
        log.trace("[IS Request {}] {}", requestId, logBuilder.toString());
    }
    int responseCode = con.getResponseCode();
    if (responseCode == 200) {
        return con.getInputStream();
    } else {
        String response = null;
        try {
            response = convertStreamToString(con.getErrorStream(), StandardCharsets.UTF_8);
        } catch (IOException ex) {
            log.error("Unable to convert InputStream to String.", ex);
        }
        log.trace("[IS Request {}] Response: {}", requestId, response);
    }
    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) IOException(java.io.IOException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) URL(java.net.URL) PrintWriter(java.io.PrintWriter)

Example 65 with Base64.encodeBase64String

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

the class XAdESSignatureProperties method calculateDigest.

protected String calculateDigest(String algorithm, byte[] bytes) throws NoSuchAlgorithmException, CertificateEncodingException {
    MessageDigest digest = MessageDigest.getInstance(algorithm);
    byte[] digestBytes = digest.digest(bytes);
    return new Base64().encodeAsString(digestBytes);
}
Also used : Base64(org.apache.commons.codec.binary.Base64) MessageDigest(java.security.MessageDigest)

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