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.cloud.utils.SwiftUtil.java

static String toHexString(byte[] bytes) {
    return Hex.encodeHexString(bytes);
}

From source file:ch.cyberduck.core.aquaticprime.Receipt.java

/**
 * Verifies the App Store Receipt/*ww  w  . ja  v a2s  . com*/
 *
 * @return False if receipt validation failed.
 */
@Override
public boolean verify() {
    try {
        Security.addProvider(new BouncyCastleProvider());
        PKCS7SignedData signature = new PKCS7SignedData(
                IOUtils.toByteArray(new FileInputStream(this.getFile().getAbsolute())));

        signature.verify();
        // For additional security, you may verify the fingerprint of the root CA and the OIDs of the
        // intermediate CA and signing certificate. The OID in the Certificate Policies Extension of the
        // intermediate CA is (1 2 840 113635 100 5 6 1), and the Marker OID of the signing certificate
        // is (1 2 840 113635 100 6 11 1).

        // Extract the receipt attributes
        CMSSignedData s = new CMSSignedData(new FileInputStream(this.getFile().getAbsolute()));
        CMSProcessable signedContent = s.getSignedContent();
        byte[] originalContent = (byte[]) signedContent.getContent();
        ASN1Object asn = ASN1Object.fromByteArray(originalContent);

        byte[] opaque = null;
        String bundleIdentifier = null;
        String bundleVersion = null;
        byte[] hash = null;

        if (asn instanceof DERSet) {
            // 2 Bundle identifier      Interpret as an ASN.1 UTF8STRING.
            // 3 Application version    Interpret as an ASN.1 UTF8STRING.
            // 4 Opaque value           Interpret as a series of bytes.
            // 5 SHA-1 hash             Interpret as a 20-byte SHA-1 digest value.
            DERSet set = (DERSet) asn;
            Enumeration enumeration = set.getObjects();
            while (enumeration.hasMoreElements()) {
                Object next = enumeration.nextElement();
                if (next instanceof DERSequence) {
                    DERSequence sequence = (DERSequence) next;
                    DEREncodable type = sequence.getObjectAt(0);
                    if (type instanceof DERInteger) {
                        if (((DERInteger) type).getValue().intValue() == 2) {
                            DEREncodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                bundleIdentifier = new String(((DEROctetString) value).getOctets(), "utf-8");
                            }
                        } else if (((DERInteger) type).getValue().intValue() == 3) {
                            DEREncodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                bundleVersion = new String(((DEROctetString) value).getOctets(), "utf-8");
                            }
                        } else if (((DERInteger) type).getValue().intValue() == 4) {
                            DEREncodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                opaque = ((DEROctetString) value).getOctets();
                            }
                        } else if (((DERInteger) type).getValue().intValue() == 5) {
                            DEREncodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                hash = ((DEROctetString) value).getOctets();
                            }
                        }
                    }
                }
            }
        } else {
            log.error(String.format("Expected set of attributes for %s", asn));
            return false;
        }
        if (!StringUtils.equals("ch.sudo.cyberduck", StringUtils.trim(bundleIdentifier))) {
            log.error("Bundle identifier in ASN set does not match");
            return false;
        }
        if (!StringUtils.equals(Preferences.instance().getDefault("CFBundleShortVersionString"),
                StringUtils.trim(bundleVersion))) {
            log.warn("Bundle version in ASN set does not match");
        }

        NetworkInterface en0 = NetworkInterface.getByName("en0");
        if (null == en0) {
            // Interface is not found when link is down #fail
            log.warn("No network interface en0");
        } else {
            byte[] mac = en0.getHardwareAddress();
            if (null == mac) {
                log.error("Cannot determine MAC address");
                // Continue without validation
                return true;
            }
            final String hex = Hex.encodeHexString(mac);
            if (log.isDebugEnabled()) {
                log.debug("Interface en0:" + hex);
            }
            // Compute the hash of the GUID
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(mac);
            digest.update(opaque);
            digest.update(bundleIdentifier.getBytes(Charset.forName("utf-8")));
            byte[] result = digest.digest();
            if (Arrays.equals(result, hash)) {
                if (log.isInfoEnabled()) {
                    log.info(String.format("Valid receipt for GUID %s", hex));
                }
                this.name = hex;
            } else {
                log.error(String.format("Failed verification. Hash with GUID %s does not match hash in receipt",
                        hex));
                return false;
            }
        }
    } catch (Exception e) {
        log.error("Unknown receipt validation error", e);
        // Shutdown if receipt is not valid
        return false;
    }
    // Always return true to dismiss donation prompt.
    return true;
}

From source file:com.linkedin.databus.core.DbusEventPart.java

