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

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

Introduction

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

Prototype

public static boolean isBase64(final byte[] arrayOctet) 

Source Link

Document

Tests a given byte array to see if it contains only valid characters within the Base64 alphabet.

Usage

From source file:biz.turnonline.ecosystem.origin.frontend.content.subscription.BaseRawContent.java

/**
 * Deserialize JSON content from data (either encoded in Base64 form or regular string)
 * and returns the target instance populated with values from the JSON data.
 *
 * @param mapper the JSON mapper//from  w w w  . j av  a  2s  . c o  m
 * @return the concrete instance populated with values from the JSON data
 * @throws IOException if deserialization fails
 */
public T convert(ObjectMapper mapper) throws IOException {
    if (content == null) {
        return null;
    }

    String decoded;
    if (Base64.isBase64(content.getBytes())) {
        decoded = new String(new PubsubMessage().setData(content).decodeData(), Charset.forName("UTF-8"));
    } else {
        decoded = content;
    }
    return mapper.readValue(decoded, type);
}

From source file:edu.wpi.cs.wpisuitetng.authentication.BasicAuth.java

/**
 * Inspects the authString and determines if it is a valid BasicAuth string.
 *    Checks if it has all 3 parts, then checks the validity of the parts.
 * @param authString   the authorization string to be validated
 * @return   true if valid, false otherwise.
 *//*from www .ja v a 2 s.  c o  m*/
private boolean isValidBasicAuth(String[] authParts) {
    // check if the post string is in the correct format
    if ((authParts.length != 2) || (!authParts[0].equalsIgnoreCase("Basic"))) {
        return false;
    }

    // check if the credential section is encoded properly
    if (!Base64.isBase64(authParts[1])) {
        return false;
    }

    return true;
}

From source file:edu.tamu.tcat.crypto.bouncycastle.PBKDF2Impl.java

@Override
protected boolean checkHash(byte[] password, String saltStr, String outputStr, DigestType digest, int rounds) {
    if (!Base64.isBase64(saltStr) || !Base64.isBase64(outputStr))
        return false;

    byte[] salt = Base64.decodeBase64(saltStr);
    byte[] output = Base64.decodeBase64(outputStr);

    int outputSize = DigestTypeMap.getDigest(digest).getDigestSize();
    if (output.length != outputSize)
        return false;

    PBKDF2Impl pbkdf2 = new PBKDF2Impl(digest);
    byte[] candidate = pbkdf2.deriveKey(password, salt, rounds, outputSize);
    return Arrays.equals(candidate, output);
}

From source file:com.cloud.upgrade.dao.Upgrade41000to41100.java

private void validateUserDataInBase64(Connection conn) {
    try (final PreparedStatement selectStatement = conn
            .prepareStatement("SELECT `id`, `user_data` FROM `cloud`.`user_vm` WHERE `user_data` IS NOT NULL;");
            final ResultSet selectResultSet = selectStatement.executeQuery()) {
        while (selectResultSet.next()) {
            final Long userVmId = selectResultSet.getLong(1);
            final String userData = selectResultSet.getString(2);
            if (Base64.isBase64(userData)) {
                final String newUserData = Base64.encodeBase64String(Base64.decodeBase64(userData.getBytes()));
                if (!userData.equals(newUserData)) {
                    try (final PreparedStatement updateStatement = conn.prepareStatement(
                            "UPDATE `cloud`.`user_vm` SET `user_data` = ? WHERE `id` = ? ;")) {
                        updateStatement.setString(1, newUserData);
                        updateStatement.setLong(2, userVmId);
                        updateStatement.executeUpdate();
                    } catch (SQLException e) {
                        LOG.error("Failed to update cloud.user_vm user_data for id:" + userVmId
                                + " with exception: " + e.getMessage());
                        throw new CloudRuntimeException(
                                "Exception while updating cloud.user_vm for id " + userVmId, e);
                    }/*from  w ww.j  a  v a 2s.  com*/
                }
            } else {
                // Update to NULL since it's invalid
                LOG.warn("Removing user_data for vm id " + userVmId + " because it's invalid");
                LOG.warn("Removed data was: " + userData);
                try (final PreparedStatement updateStatement = conn
                        .prepareStatement("UPDATE `cloud`.`user_vm` SET `user_data` = NULL WHERE `id` = ? ;")) {
                    updateStatement.setLong(1, userVmId);
                    updateStatement.executeUpdate();
                } catch (SQLException e) {
                    LOG.error("Failed to update cloud.user_vm user_data for id:" + userVmId
                            + " to NULL with exception: " + e.getMessage());
                    throw new CloudRuntimeException(
                            "Exception while updating cloud.user_vm for id " + userVmId + " to NULL", e);
                }
            }
        }
    } catch (SQLException e) {
        throw new CloudRuntimeException(
                "Exception while validating existing user_vm table's user_data column to be base64 valid with padding",
                e);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Done validating base64 content of user data");
    }
}

From source file:fr.insalyon.creatis.vip.core.server.auth.SamlAuthenticationService.java

