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

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

Introduction

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

Prototype

public static byte[] decodeHex(char[] data) throws IllegalArgumentException 

Source Link

Document

Converts an array of characters representing hexadecimal values into an array of bytes of those same values.

Usage

From source file:libepg.epg.section.eventinformationtable.EventInformationTableRepeatingPartTest.java

/**
 * Test of getDuration method, of class EventInformationTableRepeatingPart.
 *///  www. j av a  2s . c om
@Test
public void testGetDuration() throws DecoderException {
    LOG.debug("getDuration");
    EventInformationTableRepeatingPart instance = target;
    byte[] expResult = Hex.decodeHex("002500".toCharArray());
    byte[] result = instance.getDuration();
    assertArrayEquals(expResult, result);
}

From source file:libepg.epg.section.sdt.ServiceDescriptionTableRepeatingPartTest.java

@Test
public void testHashCode_NotSame() throws DecoderException, Throwable {
    LOG.debug("HashCode_Notsame");
    ServiceDescriptionTableRepeatingPart instance1 = ClassGetter.init(this.x);
    ServiceDescriptionTableRepeatingPart instance2 = ClassGetter.init(
            Hex.decodeHex("0409f3001c481201000f0e4e484b451d461d6c320f456c357ec10184cf0302fe08".toCharArray()));
    boolean xx = (instance1.hashCode() == instance2.hashCode());
    assertEquals(xx, false);/*from   w  ww .j  a  v a2 s  . c  o  m*/
}

From source file:libepg.epg.section.servicedescriptiontable.ServiceDescriptionTableRepeatingPartTest.java

@Test
public void testHashCode_NotSame() throws DecoderException, Throwable {
    LOG.info("HashCode_Notsame");
    ServiceDescriptionTableRepeatingPart instance1 = ClassGetter.init(this.x);
    ServiceDescriptionTableRepeatingPart instance2 = ClassGetter.init(
            Hex.decodeHex("0409f3001c481201000f0e4e484b451d461d6c320f456c357ec10184cf0302fe08".toCharArray()));
    boolean xx = (instance1.hashCode() == instance2.hashCode());
    assertEquals(xx, false);// w ww  . j av  a 2s .c o  m
}

From source file:libepg.epg.section.eit.descriptor.extendedeventdescriptor.ExtendedEventDescriptorTest.java

/**
 * Test of getText_char method, of class ExtendedEventDescriptor.
 * ??????//  www . j a va2s.  co  m
 *
 * @throws org.apache.commons.codec.DecoderException
 * @throws java.lang.reflect.InvocationTargetException
 */
@Test
public void testGetText_char2() throws DecoderException, InvocationTargetException {
    LOG.debug("getText_char2");

    byte[] dat = this.descs.getEXTENDED_EVENT_DESCRIPTOR_BYTE();
    byte[] dat2 = Hex.decodeHex("0e4e484b451d461d6c310f456c357e".toCharArray());
    //
    byte[] dat3 = ArrayUtils.addAll(dat, dat2);

    LOG.debug(Hex.encodeHexString(dat));
    LOG.debug(Hex.encodeHexString(dat2));
    LOG.debug(Hex.encodeHexString(dat3));

    //??
    dat3[1] = (byte) (dat.length - 1 + dat2.length - 1);
    //?
    dat3[dat.length - 1] = (byte) dat2.length;
    LOG.debug(Hex.encodeHexString(dat3));

    Descriptor dummy = Descriptors.init(dat3);
    ExtendedEventDescriptor instance = new ExtendedEventDescriptor(dummy);

    byte[] expResult = dat2;
    byte[] result = instance.getText_char();
    assertArrayEquals(expResult, result);
}

From source file:libepg.epg.section.eventinformationtable.descriptor.extendedeventdescriptor.ExtendedEventDescriptorTest.java

/**
 * Test of getText_char method, of class ExtendedEventDescriptor.
 * ??????//w  ww.  j  a v a  2s.  co  m
 *
 * @throws org.apache.commons.codec.DecoderException
 * @throws java.lang.reflect.InvocationTargetException
 */
