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

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

Introduction

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

Prototype

public static char[] encodeHex(byte[] data) 

Source Link

Document

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

Usage

From source file:com.qut.middleware.delegator.openid.authn.impl.AuthnProcessorImpl.java

private void verifyOpenIDAuthnResponse(AuthnProcessorData processorData, List<AttributeType> esoeAttributes)
        throws OpenIDException, NoSuchAlgorithmException {
    ParameterList response;/*from w w  w .  j  a  v  a 2  s .  c  o  m*/
    DiscoveryInformation discovered;
    StringBuffer receivingURL;
    String queryString;
    VerificationResult verification;
    Identifier verified;
    AuthSuccess authSuccess;

    response = new ParameterList(processorData.getHttpRequest().getParameterMap());

    /* Retrieve the stored discovery information */
    discovered = (DiscoveryInformation) processorData.getHttpRequest().getSession()
            .getAttribute(ConfigurationConstants.OPENID_USER_SESSION_IDENTIFIER);

    /* Extract the receiving URL from the HTTP request */
    receivingURL = processorData.getHttpRequest().getRequestURL();

    /*
     * If a Layer 7 type device is offloading https change the recievingURL accordingly to ensure
     * correct verification
     */
    if (httpsOffload) {
        receivingURL.delete(0, 4);
        receivingURL.insert(0, "https");
    }

    queryString = processorData.getHttpRequest().getQueryString();
    if (queryString != null && queryString.length() > 0)
        receivingURL.append("?").append(processorData.getHttpRequest().getQueryString());

    /* Verify the response */
    this.logger.debug("About to verify response, accepted at receivingURL of " + receivingURL
            + " server set return to as " + response.toString());

    verification = manager.verify(receivingURL.toString(), response, discovered);
    verified = verification.getVerifiedId();
    if (verified != null) {
        AttributeType esoeAttribute;
        MessageDigest algorithm;
        byte messageDigest[];

        authSuccess = (AuthSuccess) verification.getAuthResponse();

        /*
         * Merge verified ID to ESOE view, OpenID identifiers aren't really compatible with most applications as an
         * identifier, so we'll md5 hash them for presentation as uid
         */
        algorithm = MessageDigest.getInstance("MD5");
        algorithm.reset();
        algorithm.update(verification.getVerifiedId().getIdentifier().getBytes());
        messageDigest = algorithm.digest();

        esoeAttribute = new AttributeType();
        esoeAttribute.setNameFormat(AttributeFormatConstants.basic);
        esoeAttribute.setName(this.userIdentifier);
        esoeAttribute.getAttributeValues()
                .add(new String(Hex.encodeHex(messageDigest)) + ConfigurationConstants.OPENID_NAMESPACE);
        esoeAttributes.add(esoeAttribute);

        /*
         * Store openID identifier in attributes for use by applications
         */
        esoeAttribute = new AttributeType();
        esoeAttribute.setNameFormat(AttributeFormatConstants.basic);
        esoeAttribute.setName(ConfigurationConstants.OPENID_IDENTIFIER_ATTRIBUTE);
        esoeAttribute.getAttributeValues().add(verification.getVerifiedId().getIdentifier());
        esoeAttributes.add(esoeAttribute);

        /*
         * Retrieve requested attributes (if provided, given low deployments of attribute exchange currently we
         * don't fail when this isn't presented)
         */
        if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
            FetchResponse fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);

            for (OpenIDAttribute attribute : this.requestedAttributes) {
                List<String> values = fetchResp.getAttributeValues(attribute.getLabel());

                /* Merge to ESOE view */
                esoeAttribute = new AttributeType();
                esoeAttribute.setNameFormat(AttributeFormatConstants.basic);
                esoeAttribute.setName(attribute.getEsoeAttributeName());
                for (String value : values) {
                    esoeAttribute.getAttributeValues().add(attribute.getValuePrepend() + value);
                }
                esoeAttributes.add(esoeAttribute);
            }
        }
    } else {
        throw new OpenIDException("Attempt by manager to verify result returned null");
    }
}

From source file:be.fedict.eid.idp.webapp.ProtocolExitServlet.java

/**
 * Optionally encrypt the user ID//from w ww.  j  a  va 2s . c  o m
 * 
 * @param userId
 *            user ID to encrypt ( or not )
 * @param rp
 *            rp, can be null
 * @return (encrypted) user ID
 */
private String getUniqueId(String userId, RPEntity rp) {

    String uniqueId = userId;

    byte[] hmacSecret = getIdentifierSecret(rp);

    if (null != hmacSecret) {

        Mac mac;
        try {
            mac = CryptoUtil.getMac(hmacSecret);
        } catch (InvalidKeyException e) {
            throw new RuntimeException("Invalid key", e);
        }
        mac.update(uniqueId.getBytes());
        byte[] resultHMac = mac.doFinal();
        uniqueId = new String(Hex.encodeHex(resultHMac)).toUpperCase();
    }
    return uniqueId;
}

