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:com.bitbreeds.webrtc.datachannel.DataChannelImpl.java

public DataChannelImpl(PeerConnection parent) throws IOException {
    logger.info("Initializing {}", this.getClass().getName());
    this.dtlsServer = new WebrtcDtlsServer(parent.getKeyStoreInfo());
    this.parent = parent;
    this.channel = new DatagramSocket();
    this.channel.setReceiveBufferSize(16000000);
    this.receiveBufferSize = this.channel.getReceiveBufferSize();
    this.channel.setSendBufferSize(16000000);
    this.sendBufferSize = this.channel.getSendBufferSize();
    //this.channel.setReuseAddress(true);
    this.port = channel.getLocalPort();
    this.serverProtocol = new DTLSServerProtocol(new SecureRandom());
    this.mode = ConnectionMode.BINDING;

    /**/*from   w ww  . j  av a  2s. com*/
     * Print monitoring information
     */
    this.monitor = () -> {
        while (running && channel.isBound()) {
            try {
                Thread.sleep(3000);
                sctpService.runMonitoring();
            } catch (Exception e) {
                logger.error("Logging error", e);
            }
        }
    };

    /**
     * Create heartbeat message
     */
    this.heartBeat = () -> {
        while (running && channel.isBound()) {
            try {
                Thread.sleep(5000);
                byte[] beat = sctpService.createHeartBeat();
                logger.debug("Sending heartbeat: " + Hex.encodeHexString(beat));
                putDataOnWire(beat);
            } catch (Exception e) {
                logger.error("HeartBeat error: ", e);
            }
        }
    };

    /**
     * Acknowledge received data
     */
    this.sackSender = () -> {
        while (running && channel.isBound()) {
            try {
                Thread.sleep(1); //sleep to not go ham on cpu
                logger.trace("Creating sack:");
                byte[] beat = sctpService.createSackMessage();
                if (beat.length > 0) {
                    logger.trace("Sending sack: " + Hex.encodeHexString(beat));
                    putDataOnWire(beat);
                } else {
                    logger.trace("Already on latest sack, no send");
                }

            } catch (Exception e) {
                logger.error("Sack error: ", e);
            }

        }
    };

    /**
     * Resends non acknowledged sent messages
     */
    this.reSender = () -> {
        while (running && channel.isBound() && !channel.isClosed()) {
            try {
                Thread.sleep(250);
                List<byte[]> msgs = sctpService.getMessagesForResend();
                if (!msgs.isEmpty()) {
                    msgs.forEach(i -> {
                        try {
                            Thread.sleep(1); //Sleep to let others work a bit
                            logger.debug("Resending data: " + Hex.encodeHexString(i));
                            putDataOnWire(i);
                        } catch (InterruptedException e) {
                            logger.error("Resend error: ", e);
                        }
                    });
                }
            } catch (Exception e) {
                logger.error("Resend error: ", e);
            }
        }
    };
}

From source file:gobblin.util.guid.Guid.java

/**
 * Serializes the guid into a hex string. The original {@link Guid} can be recovered using {@link #deserialize}.
 *///ww w. j a  v  a2s. c o  m
@Override
public String toString() {
    return Hex.encodeHexString(this.sha);
}

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

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

From source file:com.mweagle.tereus.commands.evaluation.common.LambdaUtils.java