@Test
public void testGetText_char2() throws DecoderException, InvocationTargetException {
    LOG.info("getText_char2");

    byte[] dat = this.descs.getEXTENDED_EVENT_DESCRIPTOR_BYTE();
    byte[] dat2 = Hex.decodeHex("0e4e484b451d461d6c310f456c357e".toCharArray());
    //
    byte[] dat3 = ArrayUtils.addAll(dat, dat2);

    LOG.info(Hex.encodeHexString(dat));
    LOG.info(Hex.encodeHexString(dat2));
    LOG.info(Hex.encodeHexString(dat3));

    //??
    dat3[1] = (byte) (dat.length - 1 + dat2.length - 1);
    //?
    dat3[dat.length - 1] = (byte) dat2.length;
    LOG.info(Hex.encodeHexString(dat3));

    Descriptor dummy = Descriptors.init(dat3);
    ExtendedEventDescriptor instance = new ExtendedEventDescriptor(dummy);

    byte[] expResult = dat2;
    byte[] result = instance.getText_char();
    assertArrayEquals(expResult, result);
}

From source file:com.dinochiesa.edgecallouts.AesCryptoCallout.java

private byte[] decodeString(String s, EncodingType decodingKind) throws Exception {
    if (decodingKind == EncodingType.HEX) {
        return Hex.decodeHex(s.toCharArray());
    }/*from w ww  .  j  av a 2  s  . c  o  m*/
    if (decodingKind == EncodingType.BASE64) {
        return Base64.decodeBase64(s);
    }
    return s.getBytes(StandardCharsets.UTF_8);
}

From source file:de.betterform.connector.serializer.FormDataSerializer.java

protected void serializeElement(PrintWriter writer, Element element, String boundary, String charset)
        throws Exception {
    /* The specs http://www.w3.org/TR/2003/REC-xforms-20031014/slice11.html#serialize-form-data
     *//from w  ww  . ja  v a2  s  .  c  om
     *     Each element node is visited in document order.
     *
     *     Each element that has exactly one text node child is selected 
     *     for inclusion.
     *
     *     Element nodes selected for inclusion are as encoded as 
     *     Content-Disposition: form-data MIME parts as defined in 
     *     [RFC 2387], with the name parameter being the element local name.
     *
     *     Element nodes of any datatype populated by upload are serialized 
     *     as the specified content and additionally have a 
     *     Content-Disposition filename parameter, if available.
     *
     *     The Content-Type must be text/plain except for xsd:base64Binary, 
     *     xsd:hexBinary, and derived types, in which case the header 
     *     represents the media type of the attachment if known, otherwise 
     *     application/octet-stream. If a character set is applicable, the 
     *     Content-Type may have a charset parameter.
     *
     */
    String nodeValue = null;
    boolean isCDATASection = false;
    boolean includeTextNode = true;

    NodeList list = element.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
        Node n = list.item(i);
        switch (n.getNodeType()) {

        /* CDATA sections are not mentioned ... ignore for now
        case Node.CDATA_SECTION_NODE:
            isCDATASection = true;
         */

        case Node.TEXT_NODE:
            if (includeTextNode) {
                if (nodeValue != null) {
                    /* only one text node allowed by specs */
                    includeTextNode = false;
                } else {
                    nodeValue = n.getNodeValue();
                }
            }
            break;

        /* Real ambiguity in specs, what if there's one text node and
         * n elements ? Let's assume if there is an element, ignore the
         * text nodes
         */
        case Node.ELEMENT_NODE:
            includeTextNode = false;
            serializeElement(writer, (Element) n, boundary, charset);
            break;

        default:
            // ignore comments and other nodes...
        }
    }

    if (nodeValue != null && includeTextNode) {

        Object object = element.getUserData("");
        if (object != null && !(object instanceof ModelItem)) {
            throw new XFormsException("Unknown instance data format.");
        }
        ModelItem item = (ModelItem) object;

        writer.print("\r\n--" + boundary);

        String name = element.getLocalName();
        if (name == null) {
            name = element.getNodeName();
        }

        // mediatype tells about file upload
        if (item != null && item.getMediatype() != null) {
            writer.print("\r\nContent-Disposition: form-data; name=\"" + name + "\";");
            if (item.getFilename() != null) {
                File file = new File(item.getFilename());
                writer.print(" filename=\"" + file.getName() + "\";");
            }
            writer.print("\r\nContent-Type: " + item.getMediatype());

        } else {
            writer.print("\r\nContent-Disposition: form-data; name=\"" + name + "\";");
            writer.print("\r\nContent-Type: text/plain; charset=\"" + charset + "\";");
        }

        String encoding = "8bit";
        if (item != null && "base64Binary".equalsIgnoreCase(item.getDeclarationView().getDatatype())) {
            encoding = "base64";
        } else if (item != null && "hexBinary".equalsIgnoreCase(item.getDeclarationView().getDatatype())) {
            // recode to base64 because of MIME
            nodeValue = new String(Base64.encodeBase64(Hex.decodeHex(nodeValue.toCharArray()), true));
            encoding = "base64";
        }
        writer.print("\r\nContent-Transfer-Encoding: " + encoding);
        writer.print("\r\n\r\n" + nodeValue);
    }

    writer.flush();
}

