Example usage for org.apache.commons.codec.binary Hex decode

List of usage examples for org.apache.commons.codec.binary Hex decode

Introduction

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

Prototype

public Object decode(Object object) throws ClassCastException 

Source Link

Document

Converts a String or an array of character bytes representing hexadecimal values into an array of bytes of those same values.

Usage

From source file:com.lightboxtechnologies.spectrum.KeyUtilsTest.java

@Test
public void retrieveImageID() throws Exception {
    final Hex hex = new Hex();
    final byte[] hash = hex.decode("deadbeefdeadbeefdeadbeefdeadbeef".getBytes());
    final byte[] imgID = hex.decode("baadf00dbaadf00dbaadf00dbaadf00d".getBytes());
    final byte[] entryID = FsEntryUtils.makeFsEntryKey(imgID, "/etc/passwd".getBytes(), 17);
    final byte[] rowKey = KeyUtils.makeEntryKey(hash, KeyUtils.MD5, entryID);

    assertArrayEquals(imgID, KeyUtils.getImageID(rowKey));
}

From source file:com.lightboxtechnologies.spectrum.KeyUtilsTest.java

@Test
public void isType2() throws Exception {
    final Hex hex = new Hex();
    final byte[] hash = hex.decode("deadbeefdeadbeefdeadbeefdeadbeef".getBytes());
    final byte[] imgID = hex.decode("baadf00dbaadf00dbaadf00dbaadf00d".getBytes());
    final byte[] entryID = FsEntryUtils.makeFsEntryKey(imgID, "/etc/passwd".getBytes(), 17);
    final byte[] rowKey = KeyUtils.makeEntryKey(hash, KeyUtils.MD5, entryID);

    assertEquals(true, KeyUtils.isType2(rowKey));
    assertEquals(false, KeyUtils.isType2(hash));
}

From source file:com.lightboxtechnologies.spectrum.KeyUtilsTest.java

@Test
public void makeOutKeySHA1() throws Exception {
    final Hex hex = new Hex();
    final byte[] hash = hex.decode("64fa477898e268fd30c2bfe272e5a016f5ec31c4".getBytes());
    final byte type = 1;
    final byte[] col = "vassalengine.org/VASSAL 3.1.15".getBytes();

    // It's neat that I have to cast one-byte numeric literals to bytes.
    // Thanks, Java!
    final byte[] expected = { (byte) 0x64, (byte) 0xfa, (byte) 0x47, (byte) 0x78, // SHA1
            (byte) 0x98, (byte) 0xe2, (byte) 0x68, (byte) 0xfd, (byte) 0x30, (byte) 0xc2, (byte) 0xbf,
            (byte) 0xe2, (byte) 0x72, (byte) 0xe5, (byte) 0xa0, (byte) 0x16, (byte) 0xf5, (byte) 0xec,
            (byte) 0x31, (byte) 0xc4, (byte) 0x01, // type
            'v', 'a', 's', 's', 'a', 'l', 'e', 'n', 'g', // column
            'i', 'n', 'e', '.', 'o', 'r', 'g', '/', 'V', 'A', 'S', 'S', 'A', 'L', ' ', '3', '.', '1', '.', '1',
            '5' };

    assertArrayEquals(expected, KeyUtils.makeEntryKey(hash, type, col));
}

From source file:com.lightboxtechnologies.spectrum.KeyUtilsTest.java

@Test
public void makeOutKeyMD5() throws Exception {
    final Hex hex = new Hex();
    final byte[] hash = hex.decode("8a9111fe05f9815fc55c728137c5b389".getBytes());
    final byte type = 0;
    final byte[] col = "vassalengine.org/VASSAL 3.1.15".getBytes();

    // It's neat that I have to cast one-byte numeric literals to bytes.
    // Thanks, Java!
    final byte[] expected = { (byte) 0x8a, (byte) 0x91, (byte) 0x11, (byte) 0xfe, // MD5
            (byte) 0x05, (byte) 0xf9, (byte) 0x81, (byte) 0x5f, (byte) 0xc5, (byte) 0x5c, (byte) 0x72,
            (byte) 0x81, (byte) 0x37, (byte) 0xc5, (byte) 0xb3, (byte) 0x89, (byte) 0x00, (byte) 0x00,
            (byte) 0x00, (byte) 0x00, // padding
            (byte) 0x00, // type
            'v', 'a', 's', 's', 'a', 'l', 'e', 'n', 'g', // column
            'i', 'n', 'e', '.', 'o', 'r', 'g', '/', 'V', 'A', 'S', 'S', 'A', 'L', ' ', '3', '.', '1', '.', '1',
            '5' };

    assertArrayEquals(expected, KeyUtils.makeEntryKey(hash, type, col));
}

