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() 

Source Link

Document

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

Usage

From source file:com.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java

private State getState(final HttpServletRequest request) {
    if (request == null) {
        throw new PreconditionException("Required parameter is null");
    }//from  w w w.  j  av  a 2 s  .  co m
    try {
        final Base64 decoder = new Base64();
        final String stateString = request.getParameter("state") == null ? null
                : new String(decoder.decode(request.getParameter("state").getBytes()), "UTF-8");
        if (stateString == null || stateString.equals("")) {
            return null;
        }
        final ObjectMapper mapper = new ObjectMapper();
        final JsonNode stateNode = mapper.readValue(stateString, JsonNode.class);
        final State state = stateFactory.createState(stateNode.get("userID").asText(""),
                stateNode.get("sessionName").asText(""), stateNode.get("requestURI").asText());
        return state;
    } catch (IOException e) {
        throw new GeneralException("IO Exception", e);
    }
}

From source file:edu.harvard.iq.dvn.api.resources.MetadataSingletonBean.java

public VDCUser authenticateAccess(String authCredentials) {
    if (authCredentials == null) {
        return null;
    }// www . j  ava2  s .c  om
    VDCUser vdcUser = null;
    Base64 base64codec = new Base64();

    String decodedCredentials = "";
    byte[] authCredBytes = authCredentials.getBytes();

    try {
        byte[] decodedBytes = base64codec.decode(authCredBytes);
        decodedCredentials = new String(decodedBytes, "ASCII");
    } catch (UnsupportedEncodingException e) {
        return null;
    }

    if (decodedCredentials != null) {
        int i = decodedCredentials.indexOf(':');
        if (i != -1) {
            String userPassword = decodedCredentials.substring(i + 1);
            String userName = decodedCredentials.substring(0, i);

            if (!"".equals(userName)) {
                vdcUser = userService.findByUserName(userName, true);
                if (vdcUser == null || !userService.validatePassword(vdcUser.getId(), userPassword)) {
                    return null;
                }
            }
        }
    }

    return vdcUser;
}

From source file:gov.tva.sparky.hbase.RestProxy.java