public String createFunction(final String logicalResourceName, final String lambdaSourceRoot,
        final String bucketName, final String s3KeyName)
        throws IOException, InterruptedException, NoSuchAlgorithmException {

    // Build it, zip it, and upload it.  Return:
    /*//from w w w  .  ja  v  a  2  s. co m
    {
      "S3Bucket" : String,
      "S3Key" : String,
      "S3ObjectVersion" : "TODO - not yet implemented"
    }
    */
    this.logger.info("Looking for source {} relative to {}", lambdaSourceRoot, templateRoot);
    final String lambdaDir = this.templateRoot.resolve(lambdaSourceRoot).normalize().toAbsolutePath()
            .toString();
    final Path lambdaPath = Paths.get(lambdaDir);

    // Build command?
    final Optional<String> buildCommand = lambdaBuildCommand(lambdaDir);
    if (buildCommand.isPresent()) {
        this.logger.info("{} Lambda source: {}", buildCommand.get(), lambdaDir);
        try {
            Runtime rt = Runtime.getRuntime();
            Process pr = rt.exec(buildCommand.get(), null, new File(lambdaDir));
            this.logger.info("Waiting for `{}` to complete", buildCommand.get());

            final int buildExitCode = pr.waitFor();
            if (0 != buildExitCode) {
                logger.error("Failed to `{}`: {}", buildCommand.get(), buildExitCode);
                throw new IOException(buildCommand.get() + " failed for: " + lambdaDir);
            }
        } catch (Exception ex) {
            final String processPath = System.getenv("PATH");
            this.logger.error("`{}` failed. Confirm that PATH contains the required executable.",
                    buildCommand.get());
            this.logger.error("$PATH: {}", processPath);
            throw ex;
        }
    } else {
        this.logger.debug("No additional Lambda build file detected");
    }

    Path lambdaSource = null;
    boolean cleanupLambdaSource = false;
    MessageDigest md = MessageDigest.getInstance("SHA-256");

    try {
        final BiPredicate<Path, java.nio.file.attribute.BasicFileAttributes> matcher = (path, fileAttrs) -> {
            final String fileExtension = com.google.common.io.Files.getFileExtension(path.toString());
            return (fileExtension.toLowerCase().compareTo("jar") == 0);
        };

        // Find/compress the Lambda source
        // If there is a JAR file in the source root, then use that for the upload
        List<Path> jarFiles = Files.find(lambdaPath, 1, matcher).collect(Collectors.toList());

        if (!jarFiles.isEmpty()) {
            Preconditions.checkArgument(jarFiles.size() == 1, "More than 1 JAR file detected in directory: {}",
                    lambdaDir);
            lambdaSource = jarFiles.get(0);
            md.update(Files.readAllBytes(lambdaSource));
        } else {
            lambdaSource = Files.createTempFile("lambda-", ".zip");
            this.logger.info("Zipping lambda source code: {}", lambdaSource.toString());
            final FileOutputStream os = new FileOutputStream(lambdaSource.toFile());
            final ZipOutputStream zipOS = new ZipOutputStream(os);
            createStableZip(zipOS, lambdaPath, lambdaPath, md);
            zipOS.close();
            this.logger.info("Compressed filesize: {} bytes", lambdaSource.toFile().length());
            cleanupLambdaSource = true;
        }

        // Upload it
        final String sourceHash = Hex.encodeHexString(md.digest());
        this.logger.info("Lambda source hash: {}", sourceHash);
        if (!s3KeyName.isEmpty()) {
            this.logger.warn(
                    "User supplied S3 keyname overrides content-addressable name. Automatic updates disabled.");
        }
        final String keyName = !s3KeyName.isEmpty() ? s3KeyName
                : String.format("%s-lambda-%s.%s", logicalResourceName, sourceHash,
                        com.google.common.io.Files.getFileExtension(lambdaSource.toString()));
        JsonObject jsonObject = new JsonObject();
        jsonObject.add("S3Bucket", new JsonPrimitive(bucketName));
        jsonObject.add("S3Key", new JsonPrimitive(keyName));

        // Upload it to s3...
        final FileInputStream fis = new FileInputStream(lambdaSource.toFile());
        try (S3Resource resource = new S3Resource(bucketName, keyName, fis,
                Optional.of(lambdaSource.toFile().length()))) {
            this.logger.info("Source payload S3 URL: {}", resource.getS3Path());

            if (resource.exists()) {
                this.logger.info("Source {} already uploaded to S3", keyName);
            } else if (!this.dryRun) {
                Optional<String> result = resource.upload();
                this.logger.info("Uploaded Lambda source to: {}", result.get());
                resource.setReleased(true);
            } else {
                this.logger.info("Dry run requested (-n/--noop). Lambda payload upload bypassed.");
            }
        }
        final Gson serializer = new GsonBuilder().disableHtmlEscaping().enableComplexMapKeySerialization()
                .create();
        return serializer.toJson(jsonObject);
    } finally {
        if (cleanupLambdaSource) {
            this.logger.debug("Deleting temporary file: {}", lambdaSource.toString());
            Files.deleteIfExists(lambdaSource);
        }
    }
}

From source file:com.tcloud.bee.key.server.service.impl.KeyManageServiceImpl.java

