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:net.sourceforge.subsonic.backend.service.LicenseGenerator.java

/**
 * Calculates the MD5 digest and returns the value as a 32 character hex string.
 *
 * @param s Data to digest.// w w  w.  j a va2 s  .c om
 * @return MD5 digest as a hex string.
 */
private String md5Hex(String s) {
    if (s == null) {
        return null;
    }

    try {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        return new String(Hex.encodeHex(md5.digest(s.getBytes("UTF-8"))));
    } catch (Exception x) {
        throw new RuntimeException(x.getMessage(), x);
    }
}

From source file:net.sourceforge.subsonic.util.StringUtil.java

/**
* Encodes the given string by using the hexadecimal representation of its UTF-8 bytes.
*
* @param s The string to encode.//from  w  ww . ja  v a  2  s  .c o m
* @return The encoded string.
*/
public static String utf8HexEncode(String s) {
    if (s == null) {
        return null;
    }
    byte[] utf8;
    try {
        utf8 = s.getBytes(ENCODING_UTF8);
    } catch (UnsupportedEncodingException x) {
        throw new RuntimeException(x);
    }
    return String.valueOf(Hex.encodeHex(utf8));
}

From source file:net.sourceforge.subsonic.util.StringUtil.java

/**
 * Calculates the MD5 digest and returns the value as a 32 character hex string.
 *
 * @param s Data to digest./*from   ww  w.  j  a v a2 s  .  c  o  m*/
 * @return MD5 digest as a hex string.
 */
public static String md5Hex(String s) {
    if (s == null) {
        return null;
    }

    try {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        return new String(Hex.encodeHex(md5.digest(s.getBytes(ENCODING_UTF8))));
    } catch (Exception x) {
        throw new RuntimeException(x.getMessage(), x);
    }
}

From source file:net.sourceforge.vulcan.web.SignedRequestAuthorizationFilter.java

protected String hashRequestBody(HttpServletRequest request, SecretKey secretKey)
        throws IOException, ServletException {
    final byte[] result;
    try {/*from  ww  w  .j a  v a2  s  .co m*/
        final Mac mac = Mac.getInstance(algorithm);
        mac.init(secretKey);
        result = mac.doFinal(IOUtils.toByteArray(request.getInputStream()));
    } catch (NoSuchAlgorithmException e) {
        throw new ServletException(e);
    } catch (InvalidKeyException e) {
        throw new ServletException(e);
    }

    return new String(Hex.encodeHex(result));
}

From source file:nl.b3p.kaartenbalie.core.server.User.java

public static String createCode() {
    Random rd = new Random();
    StringBuilder toBeHashedString = new StringBuilder();
    toBeHashedString.append((new Date()).toString());
    toBeHashedString.append(rd.nextLong());

    byte[] hash = null;
    try {/* w  w w.j  av  a2 s .  co  m*/
        MessageDigest md = MessageDigest.getInstance(KBConfiguration.MD_ALGORITHM);
        md.update(toBeHashedString.toString().getBytes(KBConfiguration.CHARSET));
        hash = md.digest();
    } catch (Exception ex) {
        log.info("Can not create hash (ignoring): " + ex.getLocalizedMessage());
        hash = toBeHashedString.toString().getBytes();
    }

    return new String(Hex.encodeHex(hash));
}

From source file:nl.knaw.dans.easy.sword2examples.Common.java