@Override
public String toString() {
    StringBuilder sb = new StringBuilder(64);
    sb.append("Length=").append(getDataLength()).append(";SchemaVersion=").append(getSchemaVersion())
            .append(";SchemaId=").append("0x").append(Hex.encodeHexString(getSchemaDigest()));

    ByteBuffer dataBB = getData();
    if (dataBB.remaining() > MAX_DATA_BYTES_PRINTED) {
        dataBB.limit(MAX_DATA_BYTES_PRINTED);
    }/* w  ww  .ja  va  2 s  . c  om*/
    byte[] data = new byte[dataBB.remaining()];
    dataBB.get(data);
    sb.append(";Value=").append("0x").append(Hex.encodeHexString(data));
    return sb.toString();
}

From source file:com.joyent.manta.client.crypto.MantaEncryptedObjectInputStream.java

/**
 * Initializes the cipher with the object's IV.
 *
 * @return number of bytes to skip ahead after initialization
 *//*w ww. j a  v a 2 s  . c  o  m*/
private long initializeCipher() {
    String ivString = getHeaderAsString(MantaHttpHeaders.ENCRYPTION_IV);

    if (ivString == null || ivString.isEmpty()) {
        String msg = "Initialization Vector (IV) was not set for the object. Unable to decrypt.";
        MantaClientEncryptionException e = new MantaClientEncryptionException(msg);
        annotateException(e);
        throw e;
    }

    byte[] iv = Base64.getDecoder().decode(ivString);

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("IV: {}", Hex.encodeHexString(iv));
    }

    final int mode = Cipher.DECRYPT_MODE;

    try {
        this.cipher.init(mode, secretKey, cipherDetails.getEncryptionParameterSpec(iv));

        if (startPosition != null && startPosition > 0) {
            return cipherDetails.updateCipherToPosition(this.cipher, startPosition);
        } else {
            return 0L;
        }
    } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
        String msg = "Error initializing cipher";
        MantaClientEncryptionException mce = new MantaClientEncryptionException(msg, e);
        annotateException(mce);
        throw mce;
    }
}

From source file:com.microsoft.sqlserver.testframework.DBTable.java

/**
 * /*w w w. j a v  a 2 s .c o  m*/
 * @return query to create table
 */
String populateTableSql() {
    StringJoiner sb = new StringJoiner(SPACE_CHAR);

    sb.add("INSERT");
    sb.add("INTO");
    sb.add(escapedTableName);
    sb.add("VALUES");

    for (int i = 0; i < totalRows; i++) {
        if (i != 0) {
            sb.add(COMMA);
        }
        sb.add(OPEN_BRACKET);
        for (int colNum = 0; colNum < totalColumns; colNum++) {

            // TODO: consider how to enclose data in case of preparedStatemets
            if (passDataAsString(colNum)) {
                sb.add("'" + String.valueOf(getColumn(colNum).getRowValue(i)) + "'");
            } else if (passDataAsHex(colNum)) {
                sb.add("0X" + Hex.encodeHexString((byte[]) (getColumn(colNum).getRowValue(i))));
            } else {
                sb.add(String.valueOf(getColumn(colNum).getRowValue(i)));
            }

            if (colNum < totalColumns - 1) {
                sb.add(COMMA);
            }
        }
        sb.add(CLOSE_BRACKET);
    }

    return (sb.toString());
}

From source file:com.hurence.logisland.processor.ModifyId.java