/**
 * /* w w  w . ja  v a2  s.com*/
 * @param strTablename
 * @param strRowKey
 * @param strColumn
 * @param strQualifier
 * @return Returns the values from a data cell in HBase.
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
public static byte[] QueryHBaseForCell(String strTablename, String strRowKey, String strColumn,
        String strQualifier) throws ParserConfigurationException, SAXException, IOException {
    // Configuration
    Configuration conf = new Configuration(false);
    conf.addResource("hadoop-default.xml");
    conf.addResource("sparky-site.xml");
    int port = conf.getInt("sparky.hbase.restPort", 8092);
    String uri = conf.get("sparky.hbase.restURI", "http://socdvmhbase");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    // never forget this!
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();

    String strRestPath = uri + ":" + port + "/" + strTablename + "/" + strRowKey + "/" + strColumn + ":"
            + strQualifier;

    Document doc = null;

    try {
        doc = builder.parse(strRestPath);

    } catch (FileNotFoundException e) {
        //System.out.println("RestProxy > Exception: ( " + strRestPath + " )");
    }

    if (null == doc)
        return null;

    XPathFactory xpath_factory = XPathFactory.newInstance();
    XPath xpath = xpath_factory.newXPath();

    XPathExpression expr = null;

    try {
        expr = xpath.compile("/CellSet/Row/Cell/text()");
    } catch (XPathExpressionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Object result = null;
    try {
        result = expr.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    NodeList nodes = (NodeList) result;
    String cell_value = nodes.item(0).getNodeValue();

    Base64 decoder = new Base64();
    byte[] decodedValue = decoder.decode(cell_value.getBytes());

    return decodedValue;
}

From source file:org.cloudfoundry.identity.uaa.login.RemoteUaaController.java

@RequestMapping(value = "/autologin", method = RequestMethod.POST)
@ResponseBody/*from ww  w  . jav  a2  s.c  o m*/
public AutologinResponse generateAutologinCode(@RequestBody AutologinRequest request,
        @RequestHeader(value = "Authorization", required = false) String auth) throws Exception {
    if (auth == null || (!auth.startsWith("Basic"))) {
        throw new BadCredentialsException("No basic authorization client information in request");
    }

    String username = request.getUsername();
    if (username == null) {
        throw new BadCredentialsException("No username in request");
    }
    Authentication remoteAuthentication = null;
    if (remoteAuthenticationManager != null) {
        String password = request.getPassword();
        if (!StringUtils.hasText(password)) {
            throw new BadCredentialsException("No password in request");
        }
        remoteAuthentication = remoteAuthenticationManager
                .authenticate(new AuthzAuthenticationRequest(username, password, null));
    }

    String base64Credentials = auth.substring("Basic".length()).trim();
    String credentials = new String(new Base64().decode(base64Credentials.getBytes()),
            Charset.forName("UTF-8"));
    // credentials = username:password
    final String[] values = credentials.split(":", 2);
    if (values == null || values.length == 0) {
        throw new BadCredentialsException("Invalid authorization header.");
    }
    String clientId = values[0];
    logger.debug("Autologin authentication request for user:" + username + "; client:" + clientId);
    SocialClientUserDetails user = new SocialClientUserDetails(username, UaaAuthority.USER_AUTHORITIES);
    Map<String, String> details = new HashMap<>();
    details.put("client_id", clientId);
    user.setDetails(details);
    if (remoteAuthentication != null && remoteAuthentication.getPrincipal() instanceof UaaPrincipal) {
        UaaPrincipal p = (UaaPrincipal) remoteAuthentication.getPrincipal();
        if (p != null) {
            details.put("origin", p.getOrigin());
            details.put("user_id", p.getId());
        }
    }

    ResponseEntity<ExpiringCode> response = doGenerateCode(user);
    return new AutologinResponse(response.getBody().getCode());
}

From source file:com.zimbra.cs.imap.ImapRequest.java

byte[] readBase64(boolean skipEquals) throws ImapParseException {
    // in some cases, "=" means to just return null and be done with it
    if (skipEquals && peekChar() == '=') {
        skipChar('=');
        return null;
    }//from   ww w  .j a v a  2s .c om

    String encoded = readContent(BASE64_CHARS, true);
    int padding = (4 - (encoded.length() % 4)) % 4;
    if (padding == 3) {
        throw new ImapParseException(tag, "invalid base64-encoded content");
    }
    while (padding-- > 0) {
        skipChar('=');
        encoded += "=";
    }
    return new Base64().decode(encoded.getBytes(Charsets.US_ASCII));
}

From source file:com.arm.connector.bridge.core.Utils.java

static public X509Certificate createX509CertificateFromPEM(ErrorLogger logger, String pem, String cert_type) {
    try {/*from   w w  w  .  j a va 2  s  .  c  om*/
        String temp = Utils.escapeChars(pem);
        String certPEM = temp.replace("-----BEGIN CERTIFICATE-----", "");
        certPEM = certPEM.replace("-----END CERTIFICATE-----", "");

        // DEBUG
        //logger.info("createX509CertificateFromPEM: " + certPEM);

        Base64 b64 = new Base64();
        byte[] decoded = b64.decode(certPEM);

        CertificateFactory cf = CertificateFactory.getInstance(cert_type);
        return (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(decoded));
    } catch (Exception ex) {
        // exception caught
        logger.warning("createX509CertificateFromPEM: Exception during private key gen", ex);
    }
    return null;
}

From source file:io.github.bonigarcia.wdm.BrowserManager.java

protected InputStream openGitHubConnection(URL driverUrl) throws IOException {
    Proxy proxy = createProxy();/*from   www  .ja v  a2 s. com*/
    URLConnection conn = proxy != null ? driverUrl.openConnection(proxy) : driverUrl.openConnection();
    conn.setRequestProperty("User-Agent", "Mozilla/5.0");
    conn.addRequestProperty("Connection", "keep-alive");

    String gitHubTokenName = WdmConfig.getString("wdm.gitHubTokenName");
    String gitHubTokenSecret = WdmConfig.getString("wdm.gitHubTokenSecret");
    if (!isNullOrEmpty(gitHubTokenName) && !isNullOrEmpty(gitHubTokenSecret)) {
        String userpass = gitHubTokenName + ":" + gitHubTokenSecret;
        String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
        conn.setRequestProperty("Authorization", basicAuth);
    }
    conn.connect();

    return conn.getInputStream();
}

From source file:com.xwiki.authentication.sts.STSTokenValidator.java

/**
  * validateToken(SignableSAMLObject samlToken)
  * Validates Token from SAMLlObject - returns boolen
  * Validates Token - exitracting sertificate from samlToken.
  * And validates it. Returning true or false according on validation results.
  * @param samlToken SignableSAMLObject//from ww  w .j  a  v  a2s . c o m
  * @return boolean valid => true, not valid => false
  */
private static boolean validateToken(SignableSAMLObject samlToken)
        throws SecurityException, ValidationException, ConfigurationException, UnmarshallingException,
        CertificateException, KeyException {

    // Validate XML structure
    samlToken.validate(true);

    Signature signature = samlToken.getSignature();
    X509Certificate certificate = certFromToken(samlToken);

    // Certificate data
    log.debug("certificate issuerDN: " + certificate.getIssuerDN());
    log.debug("certificate issuerUniqueID: " + certificate.getIssuerUniqueID());
    log.debug("certificate issuerX500Principal: " + certificate.getIssuerX500Principal());
    log.debug("certificate notBefore: " + certificate.getNotBefore());
    log.debug("certificate notAfter: " + certificate.getNotAfter());
    log.debug("certificate serialNumber: " + certificate.getSerialNumber());
    log.debug("certificate sigAlgName: " + certificate.getSigAlgName());
    log.debug("certificate sigAlgOID: " + certificate.getSigAlgOID());
    log.debug("certificate signature: " + new String(certificate.getSignature()));
    log.debug("certificate issuerX500Principal: " + certificate.getIssuerX500Principal().toString());
    log.debug("certificate publicKey: " + certificate.getPublicKey());
    log.debug("certificate subjectDN: " + certificate.getSubjectDN());
    log.debug("certificate sigAlgOID: " + certificate.getSigAlgOID());
    log.debug("certificate version: " + certificate.getVersion());

    BasicX509Credential cred = new BasicX509Credential();
    cred.setEntityCertificate(certificate);

    // Credential data
    cred.setEntityId(entityId);
    log.debug("cred entityId: " + cred.getEntityId());
    log.debug("cred usageType: " + cred.getUsageType());
    log.debug("cred credentalContextSet: " + cred.getCredentalContextSet());
    log.debug("cred hashCode: " + cred.hashCode());
    log.debug("cred privateKey: " + cred.getPrivateKey());
    log.debug("cred publicKey: " + cred.getPublicKey());
    log.debug("cred secretKey: " + cred.getSecretKey());
    log.debug("cred entityCertificateChain: " + cred.getEntityCertificateChain());

    ArrayList<Credential> trustedCredentials = new ArrayList<Credential>();
    trustedCredentials.add(cred);

    CollectionCredentialResolver credResolver = new CollectionCredentialResolver(trustedCredentials);
    KeyInfoCredentialResolver kiResolver = SecurityTestHelper.buildBasicInlineKeyInfoResolver();
    ExplicitKeySignatureTrustEngine engine = new ExplicitKeySignatureTrustEngine(credResolver, kiResolver);

    CriteriaSet criteriaSet = new CriteriaSet();
    criteriaSet.add(new EntityIDCriteria(entityId));

    Base64 decoder = new Base64();
    // In trace mode write certificate in the file
    if (log.isTraceEnabled()) {
        String certEncoded = new String(decoder.encode(certificate.getEncoded()));
        try {
            FileUtils.writeStringToFile(new File("/tmp/Certificate.cer"),
                    "-----BEGIN CERTIFICATE-----\n" + certEncoded + "\n-----END CERTIFICATE-----");
            log.trace("Certificate file was saved in: /tmp/Certificate.cer");
        } catch (IOException e1) {
            log.error(e1);
        }
    }
    return engine.validate(signature, criteriaSet);
}

From source file:fr.gael.dhus.olingo.ODataClient.java

/**
 * Performs the execution of an OData command through HTTP.
 * //  w ww .j  ava 2 s .com
 * @param absolute_uri The not that relative URI to query.
 * @param content_type The content type can be JSON, XML, Atom+XML,
 *    see {@link OdataContentType}.
 * @param http_method {@code "POST", "GET", "PUT", "DELETE", ...}
 * 
 * @return The response as a stream. You may assume it's UTF-8 encoded.
 * 
 * @throws HttpException if the server emits an HTTP error code.
 * @throws IOException if an error occurred connecting to the server.
 */
private InputStream execute(String absolute_uri, ContentType content_type, String http_method)
        throws IOException {
    URL url = new URL(absolute_uri);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    // HTTP Basic Authentication.
    String userpass = this.username + ":" + this.password;
    String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
    connection.setRequestProperty("Authorization", basicAuth);

    // GET, POST, ...
    connection.setRequestMethod(http_method);

    // `Accept` for GET, `Content-Type` for POST and PUT.
    connection.setRequestProperty("Accept", content_type.type());

    connection.connect();

    int resp_code = connection.getResponseCode();
    // 2XX == success, 3XX == redirect (handled by the HTTPUrlConnection)
    if (resp_code == 200) {
        InputStream content = connection.getInputStream();

        content = logRawContent(http_method + " request on uri '" + absolute_uri + "' with content:\n", content,
                "\n");

        return content;
    } else if (resp_code >= 300 && resp_code < 400) {
        // HttpURLConnection should follow redirections automatically,
        // but won't follow if the protocol changes.
        // See https://bugs.openjdk.java.net/browse/JDK-4620571
        // If the scheme has changed (http -> https) follow the redirection.

        String redi_uri = connection.getHeaderField("Location");

        if (redi_uri == null || redi_uri.isEmpty())
            throw new HttpException(connection.getResponseCode(),
                    connection.getResponseMessage() + " redirection failure.");

        if (!redi_uri.startsWith("https"))
            throw new HttpException(connection.getResponseCode(),
                    connection.getResponseMessage() + " unsecure redirection.");

        LOGGER.debug("Attempting redirection to " + redi_uri);
        connection.disconnect();

        return execute(redi_uri, content_type, http_method);
    } else {
        throw new HttpException(connection.getResponseCode(), connection.getResponseMessage());
    }
}

From source file:com.arm.connector.bridge.core.Utils.java

static public PrivateKey createPrivateKeyFromPEM(ErrorLogger logger, String pem, String algorithm) {
    try {/*from  w  w w. j a  va  2  s.c o  m*/
        String temp = Utils.escapeChars(pem);
        String privKeyPEM = temp.replace("-----BEGIN RSA PRIVATE KEY-----", "");
        privKeyPEM = privKeyPEM.replace("-----END RSA PRIVATE KEY-----", "");

        // DEBUG
        //logger.info("createPrivateKeyFromPEM: " + privKeyPEM);

        Base64 b64 = new Base64();
        byte[] decoded = b64.decode(privKeyPEM);

        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
        KeyFactory kf = KeyFactory.getInstance(algorithm);
        return kf.generatePrivate(spec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
        // exception caught
        logger.warning("createPrivateKeyFromPEM: Exception during private key gen", ex);
    }
    return null;
}