public static CloseableHttpResponse sendChunk(DigestInputStream dis, int size, String method, URI uri,
        String filename, String mimeType, CloseableHttpClient http, boolean inProgress) throws Exception {
    // System.out.println(String.format("Sending chunk to %s, filename = %s, chunk size = %d, MIME-Type = %s, In-Progress = %s ... ", uri.toString(),
    // filename, size, mimeType, Boolean.toString(inProgress)));
    byte[] chunk = readChunk(dis, size);
    String md5 = new String(Hex.encodeHex(dis.getMessageDigest().digest()));
    HttpUriRequest request = RequestBuilder.create(method).setUri(uri).setConfig(RequestConfig.custom()
            /*// w  ww  .  ja v  a  2 s . c  o m
             * When using an HTTPS-connection EXPECT-CONTINUE must be enabled, otherwise buffer overflow may follow
             */
            .setExpectContinueEnabled(true).build()) //
            .addHeader("Content-Disposition", String.format("attachment; filename=%s", filename)) //
            .addHeader("Content-MD5", md5) //
            .addHeader("Packaging", BAGIT_URI) //
            .addHeader("In-Progress", Boolean.toString(inProgress)) //
            .setEntity(new ByteArrayEntity(chunk, ContentType.create(mimeType))) //
            .build();
    CloseableHttpResponse response = http.execute(request);
    // System.out.println("Response received.");
    return response;
}

From source file:nl.sidn.dnslib.message.records.dnssec.DSResourceRecord.java

@Override
public void decode(NetworkData buffer) {
    super.decode(buffer);

    keytag = buffer.readUnsignedChar();//from  ww  w.  j  av  a2s .c om

    short alg = buffer.readUnsignedByte();
    algorithm = AlgorithmType.fromValue(alg);

    short dt = buffer.readUnsignedByte();
    digestType = DigestType.fromValue(dt);

    digest = new byte[rdLength - 4];
    buffer.readBytes(digest);

    hex = new String(Hex.encodeHex(digest));
}

From source file:nl.surfnet.coin.janus.JanusRestClient.java

/**
 * Sign the given method call.//from  w  ww .  j  a  va  2 s.  c o  m
 * 
 * @param method
 *          the name of the method to call
 * @param parameters
 *          additional parameters that need to be passed to Janus
 * @return URI with parameters janus_sig and janus_key
 * @throws IOException
 */
private URI sign(String method, Map<String, String> parameters) throws IOException {
    Map<String, String> keys = new TreeMap<String, String>();
    keys.put("janus_key", user);
    keys.put("method", method);

    keys.putAll(parameters);

    keys.put("rest", "1");
    keys.put("userid", user);
    Set<String> keySet = keys.keySet();
    StringBuilder toSign = new StringBuilder(secret);
    for (String key : keySet) {
        toSign.append(key);
        toSign.append(keys.get(key));
    }

    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance("SHA-512");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Cannot use algorithm SHA-512", e);
    }
    digest.reset();
    final String charsetName = "UTF-8";
    byte[] input = digest.digest(toSign.toString().getBytes(charsetName));
    char[] value = Hex.encodeHex(input);
    String janus_sig = new String(value);
    keys.put("janus_sig", janus_sig);

    StringBuilder url = new StringBuilder();
    keySet = keys.keySet();
    for (String key : keySet) {
        if (url.length() > 0) {
            url.append('&');
        }
        url.append(key).append('=').append(URLEncoder.encode(keys.get(key), charsetName));
    }
    String uri = url.toString();
    return URI.create(janusUri + "?" + uri);
}

From source file:nl.tue.ddss.ifcrdf.model.IfcStepSerializer.java