@Override
public QueryResult createKey(Param param, String owner)
        throws NoSuchAlgorithmException, FileNotFoundException, IOException {
    logger.info("User is trying to create key. userName:" + owner + ", keyName:" + param.getKeyName());
    File newKeyfile = new File(env.getProperty("keyfile.path") + param.getKeyName());
    if (newKeyfile.exists()) {
        logger.info("keyName \"" + param.getKeyName() + "\" exists, please choose another keyName.");
        return new QueryResult(BeeConstants.ResponseStatus.FAIL,
                BeeConstants.ErrorMap.get(BeeConstants.ResponseCode.ERROR_KM_KEYNAME_EXISTS), null);
    }//from   ww w .j  a  v a  2  s .  c o m

    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(256);
    SecretKey secretKey = keyGen.generateKey();
    String hexkey = Hex.encodeHexString(secretKey.getEncoded());

    Properties prop = new Properties();
    prop.setProperty("owner", owner);
    prop.setProperty("keyName", param.getKeyName());
    prop.setProperty("hexkey", hexkey);
    prop.setProperty("users", param.getUsers());

    File keyFileFolder = new File(env.getProperty("keyfile.path"));
    if (!keyFileFolder.exists()) {
        keyFileFolder.mkdirs();
        Runtime.getRuntime().exec("chmod 700 " + env.getProperty("keyfile.path"));
    }
    prop.store(new FileOutputStream(env.getProperty("keyfile.path") + param.getKeyName()), null);
    Runtime.getRuntime().exec("chmod 600 " + env.getProperty("keyfile.path") + param.getKeyName());
    logger.info("save keyfile \"{}\" to keyfile folder: {}", param.getKeyName(),
            env.getProperty("keyfile.path"));

    return new QueryResult(BeeConstants.ResponseStatus.SUCCESS, "Key(" + param.getKeyName() + ") created",
            null);
}

From source file:dumptspacket.Main.java

public void start(String[] args) throws org.apache.commons.cli.ParseException {
    final String fileName;
    final Long limit;
    final Set<Integer> pids;

    System.out.println("args   : " + dumpArgs(args));

    final Option fileNameOption = Option.builder("f").required().longOpt("filename").desc("ts??")
            .hasArg().type(String.class).build();

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

    final Option pidsOption = Option.builder("p").required().longOpt("pids")
            .desc("pid(?16?)").type(String.class).hasArgs().build();

    Options opts = new Options();
    opts.addOption(fileNameOption);/*from w w w . j  a  v  a2s  .c o m*/
    opts.addOption(limitOption);
    opts.addOption(pidsOption);
    CommandLineParser parser = new DefaultParser();
    CommandLine cl;
    HelpFormatter help = new HelpFormatter();

    try {

        // parse options
        cl = parser.parse(opts, args);

        // handle interface option.
        fileName = cl.getOptionValue(fileNameOption.getOpt());
        if (fileName == null) {
            throw new ParseException("????????");
        }

        // handlet destination option.
        Long xl = null;
        try {
            xl = Long.parseUnsignedLong(cl.getOptionValue(limitOption.getOpt()));
        } catch (NumberFormatException e) {
            xl = null;
        } finally {
            limit = xl;
        }

        Set<Integer> x = new HashSet<>();
        List<String> ls = new ArrayList<>();
        ls.addAll(Arrays.asList(cl.getOptionValues(pidsOption.getOpt())));
        for (String s : ls) {
            try {
                x.add(Integer.parseUnsignedInt(s, 16));
            } catch (NumberFormatException e) {
                throw new ParseException(e.getMessage());
            }
        }
        pids = Collections.unmodifiableSet(x);

        System.out.println("Starting application...");
        System.out.println("filename   : " + fileName);
        System.out.println("limit : " + limit);
        System.out.println("pids : " + dumpSet(pids));

        // your code
        TsReader reader;
        if (limit == null) {
            reader = new TsReader(new File(fileName), pids);
        } else {
            reader = new TsReader(new File(fileName), pids, limit);
        }

        Map<Integer, List<TsPacketParcel>> ret = reader.getPackets();
        try {
            for (Integer pid : ret.keySet()) {

                FileWriter writer = new FileWriter(fileName + "_" + Integer.toHexString(pid) + ".txt");

                for (TsPacketParcel par : ret.get(pid)) {
                    String text = Hex.encodeHexString(par.getPacket().getData());
                    writer.write(text + "\n");

                }
                writer.flush();
                writer.close();
            }
        } catch (IOException ex) {
            LOG.fatal("", ex);
        }

    } catch (ParseException e) {
        // print usage.
        help.printHelp("My Java Application", opts);
        throw e;
    } catch (FileNotFoundException ex) {
        LOG.fatal("", ex);
    }
}