From source file:mitm.common.security.KeyEncoderTest.java

private static PrivateKey decodePrivateKey(String encoded) throws DecoderException, InvalidKeySpecException {
    byte[] rawKey = Hex.decodeHex(encoded.toCharArray());

    KeySpec keySpec = new PKCS8EncodedKeySpec(rawKey);

    return keyFactory.generatePrivate(keySpec);
}

From source file:com.streamsets.lib.security.http.PasswordHasher.java

public boolean verify(String storedPasswordHash, String user, String givenPassword) {
    boolean ok = false;
    String version = getHashVersion(storedPasswordHash);
    String valueToHash = getValueToHash(version, user, givenPassword);
    String cachedPassword = getVerifyCache().getIfPresent(storedPasswordHash);
    if (cachedPassword != null) {
        ok = cachedPassword.equals(valueToHash);
    } else {/*from  w  w  w. ja va 2s .co m*/
        try {
            String[] parts = storedPasswordHash.split(":");
            if (parts.length > 0) {
                switch (version) {
                case V1:
                case V2:
                case V3: {
                    if (parts.length == 4) {
                        int hashIterations = Integer.parseInt(parts[1]);
                        byte[] hashSalt = Hex.decodeHex(parts[2].toCharArray());
                        // we don't need the stored hash (parts[3]) as we compare the fully stored thing

                        String recomputedHash = computeHash(version, hashIterations, hashSalt, valueToHash);
                        ok = storedPasswordHash.equals(recomputedHash);
                        if (ok) {
                            getVerifyCache().put(storedPasswordHash, valueToHash);
                        }
                    }
                }
                    break;
                default:
                    throw new IllegalArgumentException(
                            Utils.format("Invalid/unsupported hash version '{}'", version));
                }
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
    return ok;
}

From source file:monasca.api.infrastructure.persistence.vertica.MetricDefinitionVerticaRepoImpl.java

private List<Map<String, Object>> executeMetricDefsQuery(String tenantId, String name,
        Map<String, String> dimensions, DateTime startTime, DateTime endTime, String offset, int limit) {

    String namePart = "";

    if (name != null && !name.isEmpty()) {

        namePart = " and defSub.name = :name ";

    }//from   www  .  ja  v a2 s  .com

    String offsetPart = "";

    if (offset != null && !offset.isEmpty()) {

        offsetPart = " and defDimsSub.id > :offset ";

    }

    String limitPart = "";

    if (limit > 0) {

        limitPart = "limit " + Integer.toString(limit + 1);

    }

    try (Handle h = db.open()) {

        String sql = String.format(MetricQueries.FIND_METRIC_DEFS_SQL, this.dbHint,
                String.format(METRIC_DEF_SUB_QUERY, MetricQueries.buildTimeJoin(startTime), namePart,
                        offsetPart, MetricQueries.buildDimensionAndClause(dimensions, TABLE_TO_JOIN_ON),
                        MetricQueries.buildTimeAndClause(startTime, endTime), limitPart));

        Query<Map<String, Object>> query = h.createQuery(sql).bind("tenantId", tenantId);

        if (name != null && !name.isEmpty()) {
            logger.debug("binding name: {}", name);
            query.bind("name", name);
        }

        if (startTime != null) {
            query.bind("startTime", startTime);
        }

        if (endTime != null) {
            query.bind("endTime", endTime);
        }

        if (offset != null && !offset.isEmpty()) {

            logger.debug("binding offset: {}", offset);

            try {

                query.bind("offset", Hex.decodeHex(offset.toCharArray()));

            } catch (DecoderException e) {

                throw Exceptions.badRequest("failed to decode offset " + offset, e);
            }

        }

        MetricQueries.bindDimensionsToQuery(query, dimensions);

        return query.list();

    }
}