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

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

Introduction

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

Prototype

public static byte[] decodeBase64(final byte[] base64Data) 

Source Link

Document

Decodes Base64 data into octets

Usage

From source file:com.hpe.caf.worker.testing.validation.Base64PropertyValidator.java

@Override
protected boolean isValid(Object testedPropertyValue, Object validatorPropertyValue) {
    if (validatorPropertyValue == null) {
        return testedPropertyValue == null;
    }/*from  w ww  . j av a  2  s  .  c  om*/

    if (testedPropertyValue == null) {
        return false;
    }

    if (!(testedPropertyValue instanceof byte[]) || !(validatorPropertyValue instanceof String)) {
        throw new AssertionError(
                "Unexpected types provided to Base64PropertyValidator. Expected byte array testedPropertyValue and String validatorPropertyValue. Provided were "
                        + testedPropertyValue.getClass().getSimpleName() + " and "
                        + validatorPropertyValue.getClass().getSimpleName() + ". Values: "
                        + testedPropertyValue.toString() + ", " + validatorPropertyValue.toString());
    }

    byte[] testedPropertyValueBytes = (byte[]) testedPropertyValue;

    if (validatorPropertyValue.toString().equals("*")) {
        return testedPropertyValueBytes.length > 0;
    }

    boolean areEqual = Arrays.equals(testedPropertyValueBytes,
            Base64.decodeBase64(validatorPropertyValue.toString()));

    if (!areEqual) {
        String actual = Base64.encodeBase64String(testedPropertyValueBytes);
        System.err.println("Unexpected result. Actual value: " + actual + ", expected value: "
                + validatorPropertyValue.toString());
    }

    return areEqual;
}

From source file:com.jsmartframework.web.manager.AuthEncrypter.java

static String decrypt(HttpServletRequest request, String key, Object value) {
    if (key != null && value != null) {
        try {/* w ww. j ava  2  s . com*/
            byte[] decoded = Base64.decodeBase64(value.toString());
            return new String(getDecryptCipher(request, key).doFinal(decoded), "UTF8");
        } catch (Exception ex) {
            LOGGER.log(Level.INFO, "Failed to decrypt value [" + value + "]: " + ex.getMessage());
        }
        return value.toString();
    }
    return null;
}

From source file:com.example.license.RSAUtil.java

/**
 * ?//  w w  w  .j  av  a2 s .  co m
 * 
 * @param data
 *            ?
 * @param key
 *            
 * @return ??
 */
public static String decrypt(String data, String seed) throws Exception {
    KeyPair keyPair = generatorKeyPair(seed);
    Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
    // ?Cipher?
    cipher.init(Cipher.DECRYPT_MODE, keyPair.getPublic());
    // ?
    return new String(cipher.doFinal(Base64.decodeBase64(data)));
}

From source file:com.tremolosecurity.unison.proxy.auth.openidconnect.loadUser.LoadJWTFromAccessToken.java

public Map loadUserAttributesFromIdP(HttpServletRequest request, HttpServletResponse response,
        ConfigManager cfg, HashMap<String, Attribute> authParams, Map accessToken) throws Exception {

    String tokenName = authParams.get("jwtTokenAttributeName").getValues().get(0);

    String hd = authParams.get("hd").getValues().get(0);

    if (logger.isDebugEnabled()) {
        logger.debug("access token : '" + accessToken + "'");
    }//from w w  w.j  a  va  2  s  .co  m

    //"id_token"
    String jwt = (String) accessToken.get(tokenName);

    Map jwtNVP = null;

    //Since we are getting the token from a valid source, no need to check the signature? (probably not really true, need to figure out what sig to check against)
    int firstPeriod = jwt.indexOf('.');
    int lastPeriod = jwt.lastIndexOf('.');

    String json = new String(Base64.decodeBase64(jwt.substring(firstPeriod + 1, lastPeriod)));

    if (logger.isDebugEnabled()) {
        logger.info("json : '" + json + "'");
    }

    jwtNVP = com.cedarsoftware.util.io.JsonReader.jsonToMaps(json);

    if (hd != null && !hd.isEmpty()) {
        String emailAddress = (String) jwtNVP.get("email");
        if (emailAddress != null && !emailAddress.isEmpty()) {
            if (!emailAddress.endsWith(hd)) {
                return null;
            }
        } else {
            return null;
        }
    }

    return jwtNVP;
}

From source file:com.redhat.rhevm.api.common.security.auth.BasicAuthorizationScheme.java

private Principal decode(String credentials) {
    Principal principal = null;//w ww . j a  v  a  2  s  .com
    try {
        credentials = credentials.trim().substring(SCHEME.length()).trim();
        String userPass = new String(Base64.decodeBase64(credentials));
        String[] creds = userPass.split(USER_PASS_SEPARATOR, 2);
        if (creds != null && creds.length == 2) {
            principal = parse(creds[0], creds[1], getSeparator(creds[0]));
        }
    } catch (Exception e) {
        // let principal remain null
    }
    return principal;
}

From source file:com.vmware.fdmsecprotomgmt.PasswdEncrypter.java

