Example usage for javax.xml.bind DatatypeConverter parseBase64Binary

List of usage examples for javax.xml.bind DatatypeConverter parseBase64Binary

Introduction

In this page you can find the example usage for javax.xml.bind DatatypeConverter parseBase64Binary.

Prototype

public static byte[] parseBase64Binary(String lexicalXSDBase64Binary) 

Source Link

Document

Converts the string argument into an array of bytes.

Usage

From source file:org.adeptnet.auth.saml.SAMLClient.java

/**
 * Check an authnResponse and return the subject if validation succeeds. The
 * NameID from the subject in the first valid assertion is returned along
 * with the attributes./*from   www . j  a v  a2 s  . co  m*/
 *
 * @param _authnResponse a base64-encoded AuthnResponse from the SP
 * @throws SAMLException if validation failed.
 * @return the authenticated subject/attributes as an AttributeSet
 */
public AttributeSet validateResponsePOST(final String _authnResponse) throws SAMLException {
    final byte[] decoded = DatatypeConverter.parseBase64Binary(_authnResponse);
    final String authnResponse;
    try {
        authnResponse = new String(decoded, "UTF-8");
        if (LOG.isTraceEnabled()) {
            LOG.trace(authnResponse);
        }
    } catch (UnsupportedEncodingException e) {
        throw new SAMLException("UTF-8 is missing, oh well.", e);
    }

    final Response response = parseResponse(authnResponse);

    try {
        validatePOST(response);
    } catch (ValidationException e) {
        throw new SAMLException(e);
    }

    return getAttributeSet(response);
}

From source file:org.adeptnet.auth.saml.SAMLClient.java

public AttributeSet validateResponseGET(final String queryString) throws SAMLException {
    final String samlTicket = getRawQueryStringParameter(queryString, SAML_RESPONSE);
    if (samlTicket == null) {
        throw new SAMLException(String.format("%s cannot be null", SAML_RESPONSE));
    }/*from ww w .ja v  a 2s.  c  o  m*/
    final String samlSig = getRawQueryStringParameter(queryString, SAML_SIGALG);
    if (samlSig == null) {
        throw new SAMLException(String.format("%s cannot be null", SAML_SIGALG));
    }
    final String samlSigature = getRawQueryStringParameter(queryString, SAML_SIGNATURE);
    if (samlSigature == null) {
        throw new SAMLException(String.format("%s cannot be null", SAML_SIGNATURE));
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("%s: %s", SAML_RESPONSE, samlTicket));
        LOG.debug(String.format("%s: %s", SAML_SIGALG, samlSig));
        LOG.debug(String.format("%s: %s", SAML_SIGNATURE, samlSigature));
    }
    try {

        final StringBuilder sb = new StringBuilder();
        sb.append(String.format("%s=%s&", SAML_RESPONSE, samlTicket));
        final String samlRelayState = getRawQueryStringParameter(queryString, SAML_RELAYSTATE);
        if (samlRelayState != null) {
            sb.append(String.format("%s=%s&", SAML_RELAYSTATE, samlRelayState));
        }
        sb.append(String.format("%s=%s", SAML_SIGALG, samlSig));

        if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("%s: %s", "verification", sb.toString()));
        }

        if (!SigningUtil.verifyWithURI(cred, getAlgorithmURIFromID(HTTPTransportUtils.urlDecode(samlSig)),
                DatatypeConverter.parseBase64Binary(HTTPTransportUtils.urlDecode(samlSigature)),
                sb.toString().getBytes("UTF-8"))) {
            throw new SAMLException("!SigningUtil.verifyWithURI");
        }
    } catch (UnsupportedEncodingException | SecurityException ex) {
        throw new SAMLException(ex);
    }

    final byte[] decoded;
    try {
        decoded = inflate(DatatypeConverter.parseBase64Binary(HTTPTransportUtils.urlDecode(samlTicket)));
    } catch (IOException ex) {
        throw new SAMLException(ex);
    }

    final String authnResponse;
    try {
        authnResponse = new String(decoded, "UTF-8");
        if (LOG.isTraceEnabled()) {
            LOG.trace(authnResponse);
        }
    } catch (UnsupportedEncodingException e) {
        throw new SAMLException("UTF-8 is missing, oh well.", e);
    }

    final Response response = parseResponse(authnResponse);

    try {
        validate(response);
    } catch (ValidationException e) {
        throw new SAMLException(e);
    }
    return getAttributeSet(response);
}

From source file:org.apache.maven.classpath.munger.validation.JarValidationUtilsTest.java

