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

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

Introduction

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

Prototype

public static String encodeHexString(byte[] data) 

Source Link

Document

Converts an array of bytes into a String representing the hexadecimal values of each byte in order.

Usage

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

@Test
public void testExtractSeptett() throws Exception {
    byte[] testBuffer1 = Hex.decodeHex("07014c008201ff00b822f60000000000".toCharArray());
    byte[] testBuffer2 = new byte[34];
    Header.extractSeptett(testBuffer1, 0, 4, testBuffer2, 10);
    Header.extractSeptett(testBuffer1, 4, 4, testBuffer2, 16);
    Header.extractSeptett(testBuffer1, 8, 4, testBuffer2, 22);
    Header.extractSeptett(testBuffer1, 12, 4, testBuffer2, 28);
    assertEquals("07014c00000002017f000500382276000500000000000000",
            Hex.encodeHexString(testBuffer2).substring(20));
}

From source file:com.tremolosecurity.saml.Saml2Assertion.java

public String generateSaml2Response() throws Exception {
    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);//  ww  w .  j a v a 2s .co m

    StringBuffer b = new StringBuffer();
    b.append('f').append(Hex.encodeHexString(idBytes));
    String id = b.toString();

    Assertion assertion = null;

    if (this.signAssertion) {
        AssertionBuilder assertionBuilder = new AssertionBuilder();
        assertion = assertionBuilder.buildObject();
        assertion.setDOM(this.generateSignedAssertion(id));

    } else {
        assertion = this.generateAssertion(id);
    }

    random.nextBytes(idBytes);

    b.setLength(0);
    b.append('f').append(Hex.encodeHexString(idBytes));
    id = b.toString();

    //assertion.setID(id);
    ResponseBuilder rb = new ResponseBuilder();
    Response r = rb.buildObject();
    r.setID(id);
    r.setIssueInstant(this.issueInstant);
    r.setDestination(recepient);

    IssuerBuilder issuerBuilder = new IssuerBuilder();

    Issuer issuer = issuerBuilder.buildObject();

    issuer.setValue(this.issuer);
    r.setIssuer(issuer);

    StatusBuilder statusBuilder = new StatusBuilder();
    Status s = statusBuilder.buildObject();
    StatusCodeBuilder scb = new StatusCodeBuilder();
    StatusCode sc = scb.buildObject();
    sc.setValue(StatusCode.SUCCESS);
    s.setStatusCode(sc);
    r.setStatus(s);

    if (this.encAssertion) {
        DataEncryptionParameters encryptionParameters = new DataEncryptionParameters();
        encryptionParameters.setAlgorithm(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128);

        KeyEncryptionParameters keyEncryptionParameters = new KeyEncryptionParameters();

        keyEncryptionParameters.setEncryptionCredential(new BasicX509Credential(this.encCert));
        keyEncryptionParameters.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP);

        Encrypter encrypter = new Encrypter(encryptionParameters, keyEncryptionParameters);
        encrypter.setKeyPlacement(Encrypter.KeyPlacement.INLINE);

        try {
            EncryptedAssertion encryptedAssertion = encrypter.encrypt(assertion);
            r.getEncryptedAssertions().add(encryptedAssertion);
        } catch (EncryptionException e) {
            throw new RuntimeException(e);
        }

        /*
                
        Credential keyEncryptionCredential = CredentialSupport.getSimpleCredential(this.encCert.getPublicKey(), null);
        EncryptionParameters encParams = new EncryptionParameters();
        encParams.setAlgorithm(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128);
                 
        KeyEncryptionParameters kekParams = new KeyEncryptionParameters();
        kekParams.setEncryptionCredential(keyEncryptionCredential);
        kekParams.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP);
        KeyInfoGeneratorFactory kigf =
            Configuration.getGlobalSecurityConfiguration()
            .getKeyInfoGeneratorManager().getDefaultManager()
            .getFactory(keyEncryptionCredential);
        kekParams.setKeyInfoGenerator(kigf.newInstance());
                 
        Encrypter samlEncrypter = new Encrypter(encParams, kekParams);
        samlEncrypter.setKeyPlacement(KeyPlacement.PEER);
                 
        try {
            EncryptedAssertion encryptedAssertion = samlEncrypter.encrypt(assertion);
            r.getEncryptedAssertions().add(encryptedAssertion);
        } catch (EncryptionException e) {
            throw new Exception("Could not encrypt response",e);
        }
          */
    } else {
        r.getAssertions().add(assertion);
    }

    if (this.signResponse) {
        if (this.sigCert == null) {
            throw new Exception("No signature key found");
        }
        BasicX509Credential signingCredential = CredentialSupport.getSimpleCredential(this.sigCert,
                this.sigKey);

        Signature signature = OpenSAMLUtils.buildSAMLObject(Signature.class);

        //SecurityHelper.prepareSignatureParams(signature, signingCredential, null, null);

        signature.setSigningCredential(signingCredential);
        signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
        signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

        r.setSignature(signature);
        //Element e = Configuration.getMarshallerFactory().getMarshaller(r).marshall(r); 

        try {
            XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(r).marshall(r);
        } catch (MarshallingException e) {
            throw new RuntimeException(e);
        }

        Signer.signObject(signature);
    }

    // Get the Subject marshaller
    Marshaller marshaller = new ResponseMarshaller();

    // Marshall the Subject
    Element responseElement = marshaller.marshall(r);

    return net.shibboleth.utilities.java.support.xml.SerializeSupport.nodeToString(responseElement);

}