From source file:com.continusec.client.AppTest.java

private static final void runCommonJsonTests(String path) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(path))));
    String line = null;//from  www.  j ava  2  s. c o m
    int state = 0;
    String j = null;
    while ((line = reader.readLine()) != null) {
        line = line.trim();
        if (line.length() > 0 && !line.startsWith("#")) {
            if (state == 0) {
                j = line;
                state = 1;
            } else if (state == 1) {
                if (new String(Hex.encodeHex(ObjectHash.objectHashWithStdRedaction(new JsonParser().parse(j))))
                        .toLowerCase().equals(line.toLowerCase())) {
                    System.out.println("Match! - " + j + " " + line);
                } else {
                    System.out.println("Fail! - " + j + " " + line);
                    throw new RuntimeException("fail");
                }
                state = 0;
            }
        }
    }
}

From source file:edu.hawaii.soest.kilonalu.flntu.FLNTUSource.java

/**
 * A method that executes the streaming of data from the source to the RBNB
 * server after all configuration of settings, connections to hosts, and
 * thread initiatizing occurs.  This method contains the detailed code for 
 * streaming the data and interpreting the stream.
 *//*from w  w w  . j  a v a  2  s .  c o m*/
protected boolean execute() {
    logger.debug("FLNTUSource.execute() called.");
    // do not execute the stream if there is no connection
    if (!isConnected())
        return false;

    boolean failed = false;

    SocketChannel socket = getSocketConnection();

    // while data are being sent, read them into the buffer
    try {
        // create four byte placeholders used to evaluate up to a four-byte 
        // window.  The FIFO layout looks like:
        //           -------------------------
        //   in ---> | One | Two |Three|Four |  ---> out
        //           -------------------------
        byte byteOne = 0x00, // set initial placeholder values
                byteTwo = 0x00, byteThree = 0x00, byteFour = 0x00;

        // Create a buffer that will store the sample bytes as they are read
        ByteBuffer sampleBuffer = ByteBuffer.allocate(getBufferSize());

        // create a byte buffer to store bytes from the TCP stream
        ByteBuffer buffer = ByteBuffer.allocateDirect(getBufferSize());

        // add a channel of data that will be pushed to the server.  
        // Each sample will be sent to the Data Turbine as an rbnb frame.
        ChannelMap rbnbChannelMap = new ChannelMap();

        // while there are bytes to read from the socket ...
        while (socket.read(buffer) != -1 || buffer.position() > 0) {

            // prepare the buffer for reading
            buffer.flip();

            // while there are unread bytes in the ByteBuffer
            while (buffer.hasRemaining()) {
                byteOne = buffer.get();
                logger.debug("char: " + (char) byteOne + "\t" + "b1: "
                        + new String(Hex.encodeHex((new byte[] { byteOne }))) + "\t" + "b2: "
                        + new String(Hex.encodeHex((new byte[] { byteTwo }))) + "\t" + "b3: "
                        + new String(Hex.encodeHex((new byte[] { byteThree }))) + "\t" + "b4: "
                        + new String(Hex.encodeHex((new byte[] { byteFour }))) + "\t" + "sample pos: "
                        + sampleBuffer.position() + "\t" + "sample rem: " + sampleBuffer.remaining() + "\t"
                        + "sample cnt: " + sampleByteCount + "\t" + "buffer pos: " + buffer.position() + "\t"
                        + "buffer rem: " + buffer.remaining() + "\t" + "state: " + state);

                // Use a State Machine to process the byte stream.
                switch (state) {

                case 0:

                    // sample sets begin with 'mvs 1\r\n' and end with 'mvs 0\r\n'.  Find the 
                    // beginning of the sample set using the 4-byte window (s 1\r\n)
                    // note bytes are in reverse order in the FIFO window
                    if (byteOne == 0x0A && byteTwo == 0x0D && byteThree == 0x31 && byteFour == 0x20) {
                        // we've found the beginning of a sample set, move on
                        state = 1;
                        break;

                    } else {
                        break;
                    }

                case 1: // read the rest of the bytes to the next EOL characters

                    // sample line is terminated by record delimiter byte (\r\n)
                    // note bytes are in reverse order in the FIFO window
                    if (byteOne == 0x0A && byteTwo == 0x0D && byteThree == 0x30 && byteFour == 0x20) {

                        // we've found the sample set ending, clear buffers and return
                        // to state 0 to wait for the next set
                        byteOne = 0x00;
                        byteTwo = 0x00;
                        byteThree = 0x00;
                        byteFour = 0x00;
                        sampleBuffer.clear();
                        sampleByteCount = 0;
                        rbnbChannelMap.Clear();
                        logger.debug("Cleared b1,b2,b3,b4. Cleared sampleBuffer. Cleared rbnbChannelMap.");
                        state = 0;

                        // if we're not at the sample set end, look for individual samples    
                    } else if (byteOne == 0x0A && byteTwo == 0x0D) {

                        // found the sample ending delimiter
                        // add in the sample delimiter to the sample buffer
                        if (sampleBuffer.remaining() > 0) {
                            sampleBuffer.put(byteOne);
                            sampleByteCount++;
                        } else {
                            sampleBuffer.compact();
                            logger.debug("Compacting sampleBuffer ...");
                            sampleBuffer.put(byteOne);
                            sampleByteCount++;

                        }

                        // extract just the length of the sample bytes out of the
                        // sample buffer, and place it in the channel map as a 
                        // byte array.  Then, send it to the data turbine.
                        byte[] sampleArray = new byte[sampleByteCount];
                        sampleBuffer.flip();
                        sampleBuffer.get(sampleArray);

                        // send the sample to the data turbine
                        rbnbChannelMap.PutTimeAuto("server");
                        String sampleString = new String(sampleArray, "US-ASCII");
                        int channelIndex = rbnbChannelMap.Add(getRBNBChannelName());
                        rbnbChannelMap.PutMime(channelIndex, "text/plain");
                        rbnbChannelMap.PutDataAsString(channelIndex, sampleString);
                        getSource().Flush(rbnbChannelMap);
                        logger.info("Sample: " + sampleString.substring(0, sampleString.length() - 2)
                                + " sent data to the DataTurbine. ");
                        byteOne = 0x00;
                        byteTwo = 0x00;
                        byteThree = 0x00;
                        byteFour = 0x00;
                        sampleBuffer.clear();
                        sampleByteCount = 0;
                        rbnbChannelMap.Clear();
                        logger.debug("Cleared b1,b2,b3,b4. Cleared sampleBuffer. Cleared rbnbChannelMap.");
                        break;

                    } else { // not 0x0

                        // still in the middle of the sample, keep adding bytes
                        sampleByteCount++; // add each byte found

                        if (sampleBuffer.remaining() > 0) {
                            sampleBuffer.put(byteOne);
                        } else {
                            sampleBuffer.compact();
                            logger.debug("Compacting sampleBuffer ...");
                            sampleBuffer.put(byteOne);

                        }

                        break;
                    } // end if for 0x0D20 EOL

                } // end switch statement

                // shift the bytes in the FIFO window
                byteFour = byteThree;
                byteThree = byteTwo;
                byteTwo = byteOne;

            } //end while (more unread bytes)

            // prepare the buffer to read in more bytes from the stream
            buffer.compact();

        } // end while (more socket bytes to read)
        socket.close();

    } catch (IOException e) {
        // handle exceptions
        // In the event of an i/o exception, log the exception, and allow execute()
        // to return false, which will prompt a retry.
        failed = true;
        e.printStackTrace();
        return !failed;
    } catch (SAPIException sapie) {
        // In the event of an RBNB communication  exception, log the exception, 
        // and allow execute() to return false, which will prompt a retry.
        failed = true;
        sapie.printStackTrace();
        return !failed;
    }

    return !failed;
}

