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

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

Introduction

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

Prototype

public Hex() 

Source Link

Document

Creates a new codec with the default charset name #DEFAULT_CHARSET_NAME

Usage

From source file:org.matmaul.freeboxos.login.LoginManager.java

protected static String hmacSha1(String key, String value) {
    try {//from  www .j  a  v a 2 s . com
        // Get an hmac_sha1 key from the raw key bytes
        byte[] keyBytes = key.getBytes();
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

        // Get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(value.getBytes());

        // Convert raw bytes to Hex
        byte[] hexBytes = new Hex().encode(rawHmac);

        // Covert array of Hex bytes to a String
        return new String(hexBytes, "UTF-8");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.onebusaway.gtfs_realtime.alerts_producer_demo.GtfsRealtimeProviderImpl.java

/**
 * Generates a unique fingerprint of the specified value.
 * /* w w  w. ja v  a  2  s.  com*/
 * @param value
 * @return an hex-string of the MD5 fingerprint of the specified value.
 */
private String getHashOfValue(String value) {
    try {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.update(value.getBytes());
        Hex hex = new Hex();
        return new String(hex.encode(digest.digest()), hex.getCharsetName());
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }
}

From source file:org.openhab.binding.freebox.internal.api.FreeboxApiManager.java

private static String hmacSha1(String key, String value) throws FreeboxException {
    try {/*from   ww w  .j a v  a 2s. c  om*/
        // Get an hmac_sha1 key from the raw key bytes
        byte[] keyBytes = key.getBytes();
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

        // Get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(value.getBytes());

        // Convert raw bytes to Hex
        byte[] hexBytes = new Hex().encode(rawHmac);

        // Covert array of Hex bytes to a String
        return new String(hexBytes, StandardCharsets.UTF_8);
    } catch (IllegalArgumentException | NoSuchAlgorithmException | InvalidKeyException
            | IllegalStateException e) {
        throw new FreeboxException("Computing the hmac-sha1 of the challenge and the app token failed", e);
    }
}

From source file:org.slc.sli.ingestion.model.RecordHash.java

/**
 * Convert binary bytes to Hex string. E.g. 20-bytes SHA hash to 40-hex-char string
 *
 * @param bytes//from  ww w . j a  v  a  2  s  .  c  om
 *            Binary bytes to be converted to hex
 *
 * @return A hex String object
 */
public static String binary2Hex(byte[] bytes) {
    return new String(new Hex().encode(bytes));
}

From source file:org.slc.sli.ingestion.model.RecordHash.java

/**
 * Convert DiD or hash to 20-byte binary form
 *
 * @param id/*from   ww w . jav a 2 s.co  m*/
 *            String of 40 chars of hex, either a SHA hash or an ID suffixed with "_id"
 *
 * @return Binary bytes, or null if cannot be decoded
 */
public static byte[] hex2Binary(String hexId) {
    // Take first 40 hex digits of DiD, lopping off the trailing "_id"
    try {
        return new Hex().decode(hexId.substring(0, 40).getBytes());
    } catch (DecoderException e) {
        LOG.warn("Cannot convert hex hash or ID to binary: '" + hexId + "'");
        LOG.warn(e.getMessage());
    }
    byte[] null_result = null;
    return null_result;
}

From source file:org.vosao.utils.CipherUtils.java

public static String decrypt(String data, String password) {
    try {//  w ww .j a  va2s  . com
        byte[] key = new Base64().decode(password);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), ivspec);
        byte[] d = (byte[]) new Hex().decode(data);
        byte[] decrypted = cipher.doFinal(d);
        return new String(decrypted, "UTF-8");

    } catch (Exception e) {
        logger.error(e);
    }
    return "";
}

From source file:org.wso2.andes.management.ui.views.ViewUtility.java

/**
 * Format object messages to have a hexadecimal view and a ascii view.
 * @param numOfBytes//from w w  w  .j a  v a2  s . c  o  m
 * @param encoding
 * @return
 */