From source file:com.envirover.spl.SPLGroungControlTest.java

@Test
public void testMOMessagePipeline()
        throws URISyntaxException, ClientProtocolException, IOException, InterruptedException {
    System.out.println("MO TEST: Testing MO message pipeline...");

    Thread.sleep(1000);/*from  ww  w.j a va 2  s .c  o  m*/

    Thread mavlinkThread = new Thread(new Runnable() {
        public void run() {
            Socket client = null;

            try {
                System.out.printf("MO TEST: Connecting to tcp://%s:%d",
                        InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort());
                System.out.println();

                client = new Socket(InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort());

                System.out.printf("MO TEST: Connected tcp://%s:%d", InetAddress.getLocalHost().getHostAddress(),
                        config.getMAVLinkPort());
                System.out.println();

                Parser parser = new Parser();
                DataInputStream in = new DataInputStream(client.getInputStream());
                while (true) {
                    MAVLinkPacket packet;
                    do {
                        int c = in.readUnsignedByte();
                        packet = parser.mavlink_parse_char(c);
                    } while (packet == null);

                    System.out.printf("MO TEST: MAVLink message received: msgid = %d", packet.msgid);
                    System.out.println();

                    Thread.sleep(100);
                }
            } catch (InterruptedException ex) {
                return;
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    mavlinkThread.start();

    HttpClient httpclient = HttpClients.createDefault();

    URIBuilder builder = new URIBuilder();
    builder.setScheme("http");
    builder.setHost(InetAddress.getLocalHost().getHostAddress());
    builder.setPort(config.getRockblockPort());
    builder.setPath(config.getHttpContext());

    URI uri = builder.build();
    HttpPost httppost = new HttpPost(uri);

    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    params.add(new BasicNameValuePair("imei", config.getRockBlockIMEI()));
    params.add(new BasicNameValuePair("momsn", "12345"));
    params.add(new BasicNameValuePair("transmit_time", "12-10-10 10:41:50"));
    params.add(new BasicNameValuePair("iridium_latitude", "52.3867"));
    params.add(new BasicNameValuePair("iridium_longitude", "0.2938"));
    params.add(new BasicNameValuePair("iridium_cep", "9"));
    params.add(new BasicNameValuePair("data", Hex.encodeHexString(getSamplePacket().encodePacket())));
    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    // Execute and get the response.
    System.out.printf("MO TEST: Sending test message to %s", uri.toString());
    System.out.println();

    HttpResponse response = httpclient.execute(httppost);

    if (response.getStatusLine().getStatusCode() != 200) {
        fail(String.format("RockBLOCK HTTP message handler status code = %d.",
                response.getStatusLine().getStatusCode()));
    }

    HttpEntity entity = response.getEntity();

    if (entity != null) {
        InputStream responseStream = entity.getContent();
        try {
            String responseString = IOUtils.toString(responseStream);
            System.out.println(responseString);
        } finally {
            responseStream.close();
        }
    }

    Thread.sleep(1000);

    mavlinkThread.interrupt();
    System.out.println("MO TEST: Complete.");
}

From source file:epgtools.dumpchannellistfromts.Main.java

public void start(String[] args) throws ParseException {
    final String fileName;
    final Long limit;

    final Option directoryNameOption = Option.builder("d").required().longOpt("directoryname")
            .desc("??").hasArg().type(String.class).build();

    final Option limitOption = Option.builder("l").required(false).longOpt("limit")
            .desc("??(???????EOF??)").hasArg()
            .type(Long.class).build();

    final Option destFileNameOption = Option.builder("f").required().longOpt("destname")
            .desc("???").hasArg().type(String.class).build();

    Options opts = new Options();
    opts.addOption(directoryNameOption);
    opts.addOption(limitOption);//from  w w  w  .  j  a  va 2 s  .  com
    opts.addOption(destFileNameOption);
    CommandLineParser parser = new DefaultParser();

    HelpFormatter help = new HelpFormatter();
    CommandLine cl;
    try {
        cl = parser.parse(opts, args);
    } catch (ParseException ex) {
        LOG.fatal("??????", ex);
        help.printHelp("My Java Application", opts);
        throw ex;
    }

    final File dirName = new File(cl.getOptionValue(directoryNameOption.getOpt()));
    if (!dirName.isDirectory()) {
        throw new IllegalArgumentException(
                "??????????? = "
                        + dirName.getAbsolutePath());
    }
    LOG.info("?? = " + dirName.getAbsolutePath());

    Long xl = null;
    try {
        if (cl.hasOption(limitOption.getOpt())) {
            xl = Long.parseUnsignedLong(cl.getOptionValue(limitOption.getOpt()));
        }
    } catch (NumberFormatException e) {
        LOG.error(e);
        throw new IllegalArgumentException("????????");
    } finally {
        limit = xl;
        LOG.info("?? = " + limit);
    }

    final File destFile = new File(cl.getOptionValue(destFileNameOption.getOpt()));
    LOG.info("??? = " + destFile.getAbsolutePath());

    List<File> files = new TsFileSeeker(dirName).seek();

    LOG.info("?? = " + files.size());

    final PhysicalChannelNumberRecordBuilder bu = new PhysicalChannelNumberRecordBuilder();
    final Set<PhysicalChannelNumberRecord> records = Collections.synchronizedSet(new TreeSet<>());
    //NIT?
    for (File f : files) {
        SectionLoader loader = new SectionLoader(f, limit, RESERVED_PROGRAM_ID.NIT.getPids());
        try {
            Map<Integer, List<Section>> pids_sections = loader.load();
            for (Integer k : pids_sections.keySet()) {
                for (Section s : pids_sections.get(k)) {
                    if (s.checkCRC() != Section.CRC_STATUS.NO_CRC_ERROR) {
                        throw new IllegalArgumentException(
                                "CRC?? = " + Hex.encodeHexString(s.getData()));
                    } else if (s.getTable_id_const() != TABLE_ID.NIT_THIS_NETWORK) {
                        throw new IllegalArgumentException(
                                "?NIT????? = "
                                        + Hex.encodeHexString(s.getData()));
                    } else {
                        NetworkInformationTableBody nitbody = (NetworkInformationTableBody) s.getSectionBody();
                        bu.setNetworkId(nitbody.getNetwork_id());
                        for (Descriptor d1 : nitbody.getDescriptors_loop().getDescriptors_loopList()) {
                            if (d1.getDescriptor_tag_const() == DESCRIPTOR_TAG.NETWORK_NAME_DESCRIPTOR) {
                                final NetworkNameDescriptor nnd = (NetworkNameDescriptor) d1;
                                bu.setNetworkName(nnd.getChar_String());
                            }
                        }
                        for (TransportStreamLoop tsLoop : nitbody.getTransport_streams_loop()) {
                            bu.setTransportStreamId(tsLoop.getTransport_stream_id());
                            bu.setOriginalNetworkId(tsLoop.getOriginal_network_id());
                            for (Descriptor desc : tsLoop.getDescriptors_loop().getDescriptors_loopList()) {
                                if (desc.getDescriptor_tag_const() == DESCRIPTOR_TAG.SERVICE_LIST_DESCRIPTOR) {
                                    ServiceListDescriptor sd = (ServiceListDescriptor) desc;
                                    List<Service> svList = sd.getServiceList();
                                    for (Service service : svList) {
                                        if (service.getService_type_Enum() == SERVICE_TYPE.DIGITAL_TV_SERVICE) {
                                            bu.setServiceId(service.getService_id());

                                            if (bu.getOriginalNetworkId() < 0x10) {
                                                //BS
                                                bu.setPhysicalChannelNumber(bu.getServiceId());
                                            } else {
                                                //          
                                                bu.setPhysicalChannelNumber(
                                                        Integer.valueOf(this.getNameWithoutExtension(f)));
                                            }

                                            records.add(bu.build());
                                        }
                                    }

                                }
                            }
                        }
                    }
                }
            }
        } catch (FileNotFoundException ex) {
            LOG.info("????? = " + f.getAbsolutePath(), ex);
        }
    }

    //        for (PhysicalChannelNumberRecord rec : records) {
    //            LOG.info(rec);
    //        }
    //        
    //???????
    List<PhysicalChannelNumberRecord> nl = new ArrayList<>();
    nl.addAll(records);
    CsvManager csvManager = CsvManagerFactory.newCsvManager();
    LOG.info(destFile.getAbsolutePath());
    try {
        csvManager.save(nl, PhysicalChannelNumberRecord.class).to(destFile, "UTF-8");
    } catch (IOException ex) {
        LOG.fatal("???????? = " + destFile.getAbsolutePath(), ex);
    }

}

From source file:net.solarnetwork.node.rfxcom.test.CommandMessageTest.java

@Test
public void encodeSaveSettingsCommand() {
    CommandMessage msg = new CommandMessage(Command.SaveSettings, (short) 31);
    assertNull("Data", msg.getData());
    final byte[] packet = msg.getMessagePacket();
    log.debug("Got packet: " + Hex.encodeHexString(packet));
    assertNotNull("Packet", packet);
    assertArrayEquals(TestUtils.bytesFromHexString("0D 00 00 1F 06 00 00 00 00 00 00 00 00 00"), packet);
}

From source file:com.consol.citrus.ws.message.SoapAttachment.java

/**
 * Get the content body.//from  w  w w.j  av  a  2s  .co  m
 * @return the content
 */
public String getContent() {
    if (resolvedContent != null) {
        return resolvedContent;
    }

    if (StringUtils.hasText(content)) {
        return content;
    }

    if (getDataHandler().getContentType().startsWith("text")) {
        try {
            return FileUtils.readToString(getDataHandler().getInputStream(), Charset.forName(charsetName));
        } catch (IOException e) {
            throw new CitrusRuntimeException("Failed to read SOAP attachment file resource", e);
        }
    } else {
        try {
            byte[] binaryData = FileUtils
                    .readToString(getDataHandler().getInputStream(), Charset.forName(charsetName))
                    .getBytes(Charset.forName(charsetName));
            if (encodingType.equals(SoapAttachment.ENCODING_BASE64_BINARY)) {
                return Base64.encodeBase64String(binaryData);
            } else if (encodingType.equals(SoapAttachment.ENCODING_HEX_BINARY)) {
                return Hex.encodeHexString(binaryData).toUpperCase();
            } else {
                throw new CitrusRuntimeException(String.format(
                        "Unsupported encoding type '%s' for SOAP attachment - choose one of %s or %s",
                        encodingType, SoapAttachment.ENCODING_BASE64_BINARY,
                        SoapAttachment.ENCODING_HEX_BINARY));
            }
        } catch (IOException e) {
            throw new CitrusRuntimeException("Failed to read SOAP attachment data input stream", e);
        }
    }
}

From source file:com.amazon.janusgraph.diskstorage.dynamodb.AbstractDynamoDBStore.java

protected String encodeKeyForLog(StaticBuffer key) {
    if (null == key) {
        return "";
    }/*from w ww.  j a  v  a2 s .com*/
    return Constants.HEX_PREFIX + Hex.encodeHexString(key.asByteBuffer().array());
}

From source file:com.cubeia.games.poker.CreateUser.java

private String getPassword() {
    if (hashPassword) {
        try {//from   w w w .  ja  v a  2 s.  c  o m
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.reset();
            md.update(password.getBytes("ISO-8859-1"));
            byte[] bytes = md.digest();
            return Hex.encodeHexString(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else {
        return password;
    }
}

From source file:libepg.util.bytearray.ByteArraySplitterTest.java

/**
 * Test of splitByLengthField method, of class ByteArraySplitter.
 *
 * @throws org.apache.commons.codec.DecoderException
 *///  w w w.j a  v a  2s.  c o m
@Test
public void testSplitByLengthField_4args() throws DecoderException {
    LOG.debug("splitByLengthField");
    byte[] src = Hex.decodeHex(
            "0408f31020481201000f0e4e484b451d461d6c310f456c357ec10184cf0701fe08f00104080409f3001c481201000f0e4e484b451d461d6c320f456c357ec10184cf0302fe08040af3001c481201000f0e4e484b451d461d6c330f456c357ec10184cf0302fe080588e5001f480ec0000b0e4e484b0f374842530e32c10188cf0a030e4e484b0f215d0e32"
                    .toCharArray());
    int lengthFieldPosition = 4;
    int lengthFieldLength = 2;
    List<byte[]> expResult = new ArrayList<>();
    expResult.add(Hex.decodeHex(
            "0408f31020481201000f0e4e484b451d461d6c310f456c357ec10184cf0701fe08f0010408".toCharArray()));//??????
    expResult.add(
            Hex.decodeHex("0409f3001c481201000f0e4e484b451d461d6c320f456c357ec10184cf0302fe08".toCharArray()));
    expResult.add(
            Hex.decodeHex("040af3001c481201000f0e4e484b451d461d6c330f456c357ec10184cf0302fe08".toCharArray()));
    expResult.add(Hex.decodeHex(
            "0588e5001f480ec0000b0e4e484b0f374842530e32c10188cf0a030e4e484b0f215d0e32".toCharArray()));
    List<byte[]> result = ByteArraySplitter.splitByLengthField(src, lengthFieldPosition, lengthFieldLength,
            (x) -> x & 0x0FFF);

    Iterator<byte[]> it_result = result.iterator();
    Iterator<byte[]> it_expResult = expResult.iterator();
    while (it_result.hasNext() && it_expResult.hasNext()) {
        StringBuilder s = new StringBuilder();
        byte[] res = it_result.next();
        byte[] expRes = it_expResult.next();
        if (Arrays.equals(res, expRes) == false) {
            fail("???????");
        } else {
            s.append(Hex.encodeHexString(expRes));
            s.append(" = ");
            s.append(Hex.encodeHexString(res));
            LOG.debug(s.toString());
        }
    }
}

From source file:io.fabric8.maven.docker.access.log.LogRequestor.java

private boolean readStreamFrame(InputStream is) throws IOException, LogCallback.DoneException {
    // Read the header, which is composed of eight bytes. The first byte is an integer
    // indicating the stream type (0 = stdin, 1 = stdout, 2 = stderr), the next three are thrown
    // out, and the final four are the size of the remaining stream as an integer.
    ByteBuffer headerBuffer = ByteBuffer.allocate(8);
    headerBuffer.order(ByteOrder.BIG_ENDIAN);
    try {/* www.j  a va 2  s  . co  m*/
        this.readFully(is, headerBuffer.array());
    } catch (NoBytesReadException e) {
        // Not bytes read for stream. Return false to stop consuming stream.
        return false;
    } catch (EOFException e) {
        throw new IOException("Failed to read log header. Could not read all 8 bytes. " + e.getMessage(), e);
    }

    // Grab the stream type (stdout, stderr, stdin) from first byte and throw away other 3 bytes.
    int type = headerBuffer.get();

    // Skip three bytes, then read size from remaining four bytes.
    int size = headerBuffer.getInt(4);

    // Ignore empty messages and keep reading.
    if (size <= 0) {
        return true;
    }

    // Read the actual message
    ByteBuffer payload = ByteBuffer.allocate(size);
    try {
        ByteStreams.readFully(is, payload.array());
    } catch (EOFException e) {
        throw new IOException("Failed to read log message. Could not read all " + size + " bytes. "
                + e.getMessage() + " [ Header: " + Hex.encodeHexString(headerBuffer.array()) + "]", e);
    }

    String message = Charsets.UTF_8.newDecoder().decode(payload).toString();
    callLogCallback(type, message);
    return true;
}