@Test
public void testSignatureOnSameJar() throws Exception {
    URL orgData = getClassContainerLocationURL(Assert.class);
    assertNotNull("Cannot find source URL", orgData);

    File cpyData = createTempFile(getCurrentTestName(), ".jar");
    try (InputStream input = orgData.openStream()) {
        try (OutputStream output = new FileOutputStream(cpyData)) {
            long cpySize = IOUtils.copyLarge(input, output);
            logger.info("Copy(" + orgData.toExternalForm() + ")[" + cpyData.getAbsolutePath() + "]: " + cpySize
                    + " bytes");
        }//from   w  w w.ja  v  a  2s. c  o  m
    }

    NamedPropertySource expected = JarValidationUtils.createJarSignature(orgData);
    NamedPropertySource actual = JarValidationUtils.createJarSignature(cpyData);
    JarValidationUtils.validateJarSignature(expected, actual);

    if (logger.isDebugEnabled()) {
        for (String name : expected.getAvailableNames()) {
            String digestString = expected.getProperty(name);
            byte[] digestValue = DatatypeConverter.parseBase64Binary(digestString);
            logger.debug("    " + name + ": " + DatatypeConverter.printHexBinary(digestValue));
        }
    }
}

From source file:org.apache.nifi.processors.standard.TestPutSQL.java

