Example usage for org.apache.commons.codec.binary Base64 Base64

List of usage examples for org.apache.commons.codec.binary Base64 Base64

Introduction

In this page you can find the example usage for org.apache.commons.codec.binary Base64 Base64.

Prototype

public Base64(final int lineLength) 

Source Link

Document

Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.

Usage

From source file:com.buddycloud.mediaserver.web.MediaServerResource.java

protected String decodeAuth(String auth) {
    Base64 decoder = new Base64(true);

    return new String(decoder.decode(auth.getBytes()));
}

From source file:com.netscape.certsrv.client.PKIClient.java

public byte[] downloadCACertChain(String uri, String servletPath)
        throws ParserConfigurationException, SAXException, IOException {

    URL url = new URL(uri + servletPath);

    if (verbose)//  w  w  w  . j a va2 s  . co m
        System.out.println("Retrieving CA certificate chain from " + url + ".");

    DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();

    Document document = documentBuilder.parse(url.openStream());
    NodeList list = document.getElementsByTagName("ChainBase64");
    Element element = (Element) list.item(0);

    String encodedChain = element.getTextContent();
    byte[] bytes = Utils.base64decode(encodedChain);

    if (verbose) {
        System.out.println("-----BEGIN PKCS7-----");
        System.out.print(new Base64(64).encodeToString(bytes));
        System.out.println("-----END PKCS7-----");
    }

    return bytes;
}

From source file:com.netcrest.pado.internal.security.AESCipher.java