From source file:com.lightboxtechnologies.nsrl.HashLoaderHelperTest.java

protected void writeRowTester(final boolean sha1rowkey) throws Exception {
    final long timestamp = 1234567890;

    final ProdData pd = new ProdData(42, "ACME Roadrunner Decapitator", "1.0", "1", "ACME", "Meep",
            "roadrunner exterminator");

    final MfgData md = new MfgData("ACME", "ACME Corporation");

    final Hex hex = new Hex();
    final byte[] sha1 = (byte[]) hex.decode("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef");
    final byte[] md5 = (byte[]) hex.decode("deadbeefdeadbeefdeadbeefdeadbeef");
    final byte[] crc32 = (byte[]) hex.decode("deadbeef");

    final byte[] sha1_col = "sha1".getBytes();
    final byte[] md5_col = "md5".getBytes();
    final byte[] crc32_col = "crc32".getBytes();
    final byte[] size_col = "filesize".getBytes();
    final byte[] nsrl_col = "NSRL".getBytes();

    final byte[] family = HBaseTables.HASH_COLFAM_B;

    final byte[] key = sha1rowkey ? sha1 : md5;
    final byte ktype = (byte) (sha1rowkey ? 1 : 0);

    final HashData hd = new HashData(sha1, md5, crc32, "librrkill.so.1", 123456, pd.code, "ACME_OS", "special");

    final ImmutableBytesWritable okey_crc32 = new ImmutableBytesWritable(
            KeyUtils.makeEntryKey(key, ktype, crc32_col));
    final KeyValue kv_crc32 = new KeyValue(key, family, crc32_col, timestamp, crc32);

    final ImmutableBytesWritable okey_sha1 = new ImmutableBytesWritable(
            KeyUtils.makeEntryKey(key, ktype, sha1_col));
    final KeyValue kv_sha1 = new KeyValue(key, family, sha1_col, timestamp, sha1);

    final ImmutableBytesWritable okey_md5 = new ImmutableBytesWritable(
            KeyUtils.makeEntryKey(key, ktype, md5_col));
    final KeyValue kv_md5 = new KeyValue(key, family, md5_col, timestamp, md5);

    final ImmutableBytesWritable okey_size = new ImmutableBytesWritable(
            KeyUtils.makeEntryKey(key, ktype, size_col));
    final KeyValue kv_size = new KeyValue(key, family, size_col, timestamp, Bytes.toBytes(hd.size));
    final ImmutableBytesWritable okey_nsrl = new ImmutableBytesWritable(
            KeyUtils.makeEntryKey(key, ktype, nsrl_col));
    final KeyValue kv_nsrl = new KeyValue(key, family, nsrl_col, timestamp, nsrl_col);

    final byte[] prod_col = (md.name + '/' + pd.name + ' ' + pd.version).getBytes();
    final ImmutableBytesWritable okey_prod = new ImmutableBytesWritable(
            KeyUtils.makeEntryKey(key, ktype, prod_col));
    final KeyValue kv_prod = new KeyValue(key, family, prod_col, timestamp, prod_col);

    final Map<Integer, List<ProdData>> prod = Collections.singletonMap(pd.code, Collections.singletonList(pd));
    final Map<String, MfgData> mfg = Collections.singletonMap(md.code, md);
    final Map<String, OSData> os = null;

    @SuppressWarnings("unchecked")
    final HashLoaderMapper.Context ctx = context.mock(HashLoaderMapper.Context.class);

    context.checking(new Expectations() {
        {// w  w w.j a v a 2s .c  om
            oneOf(ctx).write(okey_crc32, kv_crc32);

            if (sha1rowkey) {
                oneOf(ctx).write(okey_md5, kv_md5);
            } else {
                oneOf(ctx).write(okey_sha1, kv_sha1);
            }

            oneOf(ctx).write(okey_size, kv_size);
            oneOf(ctx).write(okey_nsrl, kv_nsrl);
            oneOf(ctx).write(okey_prod, kv_prod);
        }
    });

    final HashLoaderHelper hlh = new HashLoaderHelper(prod, mfg, os, timestamp);
    hlh.writeRow(key, hd, ctx);
}