@Test
public void testBinaryColumnTypes()
        throws InitializationException, ProcessException, SQLException, IOException, ParseException {
    final TestRunner runner = TestRunners.newTestRunner(PutSQL.class);
    try (final Connection conn = service.getConnection()) {
        try (final Statement stmt = conn.createStatement()) {
            stmt.executeUpdate(/*from  w  w w  . java 2s.c om*/
                    "CREATE TABLE BINARYTESTS (id integer primary key, bn1 CHAR(8) FOR BIT DATA, bn2 VARCHAR(100) FOR BIT DATA, "
                            + "bn3 LONG VARCHAR FOR BIT DATA)");
        }
    }

    runner.addControllerService("dbcp", service);
    runner.enableControllerService(service);
    runner.setProperty(PutSQL.CONNECTION_POOL, "dbcp");

    final byte[] insertStatement = "INSERT INTO BINARYTESTS (ID, bn1, bn2, bn3) VALUES (?, ?, ?, ?)".getBytes();

    final String arg2BIN = fixedSizeByteArrayAsASCIIString(8);
    final String art3VARBIN = fixedSizeByteArrayAsASCIIString(50);
    final String art4LongBin = fixedSizeByteArrayAsASCIIString(32700); //max size supported by Derby

    //ASCII (default) binary formatn
    Map<String, String> attributes = new HashMap<>();
    attributes.put("sql.args.1.type", String.valueOf(Types.INTEGER));
    attributes.put("sql.args.1.value", "1");
    attributes.put("sql.args.2.type", String.valueOf(Types.BINARY));
    attributes.put("sql.args.2.value", arg2BIN);
    attributes.put("sql.args.3.type", String.valueOf(Types.VARBINARY));
    attributes.put("sql.args.3.value", art3VARBIN);
    attributes.put("sql.args.4.type", String.valueOf(Types.LONGVARBINARY));
    attributes.put("sql.args.4.value", art4LongBin);

    runner.enqueue(insertStatement, attributes);

    //ASCII with specified format
    attributes = new HashMap<>();
    attributes.put("sql.args.1.type", String.valueOf(Types.INTEGER));
    attributes.put("sql.args.1.value", "2");
    attributes.put("sql.args.2.type", String.valueOf(Types.BINARY));
    attributes.put("sql.args.2.value", arg2BIN);
    attributes.put("sql.args.2.format", "ascii");
    attributes.put("sql.args.3.type", String.valueOf(Types.VARBINARY));
    attributes.put("sql.args.3.value", art3VARBIN);
    attributes.put("sql.args.3.format", "ascii");
    attributes.put("sql.args.4.type", String.valueOf(Types.LONGVARBINARY));
    attributes.put("sql.args.4.value", art4LongBin);
    attributes.put("sql.args.4.format", "ascii");

    runner.enqueue(insertStatement, attributes);

    //Hex
    final String arg2HexBIN = fixedSizeByteArrayAsHexString(8);
    final String art3HexVARBIN = fixedSizeByteArrayAsHexString(50);
    final String art4HexLongBin = fixedSizeByteArrayAsHexString(32700);

    attributes = new HashMap<>();
    attributes.put("sql.args.1.type", String.valueOf(Types.INTEGER));
    attributes.put("sql.args.1.value", "3");
    attributes.put("sql.args.2.type", String.valueOf(Types.BINARY));
    attributes.put("sql.args.2.value", arg2HexBIN);
    attributes.put("sql.args.2.format", "hex");
    attributes.put("sql.args.3.type", String.valueOf(Types.VARBINARY));
    attributes.put("sql.args.3.value", art3HexVARBIN);
    attributes.put("sql.args.3.format", "hex");
    attributes.put("sql.args.4.type", String.valueOf(Types.LONGVARBINARY));
    attributes.put("sql.args.4.value", art4HexLongBin);
    attributes.put("sql.args.4.format", "hex");

    runner.enqueue(insertStatement, attributes);

    //Base64
    final String arg2Base64BIN = fixedSizeByteArrayAsBase64String(8);
    final String art3Base64VARBIN = fixedSizeByteArrayAsBase64String(50);
    final String art4Base64LongBin = fixedSizeByteArrayAsBase64String(32700);

    attributes = new HashMap<>();
    attributes.put("sql.args.1.type", String.valueOf(Types.INTEGER));
    attributes.put("sql.args.1.value", "4");
    attributes.put("sql.args.2.type", String.valueOf(Types.BINARY));
    attributes.put("sql.args.2.value", arg2Base64BIN);
    attributes.put("sql.args.2.format", "base64");
    attributes.put("sql.args.3.type", String.valueOf(Types.VARBINARY));
    attributes.put("sql.args.3.value", art3Base64VARBIN);
    attributes.put("sql.args.3.format", "base64");
    attributes.put("sql.args.4.type", String.valueOf(Types.LONGVARBINARY));
    attributes.put("sql.args.4.value", art4Base64LongBin);
    attributes.put("sql.args.4.format", "base64");

    runner.enqueue(insertStatement, attributes);

    runner.run();

    runner.assertAllFlowFilesTransferred(PutSQL.REL_SUCCESS, 4);

    try (final Connection conn = service.getConnection()) {
        try (final Statement stmt = conn.createStatement()) {
            final ResultSet rs = stmt.executeQuery("SELECT * FROM BINARYTESTS");

            //First Batch
            assertTrue(rs.next());
            assertEquals(1, rs.getInt(1));
            assertTrue(Arrays.equals(arg2BIN.getBytes("ASCII"), rs.getBytes(2)));
            assertTrue(Arrays.equals(art3VARBIN.getBytes("ASCII"), rs.getBytes(3)));
            assertTrue(Arrays.equals(art4LongBin.getBytes("ASCII"), rs.getBytes(4)));

            //Second batch
            assertTrue(rs.next());
            assertEquals(2, rs.getInt(1));
            assertTrue(Arrays.equals(arg2BIN.getBytes("ASCII"), rs.getBytes(2)));
            assertTrue(Arrays.equals(art3VARBIN.getBytes("ASCII"), rs.getBytes(3)));
            assertTrue(Arrays.equals(art4LongBin.getBytes("ASCII"), rs.getBytes(4)));

            //Third Batch (Hex)
            assertTrue(rs.next());
            assertEquals(3, rs.getInt(1));
            assertTrue(Arrays.equals(DatatypeConverter.parseHexBinary(arg2HexBIN), rs.getBytes(2)));
            assertTrue(Arrays.equals(DatatypeConverter.parseHexBinary(art3HexVARBIN), rs.getBytes(3)));
            assertTrue(Arrays.equals(DatatypeConverter.parseHexBinary(art4HexLongBin), rs.getBytes(4)));

            //Fourth Batch (Base64)
            assertTrue(rs.next());
            assertEquals(4, rs.getInt(1));
            assertTrue(Arrays.equals(DatatypeConverter.parseBase64Binary(arg2Base64BIN), rs.getBytes(2)));
            assertTrue(Arrays.equals(DatatypeConverter.parseBase64Binary(art3Base64VARBIN), rs.getBytes(3)));
            assertTrue(Arrays.equals(DatatypeConverter.parseBase64Binary(art4Base64LongBin), rs.getBytes(4)));

            assertFalse(rs.next());
        }
    }
}

From source file:org.apache.storm.common.AbstractAutoCreds.java

private Credentials doGetCredentials(Map<String, String> credentials, String configKey) {
    Credentials credential = null;//from  w  w w.j  a  v  a 2  s .  co m
    if (credentials != null && credentials.containsKey(getCredentialKey(configKey))) {
        try {
            byte[] credBytes = DatatypeConverter
                    .parseBase64Binary(credentials.get(getCredentialKey(configKey)));
            ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(credBytes));

            credential = new Credentials();
            credential.readFields(in);
        } catch (Exception e) {
            LOG.error("Could not obtain credentials from credentials map.", e);
        }
    }
    return credential;

}