/**
 * Decrypt the encrypted value with provided key
 *///from   w  w  w  .j  a v a 2 s . c  om
public static String decrypt(String key, String encryptedValue) {
    String decryptedString = null;
    try {
        IvParameterSpec iv = new IvParameterSpec(INIT_VECTOR.getBytes("UTF-8"));
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

        decryptedString = new String(cipher.doFinal(Base64.decodeBase64(encryptedValue)));

    } catch (Exception ex) {
        System.out.println("Caught exception while decrypting string");
        ex.printStackTrace();
    }

    return decryptedString;
}

From source file:de.mpg.escidoc.services.aa.crypto.RSAEncoder.java

public static String rsaDecrypt(String[] string) throws Exception {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrivateKey privateKey = (PrivateKey) readKeyFromFile(Config.getProperty("escidoc.aa.private.key.file"),
            false);/*from  w w w .jav  a  2  s.  com*/
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    for (String part : string) {
        byte[] inArr = Base64.decodeBase64(part.getBytes("UTF-8"));
        baos.write(cipher.doFinal(inArr));
        baos.flush();
    }

    return new String(baos.toByteArray(), "UTF-8");

}

From source file:com.pearson.developer.xapi.proxy.AuthFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws java.io.IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;

    // AJAX will preflight xAPI request with OPTIONS request without Authorization header
    if ("OPTIONS".equals(req.getMethod())) {
        chain.doFilter(request, response);
        return;//w  ww  .java 2s .  c o m
    }

    boolean authorized = false;
    try { // decode and verify the basic auth credentials
        String authHeader = req.getHeader("Authorization");
        authHeader = authHeader.substring("Basic ".length());
        String decodedAuthHeader = new String(Base64.decodeBase64(authHeader), "UTF-8");
        String[] credentials = decodedAuthHeader.split(":");
        if (credentials.length == 2) {
            String username = credentials[0];
            String password = credentials[1];
            authorized = SessionDatabase.verify(username, password);
        }
    } catch (Exception e) {
        // do nothing
    }

    // proceed to xAPI if session was authorized
    if (authorized) {
        final String targetBasicAuth = config.getInitParameter("targetBasicAuth");

        // need to give the LRS it's expected Authorization value
        HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(req) {
            @Override
            public String getHeader(String name) {
                if ("Authorization".equalsIgnoreCase(name)) {
                    return targetBasicAuth;
                }
                return super.getHeader(name);
            }

            @Override
            public Enumeration<String> getHeaders(String name) {
                if ("Authorization".equalsIgnoreCase(name)) {
                    List<String> values = new ArrayList<String>();
                    values.add(targetBasicAuth);
                    return Collections.enumeration(values);
                }
                return super.getHeaders(name);
            }
        };
        chain.doFilter(requestWrapper, response);
        return;
    }

    // respond with a 401 if missing auth
    HttpServletResponse resp = (HttpServletResponse) response;
    resp.reset();
    resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    resp.getWriter().println("401 - Unauthorized");
}

From source file:com.qut.middleware.esoe.sso.plugins.artifact.bean.Artifact.java

public Artifact(String artifact) throws ArtifactBindingException {
    byte[] rawArtifact;
    try {/*ww w  . ja va2  s  .  c  o  m*/
        rawArtifact = Base64.decodeBase64(artifact.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException(
                "Unable to parse the Base64 SAML artifact token because the required encoding is not supported.",
                e);
    }

    if (rawArtifact.length < 20) {
        throw new ArtifactBindingException(
                "Unable to parse the SAML artifact token, it is not the correct length required by the SAML spec (20 bytes).");
    }

    type = ((int) rawArtifact[0] * 0x100) + (int) rawArtifact[1];
    index = ((int) rawArtifact[2] * 0x100) + (int) rawArtifact[3];

    if (type != 0x0004) {
        throw new ArtifactBindingException(
                "Unable to parse the SAML artifact token, unrecognized type ID: " + type);
    }

    if (rawArtifact.length != 44) {
        throw new ArtifactBindingException(
                "Unable to parse the SAML artifact token, it is not the correct length required by the SAML spec for type ID 0x0004 (44 bytes).");
    }

    this.sourceID = new byte[20];
    for (int i = 0; i < 20; ++i) {
        // Read bytes 4 - 23 inclusive.
        this.sourceID[i] = rawArtifact[4 + i];
    }

    this.messageHandle = new byte[20];
    for (int i = 0; i < 20; ++i) {
        // Read bytes 24 - 43 inclusive.
        this.messageHandle[i] = rawArtifact[24 + i];
    }
}

From source file:com.rdonasco.security.utils.EncryptionUtil.java

public static String decryptWithPassword(String encryptedString, String password) throws Exception {
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), SALT, COUNT);
    SecretKey pbeKey = getKeyFactory().generateSecret(pbeKeySpec);
    Cipher pbeCipher = Cipher.getInstance(CIPHER_KEY_SPEC);
    pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, PBE_PARAM_SPEC);
    byte[] decryptedBytes = pbeCipher.doFinal(Base64.decodeBase64(encryptedString));
    return new String(decryptedBytes);
}