From source file:com.itude.mobile.android.util.StringUtil.java

/**
 * Has a {@link String}/* ww  w. j  av  a  2s  .c o m*/
 * 
 * @param stringToHash {@link String} to hash
 * @return Hashed {@link String}
 */
public static String md5(String stringToHash) {
    MessageDigest digest = null;
    try {
        digest = java.security.MessageDigest.getInstance("MD5");
        digest.update(stringToHash.getBytes());
        byte[] hash = digest.digest();
        return new String(Hex.encodeHex(hash));
    } catch (Exception e) {
        MBLog.w(TAG, "Could not create hash of following string: " + stringToHash);
    }

    return null;
}

From source file:edu.washington.cs.mystatus.odk.database.ODKSQLiteOpenHelper.java

/**
 * Formats a byte sequence into the literal string format expected by
 * SQLCipher: hex'HEX ENCODED BYTES'/*from w w w  .  j a  va  2  s . c  o m*/
 * The key data must be 256 bits (32 bytes) wide.
 * The key data will be formatted into a 64 character hex string with a special
 * prefix and suffix SQLCipher uses to distinguish raw key data from a password.
 * @link http://sqlcipher.net/sqlcipher-api/#key
 * @param raw_key a 32 byte array
 * @return the encoded key
 */
private static String encodeRawKey(byte[] raw_key) {
    if (raw_key.length != 32)
        throw new IllegalArgumentException("provided key not 32 bytes (256 bits) wide");

    final String kPrefix;
    final String kSuffix;

    if (sqlcipher_uses_native_key) {
        //Log.d(TAG, "sqlcipher uses native method to set key");
        kPrefix = "x'";
        kSuffix = "'";
    } else {
        //Log.d(TAG, "sqlcipher uses PRAGMA to set key - SPECIAL HACK IN PROGRESS");
        kPrefix = "x''";
        kSuffix = "''";
    }

    final char[] key_chars = Hex.encodeHex(raw_key);
    if (key_chars.length != 64)
        throw new IllegalStateException("encoded key is not 64 bytes wide");

    return kPrefix + new String(key_chars) + kSuffix;
}