private static String displayByteFormat(Composite localComposite, byte[] byteArray, int numOfBytes,
        String encoding, String direction, boolean isHex) {
    final Hex hexeconder = new Hex();
    final byte[] encoded = hexeconder.encode(byteArray);

    int hexLength = byteArray.length * 2;
    StringBuilder sb = new StringBuilder();
    int currentBytePos = (Integer) localComposite.getData("currentBytePos");
    int startingBytePos = (Integer) localComposite.getData("startingBytePos");

    int strLength = 0;
    int offset = 0;
    String encStr;
    if (isHex) {
        if (direction.equals("<<")) {
            strLength = (numOfBytes > hexLength) ? hexLength : numOfBytes;
            offset = 0;
        } else if (direction.equals("<")) {
            strLength = (startingBytePos - numOfBytes < 0) ? startingBytePos : numOfBytes;
            offset = (startingBytePos - numOfBytes < 0) ? 0 : startingBytePos - numOfBytes;
        } else if (direction.equals(">")) {
            strLength = (numOfBytes > (hexLength - currentBytePos)) ? hexLength - currentBytePos : numOfBytes;
            offset = currentBytePos;
        } else if (direction.equals(">>")) {
            strLength = (numOfBytes > hexLength) ? hexLength : numOfBytes;
            offset = (hexLength - numOfBytes > 0) ? hexLength - numOfBytes : 0;
        } else {
            strLength = hexLength;
            offset = 0;
        }
        localComposite.setData("strLength", strLength);
        localComposite.setData("currentBytePos", offset + strLength);
        localComposite.setData("startingBytePos", offset);

        if (_lastButton != null && !_lastButton.isDisposed()) {
            //Set button state
            _previousButton.setEnabled(offset != 0);
            _nextButton.setEnabled(offset + strLength != hexLength);

            //set the text fields
            _hexNumTextToStart.setText("" + offset / 2);
            _hexNumTextToEnd.setText("" + (hexLength - (offset + strLength)) / 2);
        }
    }

    try {
        if (isHex) {
            encStr = new String(encoded, offset, strLength, encoding);
            for (int c = 0; c < strLength; c++) {
                sb.append(encStr.charAt(c));
                if (c % 2 == 1) {
                    sb.append(" ");
                }
            }
            return sb.toString().toUpperCase();
        } else {
            strLength = (Integer) localComposite.getData("strLength");
            sb = new StringBuilder();
            encStr = new String(byteArray, startingBytePos / 2, strLength / 2, encoding);
            for (int c = 0; c < encStr.length(); c++) {
                char ch = encStr.charAt(c);
                if (ch > 31 && ch < 127) {
                    sb.append(ch);
                } else {
                    sb.append("?");
                }

                sb.append(" ");
            }
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return sb.toString();
}

From source file:org.wso2.andes.tools.messagestore.commands.Dump.java

protected List<List> createMessageData(java.util.List<Long> msgids, List<QueueEntry> messages,
        boolean showHeaders, boolean showRouting, boolean showMessageHeaders) {

    List<List> display = new LinkedList<List>();

    List<String> hex = new LinkedList<String>();
    List<String> ascii = new LinkedList<String>();
    display.add(hex);/*from w ww .j  a  va  2 s. c o m*/
    display.add(ascii);

    for (QueueEntry entry : messages) {
        ServerMessage msg = entry.getMessage();
        if (!includeMsg(msg, msgids)) {
            continue;
        }

        //Add divider between messages
        hex.add(Console.ROW_DIVIDER);
        ascii.add(Console.ROW_DIVIDER);

        // Show general message information
        hex.add(Show.Columns.ID.name());
        ascii.add(msg.getMessageNumber().toString());

        hex.add(Console.ROW_DIVIDER);
        ascii.add(Console.ROW_DIVIDER);

        if (showRouting) {
            addShowInformation(hex, ascii, msg, "Routing Details", true, false, false);
        }
        if (showHeaders) {
            addShowInformation(hex, ascii, msg, "Headers", false, true, false);
        }
        if (showMessageHeaders) {
            addShowInformation(hex, ascii, msg, null, false, false, true);
        }

        // Add Content Body section
        hex.add("Content Body");
        ascii.add("");
        hex.add(Console.ROW_DIVIDER);
        ascii.add(Console.ROW_DIVIDER);

        final int messageSize = (int) msg.getSize();
        if (messageSize != 0) {
            hex.add("Hex");
            hex.add(Console.ROW_DIVIDER);

            ascii.add("ASCII");
            ascii.add(Console.ROW_DIVIDER);

            java.nio.ByteBuffer buf = java.nio.ByteBuffer.allocate(64 * 1024);

            int position = 0;

            while (position < messageSize) {

                position += msg.getContent(buf, position);
                buf.flip();
                //Duplicate so we don't destroy original data :)
                java.nio.ByteBuffer hexBuffer = buf;

                java.nio.ByteBuffer charBuffer = hexBuffer.duplicate();

                Hex hexencoder = new Hex();

                while (hexBuffer.hasRemaining()) {
                    byte[] line = new byte[LINE_SIZE];

                    int bufsize = hexBuffer.remaining();
                    if (bufsize < LINE_SIZE) {
                        hexBuffer.get(line, 0, bufsize);
                    } else {
                        bufsize = line.length;
                        hexBuffer.get(line);
                    }

                    byte[] encoded = hexencoder.encode(line);

                    try {
                        String encStr = new String(encoded, 0, bufsize * 2, DEFAULT_ENCODING);
                        String hexLine = "";

                        int strLength = encStr.length();
                        for (int c = 0; c < strLength; c++) {
                            hexLine += encStr.charAt(c);

                            if ((c & 1) == 1 && SPACE_BYTES) {
                                hexLine += BYTE_SPACER;
                            }
                        }

                        hex.add(hexLine);
                    } catch (UnsupportedEncodingException e) {
                        _console.println(e.getMessage());
                        return null;
                    }
                }

                while (charBuffer.hasRemaining()) {
                    String asciiLine = "";

                    for (int pos = 0; pos < LINE_SIZE; pos++) {
                        if (charBuffer.hasRemaining()) {
                            byte ch = charBuffer.get();

                            if (isPrintable(ch)) {
                                asciiLine += (char) ch;
                            } else {
                                asciiLine += NON_PRINTING_ASCII_CHAR;
                            }

                            if (SPACE_BYTES) {
                                asciiLine += BYTE_SPACER;
                            }
                        } else {
                            break;
                        }
                    }

                    ascii.add(asciiLine);
                }
                buf.clear();
            }
        } else {
            List<String> result = new LinkedList<String>();

            display.add(result);
            result.add("No ContentBodies");
        }
    }

    // if hex is empty then we have no data to display
    if (hex.size() == 0) {
        return null;
    }

    return display;
}

From source file:org.wso2.carbon.cep.objectdetection.siddhiextension.ObjectDetectionExtension.java

/**
 * Detect objects using OpenCV./*from  ww  w.  ja va  2s. co  m*/
 *
 * @param imageHex
 *            the image hex string
 * @param cascadePath
 *            the cascade path
 * @return the detected object count
 */
private long detectObjects(String imageHex, String cascadePath) {
    long objectCount = 0;
    try {
        // conversion to Mat
        byte[] imageByteArr = (byte[]) new Hex().decode(imageHex);
        Mat image = Highgui.imdecode(new MatOfByte(imageByteArr), Highgui.IMREAD_UNCHANGED);

        // initializing classifier
        CascadeClassifier cClassifier = new CascadeClassifier();
        cClassifier.load(cascadePath);

        // pre-processing
        Imgproc.cvtColor(image, image, Imgproc.COLOR_RGB2GRAY);
        Imgproc.equalizeHist(image, image);

        // detecting objects
        MatOfRect imageRect = new MatOfRect();
        cClassifier.detectMultiScale(image, imageRect);

        // image count
        objectCount = ((Integer) imageRect.toList().size()).longValue();
    } catch (DecoderException e) {
        e.printStackTrace();
    }

    return objectCount;
}

From source file:pl.otros.vfs.browser.auth.AuthStoreUtils.java

private String saltAndEncrypt(char[] data) throws NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
    String value;//  ww  w. j  a  va2  s .  co  m
    Hex hex = new Hex();
    char[] saltedData = addSalt(data);

    byte[] encode = encrypt(saltedData, password);
    value = new String(hex.encode(encode));
    return value;
}