From source file:org.apache.storm.common.HadoopCredentialUtil.java

private static Credentials doGetCredentials(CredentialKeyProvider provider, Map<String, String> credentials,
        String configKey) {//ww  w.  j av a 2s .c o  m
    Credentials credential = null;
    String credentialKey = provider.getCredentialKey(configKey);
    if (credentials != null && credentials.containsKey(credentialKey)) {
        try {
            byte[] credBytes = DatatypeConverter.parseBase64Binary(credentialKey);
            ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(credBytes));

            credential = new Credentials();
            credential.readFields(in);
        } catch (Exception e) {
            LOG.error("Could not obtain credentials from credentials map.", e);
        }
    }
    return credential;
}

From source file:org.bunkr.core.descriptor.PBKDF2Descriptor.java

public PBKDF2Descriptor(JSONObject params) {
    encryptionAlgorithm = Encryption.valueOf((String) params.get("encryptionAlgorithm"));
    pbkdf2Iterations = ((Long) params.get("timeComboBox")).intValue();
    pbkdf2Salt = DatatypeConverter.parseBase64Binary((String) params.get("salt"));

    if (pbkdf2Iterations < MINIMUM_PBKD2_ITERS)
        throw new IllegalArgumentException(
                String.format("pbkdf2Iterations must be at least %d", MINIMUM_PBKD2_ITERS));
}

From source file:org.bunkr.core.descriptor.ScryptDescriptor.java

public ScryptDescriptor(JSONObject o) {
    this.encryptionAlgorithm = Encryption.valueOf((String) o.get("encryptionAlgorithm"));
    this.scryptSalt = DatatypeConverter.parseBase64Binary((String) o.get("scryptSalt"));
    this.scryptN = ((Long) o.get("scryptN")).intValue();
    this.scryptR = ((Long) o.get("scryptR")).intValue();
    this.scryptP = ((Long) o.get("scryptP")).intValue();
}

From source file:org.bunkr.core.inventory.FileInventoryItemJSON.java

@SuppressWarnings("unchecked")
public static FileInventoryItem decodeO(JSONObject input) {
    byte[] encD = null;
    if (input.getOrDefault(KEY_ENCRYPTION_DATA, null) != null)
        encD = DatatypeConverter.parseBase64Binary((String) input.get(KEY_ENCRYPTION_DATA));

    byte[] intH = null;
    if (input.getOrDefault(KEY_INTEGRITY_HASH, null) != null)
        intH = DatatypeConverter.parseBase64Binary((String) input.get(KEY_INTEGRITY_HASH));

    Algorithms.Encryption encA = Algorithms.Encryption.NONE;
    if (input.getOrDefault(KEY_ENCRYPTION_ALGORITHM, null) != null)
        encA = Algorithms.Encryption.valueOf((String) input.get(KEY_ENCRYPTION_ALGORITHM));

    String mt = MediaType.UNKNOWN;
    if (input.getOrDefault(KEY_MEDIA_TYPE, null) != null) {
        mt = (String) input.get(KEY_MEDIA_TYPE);
        if (!MediaType.ALL_TYPES.contains(mt)) {
            Logging.warn("File %s has unsupported media type %s. Converting to %s", input.get(KEY_NAME), mt,
                    MediaType.UNKNOWN);
            mt = MediaType.UNKNOWN;
        }//w  w w  .j av  a2 s  . c  o  m
    }

    return new FileInventoryItem((String) input.get(KEY_NAME), UUID.fromString((String) input.get(KEY_UUID)),
            FragmentedRangeJSON.decode((JSONArray) input.get(KEY_BLOCKS)), (Long) input.get(KEY_SIZE_ON_DISK),
            (Long) input.get(KEY_ACTUAL_SIZE), (Long) input.get(KEY_MODIFIED_AT), encD, encA, intH, mt);
}

From source file:org.eclipse.birt.data.oda.mongodb.impl.MDbResultSet.java

private static Object tryConvertToBytes(String stringValue) {
    try {/*www  . ja  v a 2 s  .c o m*/
        return DatatypeConverter.parseBase64Binary(stringValue);
    } catch (Exception ex) {
        // DatatypeConverter could be un-initialized,
        // log and continue; note that Base64Codec#decode might be unavailable in some versions
        if (getLogger().isLoggable(Level.FINE))
            getLogger().fine(Messages.bind(
                    "Unable to convert the String field value ({0}) to a bytes[] value.\n Cause: {1}", //$NON-NLS-1$
                    stringValue, ex.getMessage()));
    }
    return stringValue; // not able to convert; return value as is
}