From source file:be.fedict.eid.pkira.common.security.AbstractPkiRaAuthenticationResponseService.java

@Override
public void validateServiceCertificate(SamlAuthenticationPolicy authenticationPolicy,
        List<X509Certificate> certificateChain) throws SecurityException {
    if (certificateChain == null || certificateChain.size() == 0) {
        throw new SecurityException("Missing certificate chain");
    }//  w  w w. j a  va  2 s  . co  m
    X509Certificate certificate = certificateChain.get(0);

    MessageDigest md;
    try {
        md = MessageDigest.getInstance("SHA1");

        md.update(certificate.getEncoded());
        byte[] fp = md.digest();

        log.info("Actual fingerprint: " + Hex.encodeHexString(fp));

        String[] fingerprintConfig = getFingerprints();

        if (fingerprintConfig == null || fingerprintConfig.length == 0) {
            log.warn("No fingerprint given");
            return;
        }

        boolean ok = false;
        Hex hex = new Hex();
        for (String fingerprint : fingerprintConfig) {
            log.info("Allowed fingerprint: " + fingerprint);
            byte[] fpConfig = (byte[]) hex.decode(fingerprint);
            ok |= java.util.Arrays.equals(fp, fpConfig);
        }

        if (!ok) {
            log.error("Signatures not correct.");
            throw new SecurityException("Signatures not correct.");
        }
    } catch (NoSuchAlgorithmException e) {
        log.error("No Such Algorithm", e);
        throw new SecurityException(e.getMessage());
    } catch (CertificateEncodingException e) {
        log.error("Certificate Encoding Exception", e);
        throw new SecurityException(e.getMessage());
    } catch (DecoderException e) {
        log.error("Fingerprint decode problem", e);
        throw new SecurityException(e.getMessage());
    } catch (Throwable e) {
        log.error("Exception during service certificate validation", e);
        throw new SecurityException(e.getMessage());
    }
}

From source file:com.baidu.cc.configuration.service.impl.VersionServiceImpl.java

/**
 * ??.//w  w w .  j  a  v a 2s. c  om
 * 
 * @param file
 *            
 * @param versionId
 *            the version id
 * @throws IOException
 *             ?
 */
@Override
public void importFromFile(File file, Long versionId) throws IOException {
    byte[] byteArray = FileUtils.readFileToByteArray(file);

    Hex encoder = new Hex();
    try {
        byteArray = encoder.decode(byteArray);
    } catch (DecoderException e) {
        throw new IOException(e.getMessage());
    }
    String json = new String(byteArray, SysUtils.UTF_8);

    // parse from gson
    JsonParser jsonParser = new JsonParser();
    JsonElement je = jsonParser.parse(json);

    if (!je.isJsonArray()) {
        throw new RuntimeException("illegal json string. must be json array.");
    }

    JsonArray jsonArray = je.getAsJsonArray();

    int size = jsonArray.size();
    Version version = new Version();
    List<ConfigGroup> groups = new ArrayList<ConfigGroup>();
    ConfigGroup group;
    List<ConfigItem> items;
    ConfigItem item;

    for (int i = 0; i < size; i++) {
        JsonObject jo = jsonArray.get(i).getAsJsonObject();
        group = gson.fromJson(jo, ConfigGroup.class);

        // get sub configuration item
        JsonArray subItemsJson = jo.get(CONFIG_ITEMS_ELE).getAsJsonArray();

        int subSize = subItemsJson.size();
        items = new ArrayList<ConfigItem>();
        for (int j = 0; j < subSize; j++) {
            item = gson.fromJson(subItemsJson.get(j), ConfigItem.class);
            items.add(item);
        }

        group.setConfigItems(items);
        groups.add(group);
    }

    version.setConfigGroups(groups);
    configCopyService.copyConfigItemsFromVersion(version, versionId);
}

From source file:com.baidu.cc.ConfigLoader.java

