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:com.nxp.ltsm.ltsmclient.tools.VCDescriptionFile.java

public static byte[] CreatePersonalizeData(byte[] VCData, String pkgName, String appShaName, short VC_Entry,
        Context context) {/*from  w  w  w  .java2s  .  c om*/
    String TAG = "VCDescriptionFile:cCreatePersonalizeData";
    Log.i(TAG, "Enter");
    int i = VCData.length;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] VC_EntryBytes = Utils.shortToByteArr(VC_Entry);
    try {
        out.write(createTlv(0x4F, Hex.decodeHex(appShaName.toCharArray())));
        out.write(createTlv(0x40, VC_EntryBytes));
        out.write(Utils.append(VCData,
                createTlv(0xC1, Hex.decodeHex(Utils.shaSignature(pkgName, context).toCharArray()))));
        return (createTlv(0x73, out.toByteArray()));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.cedarsoft.serialization.test.performance.Bson4JacksonTest.java

@Test
public void testParse() throws Exception {
    JsonParser parser = jsonFactory.createJsonParser(Hex.decodeHex(BSON.toCharArray()));

    assertEquals(JsonToken.START_OBJECT, parser.nextToken());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("id", parser.getCurrentName());
    assertEquals(JsonToken.VALUE_STRING, parser.nextToken());
    assertEquals("Canon Raw", parser.getText());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("dependent", parser.getCurrentName());
    assertEquals(JsonToken.VALUE_FALSE, parser.nextToken());
    assertFalse(parser.getBooleanValue());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("extension", parser.getCurrentName());
    assertEquals(JsonToken.START_OBJECT, parser.nextToken());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("extension", parser.getCurrentName());
    assertEquals(JsonToken.VALUE_STRING, parser.nextToken());
    assertEquals("cr2", parser.getText());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("default", parser.getCurrentName());
    assertEquals(JsonToken.VALUE_TRUE, parser.nextToken());
    assertTrue(parser.getBooleanValue());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("delimiter", parser.getCurrentName());
    assertEquals(JsonToken.VALUE_STRING, parser.nextToken());
    assertEquals(".", parser.getText());

    assertEquals(JsonToken.END_OBJECT, parser.nextToken());
    assertEquals(JsonToken.END_OBJECT, parser.nextToken());
    assertNull(parser.nextToken());/* ww  w.j a v  a 2  s .c  o  m*/
}

From source file:com.cedarsoft.serialization.jackson.test.UserDetailsSerializer.java

@Nonnull
@Override//from   w w  w  . ja  v  a 2  s  .  co  m
public UserDetails deserialize(@Nonnull JsonParser deserializeFrom, @Nonnull Version formatVersion)
        throws IOException, VersionException, JsonProcessingException {
    long registrationDate = -1;
    long lastLogin = -1;
    String passwordHash = null;

    JacksonParserWrapper parser = new JacksonParserWrapper(deserializeFrom);

    while (parser.nextToken() == JsonToken.FIELD_NAME) {
        String currentName = parser.getCurrentName();

        if (currentName.equals(PROPERTY_REGISTRATION_DATE)) {
            parser.nextToken(JsonToken.VALUE_NUMBER_INT);
            registrationDate = parser.getLongValue();
            continue;
        }

        if (currentName.equals(PROPERTY_LAST_LOGIN)) {
            parser.nextToken(JsonToken.VALUE_NUMBER_INT);
            lastLogin = parser.getLongValue();
            continue;
        }

        if (currentName.equals(PROPERTY_PASSWORD_HASH)) {
            parser.nextToken(JsonToken.VALUE_STRING);
            passwordHash = parser.getText();
            continue;
        }

        throw new IllegalStateException("Unexpected field reached <" + currentName + ">");
    }

    parser.verifyDeserialized(registrationDate, PROPERTY_REGISTRATION_DATE);
    parser.verifyDeserialized(lastLogin, PROPERTY_LAST_LOGIN);
    parser.verifyDeserialized(passwordHash, PROPERTY_PASSWORD_HASH);

    assert passwordHash != null;

    parser.ensureObjectClosed();

    try {
        return new UserDetails(registrationDate, lastLogin, Hex.decodeHex(passwordHash.toCharArray()));
    } catch (DecoderException e) {
        throw new RuntimeException(e);
    }
}

From source file:io.manasobi.utils.CryptoUtils.java

/**
 * hex ?? ? SecretKey ? ?./*ww w  .  j av  a  2  s  . c om*/
 *
 * @param keyHex generateHexKey ? ? ?? Hex ? ? 
 *       
 * @return ?? SecretKey ?
 */
private static SecretKey getSecretDESKeyFromHex(String keyHex) {

    SecretKey key = null;

    try {

        byte[] keyBytes = Hex.decodeHex(keyHex.toCharArray());

        key = new SecretKeySpec(keyBytes, ALGORITHM);

    } catch (Exception e) {

        throw new CryptoUtilsException(e.getMessage());
    }

    return key;
}

From source file:de.resol.vbus.HeaderTest.java

@Test
public void testCalcChecksumV0() throws Exception {
    byte[] testBuffer1 = Hex.decodeHex("aa000021772000050000000000000042".toCharArray());
    assertEquals(0x42, Header.calcChecksumV0(testBuffer1, 1, 14));
}

From source file:libepg.epg.util.DateTimeFieldConverterTest.java

/**
 * Test of BytesToSqlDateTime method, of class DateTimeFieldConverter.
 *
 * @throws java.lang.Exception/*w  w w .  j av a  2s  . c  o  m*/
 */
@Test
public void testBytesTOSqlDateTime2() throws Exception {
    LOG.debug("BytesTOSqlDateTime2");
    byte[] source = Hex.decodeHex("e07c180000".toCharArray());
    Timestamp expResult = new Timestamp(
            new java.text.SimpleDateFormat("yyyyMMddHHmmss").parse("20160321180000").getTime());
    Timestamp result = DateTimeFieldConverter.BytesToSqlDateTime(source);
    assertEquals(expResult, result);
}

From source file:edu.hawaii.soest.kilonalu.ctd.CTDParser.java

public void setData(String dataString) throws ParseException {
    logger.debug("CTDParser.setData() called.");

    // make the observations available to the class
    this.observationsString = dataString;

    // build the list of data variable names and offsets

    // handle profile mode
    if (this.samplingMode.equals("profile")) {

        // handle the raw frquencies and voltages in Hex OUTPUTFORMAT (0)
        if (this.outputFormat.equals("raw HEX")) {
            this.dataVariableNames = new ArrayList<String>();
            this.dataVariableNames.add(this.RAW_TEMPERATURE_FIELD_NAME);
            this.dataVariableNames.add(this.RAW_CONDUCTIVITY_FIELD_NAME);

            this.dataVariableUnits = new ArrayList<String>();
            this.dataVariableUnits.add("counts");
            this.dataVariableUnits.add("Hz");

            this.currentOffset = 6;
            this.dataVariableOffsets = new ArrayList<Integer>();
            this.dataVariableOffsets.add(currentOffset);
            this.currentOffset = currentOffset + 6;
            this.dataVariableOffsets.add(currentOffset);

            // Is pressure present?
            if (this.hasPressure) {
                this.dataVariableNames.add(this.RAW_PRESSURE_FIELD_NAME);
                this.dataVariableUnits.add("counts");
                this.currentOffset = this.currentOffset + 6;
                this.dataVariableOffsets.add(this.currentOffset);

                // And is it a strain gauge sensor?
                if (this.hasStrainGaugePressure) {
                    dataVariableNames.add(this.RAW_PRESSURE_TEMP_COMP_FIELD_NAME);
                    dataVariableUnits.add("counts");
                    currentOffset = currentOffset + 4;
                    dataVariableOffsets.add(currentOffset);

                }//  w ww.  ja v  a 2 s . c om

            } else {
                logger.info("There is no pressure sensor.");
            }

            // Is there a channel zero voltage present?
            if (this.hasVoltageChannelZero) {
                this.dataVariableNames.add(this.RAW_VOLTAGE_CHANNEL_ZERO_FIELD_NAME);
                this.dataVariableUnits.add("V");
                this.currentOffset = this.currentOffset + 4;
                this.dataVariableOffsets.add(this.currentOffset);

            }

            // Is there a channel one voltage present?
            if (this.hasVoltageChannelOne) {
                this.dataVariableNames.add(this.RAW_VOLTAGE_CHANNEL_ONE_FIELD_NAME);
                this.dataVariableUnits.add("V");
                this.currentOffset = this.currentOffset + 4;
                this.dataVariableOffsets.add(this.currentOffset);

            }

            // Is there a channel two voltage present?
            if (this.hasVoltageChannelTwo) {
                this.dataVariableNames.add(this.RAW_VOLTAGE_CHANNEL_TWO_FIELD_NAME);
                this.dataVariableUnits.add("V");
                this.currentOffset = this.currentOffset + 4;
                this.dataVariableOffsets.add(this.currentOffset);

            }

            // Is there a channel three voltage present?
            if (this.hasVoltageChannelThree) {
                this.dataVariableNames.add(this.RAW_VOLTAGE_CHANNEL_THREE_FIELD_NAME);
                this.dataVariableUnits.add("V");
                this.currentOffset = this.currentOffset + 4;
                this.dataVariableOffsets.add(this.currentOffset);

            }

            /*
             * @todo - handle SBE38, SBE50, and/or gasTensionDevice data
             */

            // We now know the data variable names, units, and corresponding
            // character offsets for each Hex data string found in the 
            // dataValuesMap.  Build a raw matrix from the dataValuesMap by only
            // applying output factors.  Conversion to useful variable units
            // will happen in the calling source driver since voltage channel
            // semantics are unknown to the parser
            int beginIndex = 0;
            int endIndex = 0;
            int offsetIndex = 0;
            String hexSubstring = "";
            String hexDataString = "";
            Hex decoder = new Hex();
            double value = 0d;
            this.convertedDataValuesMatrix = new Array2DRowRealMatrix(this.dataValuesMap.size() - 1,
                    this.dataVariableOffsets.size());

            for (int rowIndex = 1; rowIndex < this.dataValuesMap.size(); rowIndex++) {
                hexDataString = this.dataValuesMap.get(rowIndex);
                logger.debug(rowIndex + ") hexDataString is: " + hexDataString);

                for (offsetIndex = 0; offsetIndex < this.dataVariableOffsets.size(); offsetIndex++) {
                    endIndex = this.dataVariableOffsets.get(offsetIndex);
                    hexSubstring = hexDataString.substring(beginIndex, endIndex);

                    try {
                        // convert the hex characters to bytes
                        byte[] hexAsBytes = decoder.decodeHex(hexSubstring.toCharArray());

                        BigInteger bigInteger = new BigInteger(hexAsBytes);
                        int intValue = bigInteger.intValue();

                        // the hex values are either 2 or 3 bytes long (AABBCC or AABB)
                        // BigInteger fills in missing bits with 0xFF. Remove them.  This
                        // is only a problem with large bytes that cause the value to 
                        // become negative.
                        if (hexAsBytes.length < 3) {
                            intValue = (intValue & 0x0000FFFF);

                        } else {
                            intValue = (intValue & 0x00FFFFFF);

                        }
                        value = new Integer(intValue).doubleValue();

                        // convert the value based on the CTD User manual conversion using
                        // the corresponding data variable name to determine which conversion
                        double convertedValue = convert(value, this.dataVariableNames.get(offsetIndex));

                        convertedDataValuesMatrix.setEntry(rowIndex - 1, offsetIndex, convertedValue);
                        logger.debug("\t" + this.dataVariableNames.get(offsetIndex) + " is:\t" + value
                                + "\tConverted: " + convertedValue);
                        // set the beginIndex to start at the endIndex
                        beginIndex = endIndex;

                    } catch (DecoderException de) {
                        logger.debug("Could not decode the Hex string: " + hexSubstring);
                    }

                } // for

                // reset the offsetIndex for the next hexDataString
                offsetIndex = 0;
                beginIndex = 0;
            } // for

            // handle the engineering units in Hex OUTPUTFORMAT (1)
        } else if (this.outputFormat.equals("converted Hex")) {

            /*
             * @todo - handle OUTPUTFORMAT (1)
             */

            // handle the raw frquencies and voltages in decimal OUTPUTFORMAT (2)
        } else if (this.outputFormat.equals("raw decimal")) {

            /*
             * @todo - handle OUTPUTFORMAT (2)
             */

            // handle the engineering units in decimal OUTPUTFORMAT (3)
        } else if (this.outputFormat.equals("converted decimal")) {

            /*
             * @todo - handle OUTPUTFORMAT (3)
             */
        }

        // handle moored mode
    } else if (this.samplingMode.equals("moored")) {

        // handle the raw frequencies and voltages in Hex OUTPUTFORMAT (0)
        if (this.outputFormat.equals("raw HEX")) {

            // handle the engineering units in Hex OUTPUTFORMAT (1)
        } else if (this.outputFormat.equals("converted Hex")) {

            /*
             * @todo - handle OUTPUTFORMAT (1)
             */

            // handle the raw frequencies and voltages in decimal OUTPUTFORMAT (2)
        } else if (this.outputFormat.equals("raw decimal")) {

            /*
             * @todo - handle OUTPUTFORMAT (2)
             */

            // handle the engineering units in decimal OUTPUTFORMAT (3)
        } else if (this.outputFormat.equals("converted decimal")) {

            this.dataVariableNames = new ArrayList<String>();
            this.dataVariableNames.add(this.TEMPERATURE_FIELD_NAME);
            this.dataVariableNames.add(this.CONDUCTIVITY_FIELD_NAME);

            this.dataVariableUnits = new ArrayList<String>();
            this.dataVariableUnits.add("degrees C");
            this.dataVariableUnits.add("S/m");

            // Is pressure present?
            if (this.hasPressure) {
                this.dataVariableNames.add(this.PRESSURE_FIELD_NAME);
                this.dataVariableUnits.add("decibars");

            } else {
                logger.info("There is no pressure sensor.");
            }

            // Is there a channel zero voltage present?
            if (this.hasVoltageChannelZero) {
                this.dataVariableNames.add(this.RAW_VOLTAGE_CHANNEL_ZERO_FIELD_NAME);
                this.dataVariableUnits.add("V");

            }

            // Is there a channel one voltage present?
            if (this.hasVoltageChannelOne) {
                this.dataVariableNames.add(this.RAW_VOLTAGE_CHANNEL_ONE_FIELD_NAME);
                this.dataVariableUnits.add("V");

            }

            // Is there a channel two voltage present?
            if (this.hasVoltageChannelTwo) {
                this.dataVariableNames.add(this.RAW_VOLTAGE_CHANNEL_TWO_FIELD_NAME);
                this.dataVariableUnits.add("V");

            }

            // Is there a channel three voltage present?
            if (this.hasVoltageChannelThree) {
                this.dataVariableNames.add(this.RAW_VOLTAGE_CHANNEL_THREE_FIELD_NAME);
                this.dataVariableUnits.add("V");

            }

            // Is there a channel four voltage present?
            if (this.hasVoltageChannelFour) {
                this.dataVariableNames.add(this.RAW_VOLTAGE_CHANNEL_FOUR_FIELD_NAME);
                this.dataVariableUnits.add("V");

            }

            // Is there a channel five voltage present?
            if (this.hasVoltageChannelFive) {
                this.dataVariableNames.add(this.RAW_VOLTAGE_CHANNEL_FIVE_FIELD_NAME);
                this.dataVariableUnits.add("V");

            }

            /*
             * @todo - handle SBE38, SBE50, and/or gasTensionDevice data
             */

            // Will salinity be output?
            if (this.willOutputSalinity) {
                this.dataVariableNames.add(this.SALINITY_FIELD_NAME);
                this.dataVariableUnits.add("psu");

            }

            // Will sound velocity be output?
            if (this.willOutputSalinity) {
                this.dataVariableNames.add(this.SOUND_VELOCITY_FIELD_NAME);
                this.dataVariableUnits.add("m/s");

            }

            // Add the date and time fields
            this.dataVariableNames.add(this.DATE_FIELD_NAME);
            this.dataVariableUnits.add("dd MMM yyyy");
            this.dataVariableNames.add(this.TIME_FIELD_NAME);
            this.dataVariableUnits.add("hh:mm:ss");

        }

        this.convertedDataValuesMatrix = new Array2DRowRealMatrix(this.dataValuesMap.size() - 1,
                this.dataVariableOffsets.size()); // CSJ fix this

    } else {
        throw new ParseException(
                "There was an error parsing the data string. " + "The sampling mode is not recognized.", 0);

    }

}

From source file:io.stallion.utils.Encrypter.java

private static SecretKeySpec makeKeySpec(String password, String salt) {
    byte[] saltBytes = new byte[0];
    try {//w  w w  .  j  av a  2 s . co  m
        saltBytes = Hex.decodeHex(salt.toCharArray());
    } catch (DecoderException e) {
        throw new RuntimeException(e);
    }
    PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), saltBytes, ITERATIONS, KEY_LENGTH);
    SecretKey secretKey;
    try {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        secretKey = factory.generateSecret(keySpec);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Not a valid encryption algorithm", e);
    } catch (InvalidKeySpecException e) {
        throw new IllegalArgumentException("Not a valid secret key", e);
    }
    SecretKeySpec skeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
    return skeySpec;
}

From source file:com.arvato.thoroughly.util.security.impl.DefaultEncryptionKeyRetrievalStrategy.java

private SecretKeySpec keyStringToSecretKeySpec(final String data) throws Exception {
    final byte[] encoded = Hex.decodeHex(data.toCharArray());
    this.keySpec = new SecretKeySpec(encoded, ENCRYPTION_ALGORITHM);
    return this.keySpec;
}

From source file:eu.peppol.security.OxalisCipherConverter.java

private byte[] encodedBytesFromHexString(String wrappedSymmetricKeyAsHexString) {
    byte[] encodedBytes;

    try {//from   w w  w .j  av a 2  s .  c  o m
        encodedBytes = Hex.decodeHex(wrappedSymmetricKeyAsHexString.toCharArray());
    } catch (DecoderException e) {
        throw new IllegalArgumentException(
                "Unable to decode hex string " + wrappedSymmetricKeyAsHexString + "; " + e.getMessage(), e);
    }
    return encodedBytes;
}