@Override
public void init(ProcessContext context) {
    super.init(context);
    if (context.getPropertyValue(STRATEGY).isSet()) {
        if (context.getPropertyValue(STRATEGY).getRawValue().equals(RANDOM_UUID_STRATEGY.getValue())) {
            idBuilder = new IdBuilder() {
                @Override/*from  ww w.  ja  v a  2  s.c o m*/
                public void buildId(Record record) {
                    record.setId(UUID.randomUUID().toString());
                }
            };
        } else if (context.getPropertyValue(STRATEGY).getRawValue().equals(HASH_FIELDS_STRATEGY.getValue())) {
            final List<String> fieldsForHash = Lists
                    .newArrayList(context.getPropertyValue(FIELDS_TO_USE).asString().split(","));

            try {
                final MessageDigest digest = MessageDigest
                        .getInstance(context.getPropertyValue(HASH_ALGORITHM).asString());
                final Charset charset = Charset
                        .forName(context.getPropertyValue(CHARSET_TO_USE_FOR_HASH).asString());
                idBuilder = new IdBuilder() {
                    @Override
                    public void buildId(Record record) {
                        StringBuilder stb = new StringBuilder();
                        for (String fieldName : fieldsForHash) {
                            if (record.hasField(fieldName))
                                stb.append(record.getField(fieldName).asString());
                        }
                        digest.update(stb.toString().getBytes(charset));
                        byte[] digested = digest.digest();
                        record.setId(Hex.encodeHexString(digested));
                    }
                };
            } catch (NoSuchAlgorithmException e) {
                throw new Error(
                        "This error should not happen because the validator should ensure the algorythme exist",
                        e);
            }
        } else if (context.getPropertyValue(STRATEGY).getRawValue()
                .equals(JAVA_FORMAT_STRING_WITH_FIELDS_STRATEGY.getValue())) {
            final String[] fieldsForFormat = context.getPropertyValue(FIELDS_TO_USE).asString().split(",");
            final String format = context.getPropertyValue(JAVA_FORMAT_STRING).asString();
            final Locale local = Locale.forLanguageTag(context.getPropertyValue(LANGUAGE_TAG).asString());
            idBuilder = new IdBuilder() {
                @Override
                public void buildId(Record record) {
                    final Object[] valuesForFormat = new Object[fieldsForFormat.length];
                    for (int i = 0; i < valuesForFormat.length; i++) {
                        if (!record.hasField(fieldsForFormat[i])) {
                            List<String> fieldsName = Lists.newArrayList(fieldsForFormat);
                            record.addError(ProcessError.CONFIG_SETTING_ERROR.getName(),
                                    String.format(
                                            "could not build id with format : '%s' \nfields: '%s' \n because "
                                                    + "field: '%s' does not exist",
                                            format, fieldsName, fieldsForFormat[i]));
                            return;
                        }
                        valuesForFormat[i] = record.getField(fieldsForFormat[i]).getRawValue();
                    }
                    try {
                        record.setId(String.format(local, format, valuesForFormat));
                    } catch (IllegalFormatException e) {
                        // If a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments,
                        // insufficient arguments given the format string, or other illegal conditions.
                        // For specification of all possible formatting errors, see the Details section of the formatter class specification.
                        record.addError(ProcessError.STRING_FORMAT_ERROR.getName(), e.getMessage());
                    } catch (NullPointerException e) {//should not happen
                        record.addError(ProcessError.CONFIG_SETTING_ERROR.getName(), e.getMessage());
                    }
                }
            };
        } else if (context.getPropertyValue(STRATEGY).getRawValue()
                .equals(TYPE_TIME_HASH_STRATEGY.getValue())) {
            final List<String> fieldsForHash = Lists
                    .newArrayList(context.getPropertyValue(FIELDS_TO_USE).asString().split(","));
            try {
                final MessageDigest digest = MessageDigest
                        .getInstance(context.getPropertyValue(HASH_ALGORITHM).asString());
                final Charset charset = Charset
                        .forName(context.getPropertyValue(CHARSET_TO_USE_FOR_HASH).asString());
                idBuilder = new IdBuilder() {
                    @Override
                    public void buildId(Record record) {
                        StringBuilder stb = new StringBuilder();
                        for (String fieldName : fieldsForHash) {
                            stb.append(record.getField(fieldName).asString());
                        }
                        digest.update(stb.toString().getBytes(charset));
                        byte[] digested = digest.digest();
                        final String hashString = new String(digested, charset);
                        final String recordType = record.getField(FieldDictionary.RECORD_TYPE).asString();
                        final String recordTime = record.getField(FieldDictionary.RECORD_TIME).asString();
                        final String newId = String.format("%s-%s-%s", recordType, recordTime, hashString);
                        record.setId(newId);
                    }
                };
            } catch (NoSuchAlgorithmException e) {
                throw new Error(
                        "This error should not happen because the validator should ensure the algorythme exist",
                        e);
            }
        }
    }
}

From source file:com.bitbreeds.webrtc.datachannel.DataChannelImpl.java