private void writePrimitive(Resource val) throws IOException, SerializerException {
    if (isLogical(val)) {
        if (val.hasProperty(HASLOGICAL, EXPRESS_TRUE)) {
            print(BOOLEAN_TRUE);/*ww w  .  j ava  2 s  . c  o m*/
        } else if (val.hasProperty(HASLOGICAL, EXPRESS_FALSE)) {
            print(BOOLEAN_FALSE);
        } else if (val.hasProperty(HASLOGICAL, EXPRESS_UNDEFINED)) {
            print(BOOLEAN_UNDEFINED);
        }
    } else if (isReal(val) || isNumber(val)) {
        Double valDouble = val.getProperty(HASDOUBLE).getObject().asLiteral().getDouble();
        if ((valDouble).isInfinite() || ((valDouble).isNaN())) {
            LOGGER.info("Serializing infinite or NaN double as 0.0");
            print("0.0");
        } else {
            String string = valDouble.toString();
            if (string.endsWith(DOT_0)) {
                print(string.substring(0, string.length() - 1));
            } else {
                print(string);
            }
        }
    } else if (isInteger(val)) {
        Integer valInteger = val.getProperty(HASINTEGER).getObject().asLiteral().getInt();
        String string = valInteger.toString();
        if (string.endsWith(DOT_0)) {
            print(string.substring(0, string.length() - 2));
        } else {
            print(string);
        }
    } else if (isBoolean(val)) {
        if (val.hasLiteral(HASBOOLEAN, true)) {
            print(BOOLEAN_TRUE);
        } else if (val.hasLiteral(HASBOOLEAN, false)) {
            print(BOOLEAN_FALSE);
        }
    } else if (isString(val)) {
        print(SINGLE_QUOTE);
        String stringVal = val.getProperty(HASSTRING).getObject().asLiteral().getString();
        for (int i = 0; i < stringVal.length(); i++) {
            char c = stringVal.charAt(i);
            if (c == '\'') {
                print("\'\'");
            } else if (c == '\\') {
                print("\\\\");
            } else if (c >= 32 && c <= 126) {
                // ISO 8859-1
                print("" + c);
            } else if (c < 255) {
                // ISO 10646 and ISO 8859-1 are the same < 255 , using
                // ISO_8859_1
                print("\\X\\" + new String(Hex.encodeHex(
                        Charsets.ISO_8859_1.encode(CharBuffer.wrap(new char[] { (char) c })).array()))
                                .toUpperCase());
            } else {
                if (useIso8859_1) {
                    // ISO 8859-1 with -128 offset
                    ByteBuffer encode = Charsets.ISO_8859_1.encode(new String(new char[] { (char) (c - 128) }));
                    print("\\S\\" + (char) encode.get());
                } else {
                    // The following code has not been tested (2012-04-25)
                    // Use UCS-2 or UCS-4

                    // TODO when multiple sequential characters should be
                    // encoded in UCS-2 or UCS-4, we don't really need to
                    // add all those \X0\ \X2\ and \X4\ chars
                    if (Character.isLowSurrogate(c)) {
                        throw new SerializerException("Unexpected low surrogate range char");
                    } else if (Character.isHighSurrogate(c)) {
                        // We need UCS-4, this is probably never happening
                        if (i + 1 < stringVal.length()) {
                            char low = stringVal.charAt(i + 1);
                            if (!Character.isLowSurrogate(low)) {
                                throw new SerializerException(
                                        "High surrogate char should be followed by char in low surrogate range");
                            }
                            try {
                                print("\\X4\\" + new String(Hex.encodeHex(Charset.forName("UTF-32")
                                        .encode(new String(new char[] { c, low })).array())).toUpperCase()
                                        + "\\X0\\");
                            } catch (UnsupportedCharsetException e) {
                                throw new SerializerException(e);
                            }
                            i++;
                        } else {
                            throw new SerializerException(
                                    "High surrogate char should be followed by char in low surrogate range, but end of string reached");
                        }
                    } else {
                        // UCS-2 will do
                        print("\\X2\\" + new String(Hex
                                .encodeHex(Charsets.UTF_16BE.encode(CharBuffer.wrap(new char[] { c })).array()))
                                        .toUpperCase()
                                + "\\X0\\");
                    }
                }
            }
        }
        print(SINGLE_QUOTE);
    } else if (isEnumeration(val)) {
        String enumVal = val.getLocalName();
        print("." + enumVal + ".");
    } else {
        print(val == null ? "$" : val.toString());
    }
}

From source file:no.kantega.kwashc.server.test.InsecureCryptographicStorageTest.java

private String generateHash(String algorithm, String password) {

    try {/*from   w  w  w . j a va2  s  . c om*/
        final MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
        messageDigest.reset();
        messageDigest.update(password.getBytes(Charset.forName("UTF8")));
        final byte[] resultByte = messageDigest.digest();
        return new String(Hex.encodeHex(resultByte));
    } catch (NoSuchAlgorithmException e) {
        //
        return "";
    }
}