From source file:me.footlights.core.crypto.Fingerprint.java

String hex() {
    return Hex.encodeHexString(bytes.array());
}

From source file:com.weblyzard.lib.string.nilsimsa.Nilsimsa.java

/**
 * Compute the Nilsimsa hexDigest for the given String.
 * @param s: the String to hash//from   w ww . j a  v a2  s.c  om
 * @return the Nilsimsa hexdigest.
 */

public String hexdigest(String s) {
    return Hex.encodeHexString(digest(s));
}

From source file:com.exalttech.trex.ui.views.streams.viewer.PacketParser.java

/**
 * Extract packet info/*from w  w w . j a  v a2 s.co m*/
 *
 * @param packet
 * @return
 */
private PacketInfo extractPacketInfo(Packet packet) {

    if (packet != null) {
        packetInfo.setPacketHex(formatHex(DatatypeConverter.printHexBinary(packet.getRawData())));
        packetInfo.setPacketRawData(formatPayLoad(new String(packet.getRawData())));
    }

    // defien whether packet has vlan or not
    if (packet.get(Dot1qVlanTagPacket.class) != null) {
        packetInfo.setVlanPacket(true);
    }
    // If the packet has Ethernet
    if (packet.get(EthernetPacket.class) != null) {
        packetInfo.setEthernetHex(
                getHeaderOffset(packet.get(EthernetPacket.class).getHeader().toHexString().toUpperCase()));
        packetInfo.setEthernetRawData(new String());
        packetInfo.setDestMac(packet.get(EthernetPacket.class).getHeader().getDstAddr().toString());
        packetInfo.setSrcMac(packet.get(EthernetPacket.class).getHeader().getSrcAddr().toString());
    }

    // if the packet has IPV4
    if (packet.get(IpV4Packet.class) != null) {
        packetInfo.setIpv4Hex(
                getHeaderOffset(packet.get(IpV4Packet.class).getHeader().toHexString().toUpperCase()));
        packetInfo.setIpv4RawData(new String());
        packetInfo.setDestIpv4(packet.get(IpV4Packet.class).getHeader().getDstAddr().getHostAddress());
        packetInfo.setSrcIpv4(packet.get(IpV4Packet.class).getHeader().getSrcAddr().getHostAddress());
    }

    // if the packet has TCP
    if (packet.get(TcpPacket.class) != null) {
        packetInfo.setL4Name("TCP");
        packetInfo
                .setL4Hex(getHeaderOffset(packet.get(TcpPacket.class).getHeader().toHexString().toUpperCase()));
        packetInfo.setL4RawData(new String());
        if (packet.get(TcpPacket.class).getPayload() != null) {
            packetInfo.setPacketPayLoad(getHeaderOffset(
                    spaceHex(Hex.encodeHexString(packet.get(TcpPacket.class).getPayload().getRawData()))));
        } else {
            packetInfo.setPacketPayLoad(null);
        }
    }

    // if the packet has UDP
    if (packet.get(UdpPacket.class) != null) {
        packetInfo.setL4Name("UDP");
        packetInfo
                .setL4Hex(getHeaderOffset(packet.get(UdpPacket.class).getHeader().toHexString().toUpperCase()));
        packetInfo.setL4RawData(new String());

        if (packet.get(UdpPacket.class).getPayload() != null) {
            packetInfo.setPacketPayLoad(getHeaderOffset(
                    spaceHex(Hex.encodeHexString(packet.get(UdpPacket.class).getPayload().getRawData()))));
        } else {
            packetInfo.setPacketPayLoad(null);
        }
    }
    return packetInfo;
}

From source file:com.tremolosecurity.unison.google.u2f.U2FServerUnison.java