private static byte[] getUserPrivateKey() throws IOException {
    byte[] privateKey = null;

    String estr;/*from w  w w .  j  av  a2s  .c om*/
    String certificateFilePath = PadoUtil.getProperty(Constants.PROP_SECURITY_AES_USER_CERTIFICATE,
            "security/user.cer");
    if (certificateFilePath.startsWith("/") == false) {

        // TODO: Make server files relative to PADO_HOME also.
        if (PadoUtil.isPureClient()) {
            String padoHome = PadoUtil.getProperty(Constants.PROP_HOME_DIR);
            certificateFilePath = padoHome + "/" + certificateFilePath;
        }
    }
    File file = new File(certificateFilePath);
    if (file.exists() == false) {
        FileWriter writer = null;
        try {
            privateKey = AESCipher.getPrivateKey();
            Base64 base64 = new Base64(0); // no line breaks
            estr = base64.encodeToString(privateKey);
            writer = new FileWriter(file);
            writer.write(estr);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    } else {
        FileReader reader = null;
        try {
            reader = new FileReader(file);
            StringBuffer buffer = new StringBuffer(2048);
            int c;
            while ((c = reader.read()) != -1) {
                buffer.append((char) c);
            }
            estr = buffer.toString();
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }
    Base64 base64 = new Base64(0); // no line breaks
    privateKey = base64.decode(estr);
    return privateKey;
}

From source file:io.druid.security.kerberos.DruidKerberosAuthenticationHandler.java

@Override
public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response)
        throws IOException, AuthenticationException {
    AuthenticationToken token = null;/*  w  w w . jav a2 s . c  om*/
    String authorization = request
            .getHeader(org.apache.hadoop.security.authentication.client.KerberosAuthenticator.AUTHORIZATION);

    if (authorization == null || !authorization
            .startsWith(org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE)) {
        return null;
    } else {
        authorization = authorization.substring(
                org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE.length())
                .trim();
        final Base64 base64 = new Base64(0);
        final byte[] clientToken = base64.decode(authorization);
        final String serverName = request.getServerName();
        try {
            token = Subject.doAs(serverSubject, new PrivilegedExceptionAction<AuthenticationToken>() {

                @Override
                public AuthenticationToken run() throws Exception {
                    AuthenticationToken token = null;
                    GSSContext gssContext = null;
                    GSSCredential gssCreds = null;
                    try {
                        gssCreds = gssManager.createCredential(
                                gssManager.createName(KerberosUtil.getServicePrincipal("HTTP", serverName),
                                        KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL")),
                                GSSCredential.INDEFINITE_LIFETIME,
                                new Oid[] { KerberosUtil.getOidInstance("GSS_SPNEGO_MECH_OID"),
                                        KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID") },
                                GSSCredential.ACCEPT_ONLY);
                        gssContext = gssManager.createContext(gssCreds);
                        byte[] serverToken = gssContext.acceptSecContext(clientToken, 0, clientToken.length);
                        if (serverToken != null && serverToken.length > 0) {
                            String authenticate = base64.encodeToString(serverToken);
                            response.setHeader(
                                    org.apache.hadoop.security.authentication.client.KerberosAuthenticator.WWW_AUTHENTICATE,
                                    org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE
                                            + " " + authenticate);
                        }
                        if (!gssContext.isEstablished()) {
                            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                            log.trace("SPNEGO in progress");
                        } else {
                            String clientPrincipal = gssContext.getSrcName().toString();
                            KerberosName kerberosName = new KerberosName(clientPrincipal);
                            String userName = kerberosName.getShortName();
                            token = new AuthenticationToken(userName, clientPrincipal, getType());
                            response.setStatus(HttpServletResponse.SC_OK);
                            log.trace("SPNEGO completed for principal [%s]", clientPrincipal);
                        }
                    } finally {
                        if (gssContext != null) {
                            gssContext.dispose();
                        }
                        if (gssCreds != null) {
                            gssCreds.dispose();
                        }
                    }
                    return token;
                }
            });
        } catch (PrivilegedActionException ex) {
            if (ex.getException() instanceof IOException) {
                throw (IOException) ex.getException();
            } else {
                throw new AuthenticationException(ex.getException());
            }
        }
    }
    return token;
}

From source file:com.flipkart.fdp.migration.distcp.security.KerberosAuthenticator2.java

/**
 * Performs SPNEGO authentication against the specified URL.
 * <p/>//ww  w .ja  va  2 s  . c o m
 * If a token is given it does a NOP and returns the given token.
 * <p/>
 * If no token is given, it will perform the SPNEGO authentication sequence
 * using an HTTP <code>OPTIONS</code> request.
 * 
 * @param url
 *            the URl to authenticate against.
 * @param token
 *            the authentication token being used for the user.
 * 
 * @throws IOException
 *             if an IO error occurred.
 * @throws AuthenticationException
 *             if an authentication error occurred.
 */
public void authenticate(URL url, AuthenticatedURL.Token token) throws IOException, AuthenticationException {
    if (!token.isSet()) {
        this.url = url;
        base64 = new Base64(0);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(AUTH_HTTP_METHOD);
        conn.connect();
        if (isNegotiate()) {
            doSpnegoSequence(token);
        } else {
            getFallBackAuthenticator().authenticate(url, token);
        }
    }
}

From source file:com.amazon.advertising.api.sample.SignedRequestsHelper.java

/**
 * Compute the HMAC./* w  w  w  . ja va2  s. c om*/
 *  
 * @param stringToSign  String to compute the HMAC over.
 * @return              base64-encoded hmac value.
 */
private String hmac(String stringToSign) {
    String signature = null;
    byte[] data;
    byte[] rawHmac;
    try {
        data = stringToSign.getBytes(UTF8_CHARSET);
        rawHmac = mac.doFinal(data);
        Base64 encoder = new Base64(0);
        signature = new String(encoder.encode(rawHmac));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(UTF8_CHARSET + " is unsupported!", e);
    }
    return signature;
}

From source file:de.zib.scalaris.examples.wikipedia.data.Revision.java

/**
 * @param text/*w w w  .j  a  va2  s .  c o  m*/
 *            the base64-encoded packed text to set
 */
public void setB64pText(String text) {
    Base64 b64 = new Base64(0);
    this.pText = b64.decode(text);
}

From source file:com.cloudera.alfredo.server.TestKerberosAuthenticationHandler.java

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 {//w ww  .j  a  v  a 2  s .  co m
        handler.authenticate(request, response);
        fail();
    } catch (AuthenticationException ex) {

    } catch (Exception ex) {
        fail();
    }
}

From source file:mx.bigdata.sat.cfdi.TFDv1_v32.java

String getSignature(PrivateKey key) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initSign(key);//  w ww. j av  a2  s .c  o m
    sig.update(bytes);
    byte[] signed = sig.sign();
    Base64 b64 = new Base64(-1);
    return b64.encodeToString(signed);
}

From source file:com.lucidworks.security.authentication.client.KerberosAuthenticator.java

/**
 * Performs SPNEGO authentication against the specified URL.
 * <p/>//from  w  w w .ja va 2 s . c  o m
 * If a token is given it does a NOP and returns the given token.
 * <p/>
 * If no token is given, it will perform the SPNEGO authentication sequence using an
 * HTTP <code>OPTIONS</code> request.
 *
 * @param url the URl to authenticate against.
 * @param token the authentication token being used for the user.
 *
 * @throws IOException if an IO error occurred.
 * @throws AuthenticationException if an authentication error occurred.
 */
@Override
public void authenticate(URL url, AuthenticatedURL.Token token) throws IOException, AuthenticationException {
    if (!token.isSet()) {
        this.url = url;
        base64 = new Base64(0);
        conn = (HttpURLConnection) url.openConnection();
        if (connConfigurator != null) {
            conn = connConfigurator.configure(conn);
        }
        conn.setRequestMethod(AUTH_HTTP_METHOD);
        conn.connect();

        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            LOG.debug("JDK performed authentication on our behalf.");
            // If the JDK already did the SPNEGO back-and-forth for
            // us, just pull out the token.
            AuthenticatedURL.extractToken(conn, token);
            return;
        } else if (isNegotiate()) {
            LOG.debug("Performing our own SPNEGO sequence.");
            doSpnegoSequence(token);
        } else {
            LOG.debug("Using fallback authenticator sequence.");
            Authenticator auth = getFallBackAuthenticator();
            // Make sure that the fall back authenticator have the same
            // ConnectionConfigurator, since the method might be overridden.
            // Otherwise the fall back authenticator might not have the information
            // to make the connection (e.g., SSL certificates)
            auth.setConnectionConfigurator(connConfigurator);
            auth.authenticate(url, token);
        }
    }
}