From source file:com.zimbra.cs.servlet.util.CsrfUtil.java

/**
 * @param sessionId/*from w  w  w .  ja  v a 2 s .  c o m*/
 * @param i
 * @return
 * @throws AuthTokenException
 * @throws ServiceException
 * @throws InvalidAlgorithmParameterException
 */
public static String generateCsrfToken(String accountId, long authTokenExpiration, int tokenSalt, AuthToken at)
        throws ServiceException {

    try {
        String crumb = at.getCrumb();
        String tokenData = getExistingCsrfTokenForThisAuthToken(at, crumb);
        if (tokenData == null) {

            StringBuilder encodedBuff = new StringBuilder(64);
            BlobMetaData.encodeMetaData(C_ID, accountId, encodedBuff);
            BlobMetaData.encodeMetaData(C_EXP, Long.toString(authTokenExpiration), encodedBuff);
            BlobMetaData.encodeMetaData(C_SALT_ID, tokenSalt, encodedBuff);
            tokenData = new String(Hex.encodeHex(encodedBuff.toString().getBytes()));
        }
        CsrfTokenKey key = getCurrentKey();
        String hmac = TokenUtil.getHmac(tokenData, key.getKey());
        String encoded = key.getVersion() + "_" + hmac;
        storeTokenData(tokenData, at, authTokenExpiration, crumb);
        return encoded;
    } catch (AuthTokenException e) {
        throw ServiceException.FAILURE("Error generating Auth Token, " + e.getMessage(), e);
    }

}

From source file:net.padlocksoftware.padlock.validator.Validator.java

public Validator(License l, byte[] publicKey) {
    this(l, new String(Hex.encodeHex(publicKey)));
}

From source file:com.ephesoft.dcma.util.EphesoftStringUtil.java

/**
 * Encodes the String value to its corresponding Hex representation.
 * /*w w w. ja  v  a 2 s . com*/
 * @param originalData byte[] data to be encoded.
 * @return {@link String} Hex representation of the String.
 */
public static String toHexString(final byte[] originalData) {
    String encodedString = null;
    if (originalData != null) {
        char[] encodedCharacters = Hex.encodeHex(originalData);
        encodedString = new String(encodedCharacters);
    }
    return encodedString;
}

From source file:com.ning.arecibo.util.timeline.times.TestTimelineCoder.java

@Test(groups = "fast")
public void test65KRepeats() throws Exception {
    int count = 0;
    final List<DateTime> dateTimes = new ArrayList<DateTime>();
    final DateTime startingDateTime = DateTimeUtils.dateTimeFromUnixSeconds(1000000);
    DateTime time = startingDateTime;// www.  j  a va 2  s  . co m
    for (int i = 0; i < 20; i++) {
        time = time.plusSeconds(200);
        dateTimes.add(time);
    }
    for (int i = 0; i < 0xFFFF + 100; i++) {
        time = time.plusSeconds(100);
        dateTimes.add(time);
    }
    final byte[] timeBytes = timelineCoder.compressDateTimes(dateTimes);
    final String hex = new String(Hex.encodeHex(timeBytes));
    // Here are the compressed samples: ff000f4308fe13c8fdffff64fe6464
    // Translation:
    // [ff 00 0f 43 08] means absolution time 1000000
    // [fe 13 c8] means repeat 19 times delta 200 seconds
    // [fd ff ff 64] means repeat 65525 times delta 100 seconds
    // [fe 64 64] means repeat 100 times delta 100 seconds
    Assert.assertEquals(timeBytes, Hex.decodeHex("ff000f4308fe13c8fdffff64fe6464".toCharArray()));
    final List<DateTime> restoredSamples = timelineCoder.decompressDateTimes(timeBytes);
    Assert.assertEquals(restoredSamples.size(), dateTimes.size());
    for (int i = 0; i < count; i++) {
        Assert.assertEquals(restoredSamples.get(i), DateTimeUtils.unixSeconds(dateTimes.get(i)));
    }
}