@Override
public SecurityKeyData processRegistrationResponse(RegistrationResponse registrationResponse,
        long currentTimeInMillis) throws U2FException {
    log.debug(">> processRegistrationResponse");

    String sessionId = registrationResponse.getSessionId();
    String clientDataBase64 = registrationResponse.getClientData();
    String rawRegistrationDataBase64 = registrationResponse.getRegistrationData();

    log.debug(">> rawRegistrationDataBase64: " + rawRegistrationDataBase64);
    EnrollSessionData sessionData = dataStore.getEnrollSessionData(sessionId);

    if (sessionData == null) {
        throw new U2FException("Unknown session_id");
    }//from w w  w .j  av  a 2  s .  c  o m

    String appId = sessionData.getAppId();
    String clientData = new String(Base64.decodeBase64(clientDataBase64));
    byte[] rawRegistrationData = Base64.decodeBase64(rawRegistrationDataBase64);
    if (log.isDebugEnabled()) {
        log.debug("-- Input --");
        log.debug("  sessionId: " + sessionId);
        log.debug("  challenge: " + Hex.encodeHexString(sessionData.getChallenge()));
        log.debug("  accountName: " + sessionData.getAccountName());
        log.debug("  clientData: " + clientData);
        log.debug("  rawRegistrationData: " + Hex.encodeHexString(rawRegistrationData));
    }
    RegisterResponse registerResponse = RawMessageCodec.decodeRegisterResponse(rawRegistrationData);

    byte[] userPublicKey = registerResponse.getUserPublicKey();
    byte[] keyHandle = registerResponse.getKeyHandle();
    X509Certificate attestationCertificate = registerResponse.getAttestationCertificate();
    byte[] signature = registerResponse.getSignature();
    List<Transports> transports = null;
    try {
        transports = U2fAttestation.Parse(attestationCertificate).getTransports();
    } catch (CertificateParsingException e) {
        log.warn("Could not parse transports extension " + e.getMessage());
    }

    if (log.isDebugEnabled()) {
        log.debug("-- Parsed rawRegistrationResponse --");
        log.debug("  userPublicKey: " + Hex.encodeHexString(userPublicKey));
        log.debug("  keyHandle: " + Hex.encodeHexString(keyHandle));
        log.debug("  attestationCertificate: " + attestationCertificate.toString());
        log.debug("  transports: " + transports);
        try {
            log.debug("  attestationCertificate bytes: "
                    + Hex.encodeHexString(attestationCertificate.getEncoded()));
        } catch (CertificateEncodingException e) {
            throw new U2FException("Cannot encode certificate", e);
        }
        log.debug("  signature: " + Hex.encodeHexString(signature));
    }

    byte[] appIdSha256 = crypto.computeSha256(appId.getBytes());
    byte[] clientDataSha256 = crypto.computeSha256(clientData.getBytes());
    byte[] signedBytes = RawMessageCodec.encodeRegistrationSignedBytes(appIdSha256, clientDataSha256, keyHandle,
            userPublicKey);

    Set<X509Certificate> trustedCertificates = dataStore.getTrustedCertificates();
    boolean found = false;
    for (X509Certificate trusted : trustedCertificates) {
        try {
            attestationCertificate.verify(trusted.getPublicKey());
            found = true;
        } catch (InvalidKeyException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException
                | SignatureException e) {

        }
    }

    if (!found) {
        if (!this.requireAttestation) {
            log.warn("attestion cert is not trusted");
        } else {
            throw new U2FException("Attestation certificate is not trusted");
        }
    }

    verifyBrowserData(new JsonParser().parse(clientData), "navigator.id.finishEnrollment", sessionData);
    if (log.isDebugEnabled()) {
        log.debug("Verifying signature of bytes " + Hex.encodeHexString(signedBytes));
    }

    if (!crypto.verifySignature(attestationCertificate, signedBytes, signature)) {
        throw new U2FException("Signature is invalid");
    }

    // The first time we create the SecurityKeyData, we set the counter value to 0.
    // We don't actually know what the counter value of the real device is - but it will
    // be something bigger (or equal) to 0, so subsequent signatures will check out ok.
    SecurityKeyData securityKeyData = new SecurityKeyData(currentTimeInMillis, transports, keyHandle,
            userPublicKey, attestationCertificate, /* initial counter value */ 0);
    dataStore.addSecurityKeyData(sessionData.getAccountName(), securityKeyData);

    if (log.isDebugEnabled()) {
        log.debug("<< processRegistrationResponse");
    }

    return securityKeyData;
}