/**
 * Read property from local resource file
 * /*w  ww. j av a 2s.  c  o  m*/
 * @param props to merge from local
 * @param localFile local resource file
 * @throws IOException throw all file operation exception
 */
public void readLocal(Properties props, File localFile) throws IOException {
    Assert.notNull(localFile, "Property 'localFile' is null.");
    if (!localFile.exists()) {
        throw new IOException("File not exist. " + localFile.getPath());
    }

    byte[] byteArray = FileUtils.readFileToByteArray(localFile);
    Hex encoder = new Hex();
    try {
        byteArray = encoder.decode(byteArray);
    } catch (DecoderException e) {
        throw new IOException(e.getMessage());
    }

    String json = new String(byteArray, FILE_ENCODE);

    Map<String, String> map = gson.fromJson(json, new TypeToken<Map<String, String>>() {
    }.getType());

    setVersionTag(map);
    props.putAll(map);
}

From source file:org.apache.accumulo.server.tabletserver.Tablet.java

Pair<Long, List<IteratorSetting>> getCompactionID() throws NoNodeException {
    try {//from   w w  w .ja  v  a 2  s  . c  om
        String zTablePath = Constants.ZROOT + "/" + HdfsZooInstance.getInstance().getInstanceID()
                + Constants.ZTABLES + "/" + extent.getTableId() + Constants.ZTABLE_COMPACT_ID;

        String[] tokens = new String(ZooReaderWriter.getRetryingInstance().getData(zTablePath, null))
                .split(",");
        long compactID = Long.parseLong(tokens[0]);

        CompactionIterators iters = new CompactionIterators();

        if (tokens.length > 1) {
            Hex hex = new Hex();
            ByteArrayInputStream bais = new ByteArrayInputStream(
                    hex.decode(tokens[1].split("=")[1].getBytes()));
            DataInputStream dis = new DataInputStream(bais);

            try {
                iters.readFields(dis);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            KeyExtent ke = new KeyExtent(extent.getTableId(), iters.getEndRow(), iters.getStartRow());

            if (!ke.overlaps(extent)) {
                // only use iterators if compaction range overlaps
                iters = new CompactionIterators();
            }
        }

        return new Pair<Long, List<IteratorSetting>>(compactID, iters.getIterators());
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (NumberFormatException nfe) {
        throw new RuntimeException(nfe);
    } catch (KeeperException ke) {
        if (ke instanceof NoNodeException) {
            throw (NoNodeException) ke;
        } else {
            throw new RuntimeException(ke);
        }
    } catch (DecoderException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.accumulo.tserver.tablet.Tablet.java

public Pair<Long, UserCompactionConfig> getCompactionID() throws NoNodeException {
    try {/*from  w w  w.  j  av  a2  s  . c om*/
        String zTablePath = Constants.ZROOT + "/" + tabletServer.getInstance().getInstanceID()
                + Constants.ZTABLES + "/" + extent.getTableId() + Constants.ZTABLE_COMPACT_ID;

        String[] tokens = new String(ZooReaderWriter.getInstance().getData(zTablePath, null), UTF_8).split(",");
        long compactID = Long.parseLong(tokens[0]);

        UserCompactionConfig compactionConfig = new UserCompactionConfig();

        if (tokens.length > 1) {
            Hex hex = new Hex();
            ByteArrayInputStream bais = new ByteArrayInputStream(
                    hex.decode(tokens[1].split("=")[1].getBytes(UTF_8)));
            DataInputStream dis = new DataInputStream(bais);

            try {
                compactionConfig.readFields(dis);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            KeyExtent ke = new KeyExtent(extent.getTableId(), compactionConfig.getEndRow(),
                    compactionConfig.getStartRow());

            if (!ke.overlaps(extent)) {
                // only use iterators if compaction range overlaps
                compactionConfig = new UserCompactionConfig();
            }
        }

        return new Pair<Long, UserCompactionConfig>(compactID, compactionConfig);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (NumberFormatException nfe) {
        throw new RuntimeException(nfe);
    } catch (KeeperException ke) {
        if (ke instanceof NoNodeException) {
            throw (NoNodeException) ke;
        } else {
            throw new RuntimeException(ke);
        }
    } catch (DecoderException e) {
        throw new RuntimeException(e);
    }
}