@Override
protected void checkValidRequest(HttpServletRequest request) throws BusinessException {
    logger.info("SAML authentication request");

    String token = request.getParameter("_saml_token");
    if (token == null) {
        throw new BusinessException("SAML token is null");
    }//from w  w  w.  j  a  va  2s.  c  om

    // Get the SAML assertion in XML form
    // SAML assertion might be encoded in base64 (happens in FLI)
    byte[] xmlAssertion = token.getBytes();
    if (Base64.isBase64(xmlAssertion)) {
        xmlAssertion = Base64.decodeBase64(xmlAssertion);
    }

    // Get an Assertion object from XML assertion
    assertion = null;
    try {
        try {
            // XML object might be a saml response. In this case, take the first assertion found
            // (happens in FLI)
            Response samlResponse = (Response) SamlTokenValidator.getSAMLObject(xmlAssertion);
            List<Assertion> assertions = samlResponse.getAssertions();
            assertion = assertions.get(0);
        } catch (ClassCastException ex) {
            // Otherwise, try to cast directly the XML object to Assertion (happens in Neugrid).
            assertion = (Assertion) SamlTokenValidator.getSAMLObject(xmlAssertion);
        }
    } catch (UnsupportedEncodingException | ConfigurationException | XMLParserException
            | UnmarshallingException ex) {
        java.util.logging.Logger.getLogger(SamlAuthenticationService.class.getName()).log(Level.SEVERE, null,
                ex);
    }
    if (assertion == null) {
        throw new BusinessException("Cannot get assertion!");
    }

    // Find public key certificate to use from issuer
    issuer = assertion.getIssuer();
    if (issuer == null) {
        throw new BusinessException("Cannot find assertion issuer!");
    }
    logger.info("Received SAML assertion from issuer " + issuer.getValue());
    String certFile = Server.getInstance().getSamlTrustedCertificate(issuer.getValue());

    // Check validity of assertion
    try {
        SamlTokenValidator.isSignatureValid(certFile, assertion);
    } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException
            | ValidationException ex) {
        throw new BusinessException("Assertion signature is not valid!");
    }
    if (!SamlTokenValidator.isTimeValid(assertion)) {
        throw new BusinessException("Assertion is not time valid!");
    }
    try {
        if (!SamlTokenValidator.isAudienceValid(request.getRequestURL().toString(), assertion)) {
            throw new BusinessException("Assertion audience is not valid!");
        }
    } catch (MalformedURLException ex) {
        throw new BusinessException(ex);
    }
}

From source file:com.vmware.o11n.plugin.crypto.service.CryptoDigestService.java

private void validateB64(String dataB64) {
    if (!Base64.isBase64(dataB64)) {
        throw new IllegalArgumentException(
                "Expecting base64 encoded data.  Use CryptoEncoding.base64Encode() against this string before attempting to hash it");
    }/*  w  ww.  j  a v  a 2  s  .  co  m*/
}

From source file:com.msopentech.odatajclient.engine.AbstractPrimitiveTest.java

protected void binary(final String entity, final String propertyName) {
    final ODataPrimitiveValue opv = readPrimitiveValue(entity, propertyName);
    assertEquals(EdmSimpleType.Binary.toString(), opv.getTypeName());

    final byte[] value = opv.<byte[]>toCastValue();
    assertNotNull(value);//from  w w w  .  jav a  2 s .  c  o  m
    assertTrue(value.length > 0);
    assertTrue(Base64.isBase64(opv.toString()));
}

From source file:com.amazonaws.serverless.proxy.test.jersey.JerseyAwsProxyTest.java

@Test
public void base64_binaryResponse_base64Encoding() {
    AwsProxyRequest request = new AwsProxyRequestBuilder("/echo/binary", "GET").build();

    AwsProxyResponse response = handler.proxy(request, lambdaContext);
    assertNotNull(response.getBody());/*  w ww  .  j  a  va2  s .  c o  m*/
    assertTrue(Base64.isBase64(response.getBody()));
}

From source file:codesample.AuthenticationSample.java

/*****************************************************************************************************************
 *
 * Get the encoded username required to authenticate user to BWS.
 *
 * @return Returns a string containing the encoded username if successful, and null otherwise.
 *
 *****************************************************************************************************************
 *///from w  w w  .  j  a v  a 2 s  . co m
public static String getEncodedUserName(String username, Authenticator authenticator,
        CredentialType credentialType, String domain) throws WebServiceException {
    final String METHOD_NAME = "getEncodedUserName()";
    final String BWS_API_NAME = "_bwsUtil.getEncodedUsername()";
    logMessage("Entering %s", METHOD_NAME);
    String returnValue = null;

    GetEncodedUsernameRequest request = new GetEncodedUsernameRequest();
    request.setMetadata(REQUEST_METADATA);
    request.setUsername(username);
    request.setOrgUid(REQUEST_METADATA.getOrganizationUid());
    request.setAuthenticator(authenticator);

    request.setCredentialType(credentialType);
    request.setDomain(domain);

    GetEncodedUsernameResponse response = null;
    try {
        logRequest(BWS_API_NAME);
        response = _bwsUtil.getEncodedUsername(request);
        logResponse(BWS_API_NAME, response.getReturnStatus().getCode(), response.getMetadata());
    } catch (WebServiceException e) {
        // Log and re-throw exception.
        logMessage("Exiting %s with exception \"%s\"", METHOD_NAME, e.getMessage());
        throw e;
    }

    if (response.getReturnStatus().getCode().equals("SUCCESS")) {
        returnValue = response.getEncodedUsername();
    } else {
        logMessage("Error Message: \"%s\"", response.getReturnStatus().getMessage());
    }

    if (Base64.isBase64(returnValue)) {
        logMessage("Decoded value of encoded username \"%s\"",
                StringUtils.newStringUtf8(Base64.decodeBase64(returnValue)));
    } else {
        logMessage("Value of encoded username \"%s\"", returnValue);
    }
    logMessage("Exiting %s", METHOD_NAME);
    return returnValue;
}

From source file:fr.aliacom.obm.common.addition.CommitedOperationDaoJdbcImpl.java

@VisibleForTesting
void checkClientIdFormat(String clientId) {
    Preconditions.checkArgument(clientId.length() == 40, "clientId must have a length of 40 characters");
    Preconditions.checkArgument(Base64.isBase64(clientId), "clientId must be in base 64");
}