@Override
public void run() {
    if (parent.getRemote() == null) {
        throw new IllegalArgumentException("No user data set for remote user");
    }/*from   ww w. j  a v  a  2  s.c om*/

    logger.info("Started listening to port: " + port);
    while (running && channel.isBound()) {

        byte[] bt = new byte[bufferSize];

        try {
            if (mode == ConnectionMode.BINDING) {
                logger.info("Listening for binding on: " + channel.getLocalSocketAddress() + " - "
                        + channel.getPort());
                Thread.sleep(5); //No reason to hammer on this

                DatagramPacket packet = new DatagramPacket(bt, 0, bt.length);
                channel.receive(packet);
                SocketAddress currentSender = packet.getSocketAddress();

                sender = currentSender;
                byte[] data = Arrays.copyOf(packet.getData(), packet.getLength());
                logger.info("Received data: " + Hex.encodeHexString(data) + " on "
                        + channel.getLocalSocketAddress() + " - " + channel.getPort());

                byte[] out = bindingService.processBindingRequest(data, parent.getLocal().getUserName(),
                        parent.getLocal().getPassword(), (InetSocketAddress) currentSender);

                ByteBuffer outData = ByteBuffer.wrap(out);
                logger.info("Sending: " + Hex.encodeHexString(outData.array()) + " to " + currentSender);

                DatagramPacket pc = new DatagramPacket(out, 0, out.length);
                pc.setSocketAddress(sender);
                channel.send(pc);

                this.mode = ConnectionMode.HANDSHAKE; //Go to handshake mode
                logger.info("-> DTLS handshake");
            } else if (mode == ConnectionMode.HANDSHAKE) {
                Thread.sleep(5);
                logger.info("In handshake mode: ");

                if (transport == null) {
                    channel.connect(sender);

                    /**
                     * {@link NioUdpTransport} might replace the {@link UDPTransport} here.
                     * @see <a href="https://github.com/RestComm/mediaserver/blob/master/io/rtp/src/main/java/org/mobicents/media/server/impl/srtp/NioUdpTransport.java">NioUdpTransport</a>
                     */
                    transport = serverProtocol.accept(dtlsServer,
                            new DtlsMuxStunTransport(parent, channel, MTU));
                }

                sctpService = new SCTPImpl(this);

                mode = ConnectionMode.TRANSFER;
                logger.info("-> SCTP mode");
            } else if (mode == ConnectionMode.TRANSFER) {

                /**
                 * Here we receive message and put them to a worker thread for handling
                 * If the output of handling the message is a message, then we send those
                 * using the same thread.
                 */
                byte[] buf = new byte[transport.getReceiveLimit()];
                int length = transport.receive(buf, 0, buf.length, waitMillis);
                if (length >= 0) {
                    byte[] handled = Arrays.copyOf(buf, length);
                    workPool.submit(() -> {
                        try {
                            List<byte[]> data = sctpService.handleRequest(handled);
                            data.forEach(this::putDataOnWire);
                        } catch (Exception e) {
                            logger.error("Failed handling message: ", e);
                        }
                    });
                    logger.debug("Input: " + Hex.encodeHexString(handled));
                }
            }
        } catch (Exception e) {
            logger.error("Com error:", e);
            logger.info("Shutting down, we cannot continue here");
            running = false; //Need to quit channel now
        }
    }
    workPool.shutdown();
}

From source file:io.warp10.quasar.encoder.QuasarTokenEncoder.java

public String getTokenIdent(String token, byte[] tokenSipHashkey) {
    long ident = SipHashInline.hash24_palindromic(tokenSipHashkey, token.getBytes());

    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    buffer.order(ByteOrder.BIG_ENDIAN);
    buffer.putLong(ident);/* w  w  w.j  a  v a2s  .co  m*/
    return Hex.encodeHexString(buffer.array());
}

From source file:com.github.consiliens.harv.util.Utils.java

/**
 * Calculate SHA-256 value of given input stream. Save input stream to file
 * using the digest for a name. Return the digest value as a string
 **///  ww  w  .j  a v a  2s .c o  m
public static String streamToFile(final InputStream input, final String entityParentFolder) {
    String fileName = null;

    try {
        final byte[] dataBytes = new byte[input.available()];
        ByteStreams.readFully(input, dataBytes);

        // shasum -a 256 file.txt
        final MessageDigest sha256 = MessageDigest.getInstance(SHA256);
        final byte[] digest = ByteStreams.getDigest(ByteStreams.newInputStreamSupplier(dataBytes), sha256);

        fileName = Hex.encodeHexString(digest);
        Files.write(dataBytes, new File(entityParentFolder, fileName));
    } catch (final Exception e) {
        e.printStackTrace();
    }

    return fileName;
}

From source file:libepg.epg.section.sectionreconstructor.PayLoadSplitter.java

private synchronized void dumpMap(Map<PayLoadSplitter.PAYLOAD_PART_KEY, byte[]> t_map) {
    if (LOG.isTraceEnabled() && PayLoadSplitter.CLASS_LOG_OUTPUT_MODE == true) {
        StringBuilder s = new StringBuilder();
        s.append("?[");
        MessageFormat msg1 = new MessageFormat("={0} ?={1}");
        Set<PayLoadSplitter.PAYLOAD_PART_KEY> keys = t_map.keySet();
        for (PayLoadSplitter.PAYLOAD_PART_KEY key : keys) {
            Object[] parameters1 = { key, Hex.encodeHexString(t_map.get(key)) };
            s.append(msg1.format(parameters1));
        }//w  w w  . ja va  2s .  co  m
        s.append("]");
        LOG.trace(s.toString());
    }
}