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:pl.umk.mat.zawodyweb.database.pojo.Users.java

public String hashPass(String password) {
    try {/*  ww w .  j  a va  2  s .  c  o m*/
        MessageDigest md = MessageDigest.getInstance("SHA1");
        md.update((login + "+" + password).getBytes());
        byte[] digest = md.digest();
        org.apache.commons.codec.binary.Hex hex = new Hex();
        return new String(hex.encode(digest));
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(Users.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:rapture.kernel.AdminApiImpl.java

private String generateSecureToken() {
    try {//w ww  .j ava2 s . co  m
        // get secure random
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        byte bytes[] = new byte[128];
        random.nextBytes(bytes);
        // get its digest
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        byte[] result = sha.digest(bytes);
        // encode to hex
        return (new Hex()).encodeHexString(result);
    } catch (NoSuchAlgorithmException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, e.getMessage());
    }
}

From source file:staging.plugin.StagingUtils.java

/**
 * @param stageFileStore//  w w  w  .  j a  v  a  2 s. c  o  m
 * @return
 */
public static String fetchMD5Digest(IFileStore fileStore, IProgressMonitor monitor) throws CoreException {
    String result = null;
    IFileInfo info = null;
    monitor.beginTask("Retreiving staged file and calculating checksum", 100);
    info = fileStore.fetchInfo();
    if (info.getLength() == 0) {
        return "d41d8cd98f00b204e9800998ecf8427e";
    }
    MessageDigest messageDigest;
    try {
        messageDigest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new CoreException(new Status(Status.ERROR, StagingPlugin.PLUGIN_ID,
                "Cannot create checksum without MD5 algorithm.", e));
    }
    messageDigest.reset();
    byte[] buffer = new byte[chunkSize];
    int bytesRead = 0;
    int totalBytesRead = 0;
    int progressTickBytes = (int) info.getLength() / 100;
    if (progressTickBytes == 0) {
        progressTickBytes = 1; // prevents divide by zero on files less
        // than 100 bytes
    }
    BufferedInputStream in = new BufferedInputStream(fileStore.openInputStream(EFS.NONE, null));
    try {
        while ((bytesRead = in.read(buffer, 0, chunkSize)) != -1) {
            messageDigest.update(buffer, 0, bytesRead);
            totalBytesRead = totalBytesRead + bytesRead;
            if ((totalBytesRead % progressTickBytes) < bytesRead) {
                monitor.worked(1);
            }
        }
    } catch (IOException e) {
        throw new CoreException(new Status(Status.ERROR, StagingPlugin.PLUGIN_ID,
                "Cannot read file store to calculate MD5 digest.", e));
    }
    Hex hex = new Hex();
    result = new String(hex.encode(messageDigest.digest()));
    monitor.done();
    return result;
}

From source file:staging.plugin.StagingUtils.java

public static final String copyWithMD5Digest(IFileStore source, IFileStore destination, IFileInfo sourceInfo,
        IProgressMonitor monitor) throws CoreException {
    // TODO honor cancellation requests during copy
    // TODO report progress
    log.debug("source: {}", source);
    log.debug("destination: {}", destination);
    // monitor.subTask("Copying file " + source.getName() + "...");
    String result = null;//from  www  .ja  v  a2  s .  com
    byte[] buffer = new byte[chunkSize];
    int length = (int) sourceInfo.getLength();
    int progressTickBytes = length / 100;
    int bytesRead = 0;
    int totalBytesCopied = 0;
    InputStream in = null;
    OutputStream out = null;
    try {
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new CoreException(new Status(Status.ERROR, StagingPlugin.PLUGIN_ID,
                    "Cannot compare checksums without MD5 algorithm.", e));
        }
        messageDigest.reset();
        in = new BufferedInputStream(source.openInputStream(EFS.NONE, null), 1024 * 64);
        destination.getParent().mkdir(EFS.NONE, null);
        out = new BufferedOutputStream(destination.openOutputStream(EFS.NONE, null), 1024 * 64);
        while ((bytesRead = in.read(buffer, 0, chunkSize)) != -1) {
            if (monitor.isCanceled()) {
                throw new CoreException(
                        new Status(IStatus.CANCEL, StagingPlugin.PLUGIN_ID, "Staging cancelled"));
            }
            out.write(buffer, 0, bytesRead);
            messageDigest.update(buffer, 0, bytesRead);
            totalBytesCopied = totalBytesCopied + bytesRead;
            if (totalBytesCopied > 0 && progressTickBytes > 0) {
                if ((totalBytesCopied % progressTickBytes) < bytesRead) {
                    monitor.worked(1);
                    // if (length > 0) {
                    // int percent = (int) (100.0 * ((float)
                    // totalBytesCopied / length));
                    // monitor.subTask(percent + "% (" + totalBytesCopied /
                    // 1024 + "/" + length / 1024 + "K)");
                    // }
                }
            }
        }
        Hex hex = new Hex();
        result = new String(hex.encode(messageDigest.digest()));
    } catch (IOException e) {
        throw new CoreException(new Status(Status.ERROR, StagingPlugin.PLUGIN_ID, e.getLocalizedMessage(), e));
    } finally {
        try {
            if (out != null) {
                out.flush();
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            log.error("Trouble closing i/o resources", e);
        }
    }
    return result;
}

From source file:staging.plugin.StagingUtils.java

/**
 * @param sourceFileStore/* w  w w .j a  v a2 s.c om*/
 * @param sourceFileInfo
 * @param checksumMonitor
 * @return
 * @throws CoreException
 */
private static String checksumWithMD5Digest(IFileStore source, IFileInfo sourceInfo, IProgressMonitor monitor)
        throws CoreException {
    // TODO honor cancellation requests during copy
    // TODO report progress
    log.info("source: {}", source);
    String result = null;
    byte[] buffer = new byte[chunkSize];
    int length = (int) sourceInfo.getLength();
    int progressTickBytes = length / 100;
    int bytesRead = 0;
    int totalBytesCopied = 0;
    InputStream in = null;
    try {
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new CoreException(new Status(Status.ERROR, StagingPlugin.PLUGIN_ID,
                    "Cannot compare checksums without MD5 algorithm.", e));
        }
        messageDigest.reset();
        in = new BufferedInputStream(source.openInputStream(EFS.NONE, null), 1024 * 64);
        while ((bytesRead = in.read(buffer, 0, chunkSize)) != -1) {
            messageDigest.update(buffer, 0, bytesRead);
            totalBytesCopied = totalBytesCopied + bytesRead;
            if (totalBytesCopied > 0 && progressTickBytes > 0) {
                if ((totalBytesCopied % progressTickBytes) < bytesRead) {
                    monitor.worked(1);
                    // if (length > 0) {
                    // int percent = (int) (100.0 * ((float)
                    // totalBytesCopied / length));
                    // monitor.subTask(percent + "% (" + totalBytesCopied /
                    // 1024 + "/" + length / 1024 + "K)");
                    // }
                }
            }
        }
        Hex hex = new Hex();
        result = new String(hex.encode(messageDigest.digest()));
    } catch (IOException e) {
        throw new CoreException(new Status(Status.ERROR, StagingPlugin.PLUGIN_ID, e.getLocalizedMessage(), e));
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            log.error("Trouble closing i/o resources", e);
        }
    }
    return result;
}

From source file:test.frames.CryptoServiceSingleton.java

/**
 * Sign a message with a key./*from w  w w.ja  v  a  2s .  c  om*/
 *
 * @param message The message to sign
 * @param key     The key to use
 * @return The signed message (in hexadecimal)
 */
public String sign(String message, byte[] key) {
    try {
        // Get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key, HMAC_SHA_1);

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

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

        // 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 IllegalArgumentException(e);
    }
}

From source file:tkwatch.Utilities.java

/**
 * Generates the signature necessary to make a TradeKing API call. Adapted
 * from the <i>TradeKing API Reference Guide</i>, 03.25.2011, p. 51.
 * //from  w  w w  .j  a va 2 s  .c  o  m
 * @param data
 *            Concatenation of the API request body and a timestamp.
 * @param key
 *            The user's secret key.
 * @return Returns the necessary signature.
 * @throws java.security.SignatureException
 *             Thrown if the md5 hash-based message authentication code
 *             can't be generated.
 */
public static final String generateSignature(final String data, final String key)
        throws java.security.SignatureException {
    String result;
    try {
        byte[] encodedData = Base64.encodeBase64(data.getBytes());
        // Get an hmac_md5 key from the raw key bytes
        byte[] keyBytes = key.getBytes();
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacMD5");
        // Get an hmac_md5 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacMD5");
        mac.init(signingKey);
        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(encodedData);
        // Convert raw bytes to Hex
        byte[] hexBytes = new Hex().encode(rawHmac);
        // Covert array of Hex bytes to a String
        result = new String(hexBytes, "ISO-8859-1");
    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
    return result;
}

From source file:tor.HiddenService.java

public static void sendIntroduce(TorSocket sock, String onion, TorCircuit rendz) throws IOException {
    log.debug("Fetching Hidden Service Descriptor");
    String hsdescTxt = fetchHSDescriptor(sock, onion);
    OnionRouter rendzOR = rendz.getLastHop().router;

    // parse the hidden service descriptor
    TorDocumentParser hsdesc = new TorDocumentParser(hsdescTxt);
    //decode the intro points
    String intopointsb64 = new String(Base64.decode(hsdesc.map.get("introduction-points")));
    // parse intro points document
    TorDocumentParser intros = new TorDocumentParser(intopointsb64);
    // get first intro point
    String introPointIdentities[] = intros.getArrayItem("introduction-point");

    int introPointNum = 0;

    String ip0 = Hex.encodeHexString(new Base32().decode(introPointIdentities[introPointNum].toUpperCase()));
    OnionRouter ip0or = Consensus.getConsensus().routers.get(ip0);
    byte[] serviceKey = Base64.decode(intros.getArrayItem("service-key")[introPointNum]);
    byte skHash[] = TorCrypto.getSHA1().digest(serviceKey);
    assert (skHash.length == 20);
    log.debug("Using Intro Point: {}, building circuit...", ip0or);

    TorCircuit ipcirc = sock.createCircuit(true);
    ipcirc.create();//from w ww  . j  ava2 s .c  o  m
    ipcirc.extend(ip0or);

    // outer packet
    ByteBuffer buf = ByteBuffer.allocate(1024);
    buf.put(skHash); // service PKhash

    // inner handshake
    ByteBuffer handshake = ByteBuffer.allocate(1024);
    handshake.put((byte) 2); //ver
    handshake.put(rendzOR.ip.getAddress()); // rendz IP addr
    handshake.putShort((short) rendzOR.orport);
    try {
        handshake.put(new Hex().decode(rendzOR.identityhash.getBytes()));
    } catch (DecoderException e) {
        e.printStackTrace();
    }
    handshake.putShort((short) rendzOR.onionKeyRaw.length); // rendz key len
    handshake.put(rendzOR.onionKeyRaw); // rendz key
    handshake.put(rendz.rendezvousCookie); //rend cookie

    // tap handshake / create handshake
    byte priv_x[] = new byte[128];
    TorCrypto.rnd.nextBytes(priv_x); // g^x
    rendz.temp_x = TorCrypto.byteToBN(priv_x);
    rendz.temp_r = null;

    BigInteger pubKey = TorCrypto.DH_G.modPow(rendz.temp_x, TorCrypto.DH_P);
    byte pubKeyByte[] = TorCrypto.BNtoByte(pubKey);
    handshake.put(pubKeyByte);

    handshake.flip();

    // convert to byte array
    byte handshakeBytes[] = new byte[handshake.remaining()];
    handshake.get(handshakeBytes);

    // encrypt handshake
    PublicKey skPK = TorCrypto.asn1GetPublicKey(serviceKey);
    buf.put(TorCrypto.hybridEncrypt(handshakeBytes, skPK));

    buf.flip();
    byte introcell[] = new byte[buf.remaining()];
    buf.get(introcell);

    ipcirc.send(introcell, TorCircuit.RELAY_COMMAND_INTRODUCE1, false, (short) 0);
    log.debug("waiting for introduce acknowledgement");
    ipcirc.waitForState(TorCircuit.STATES.INTRODUCED, false);

    log.debug("Now waiting for rendezvous connect");
    rendz.waitForState(TorCircuit.STATES.RENDEZVOUS_COMPLETE, false);

    ipcirc.destroy(); // no longer needed
    log.debug("Hidden Service circuit built");
}

From source file:uk.ac.ox.webauth.crypto.Des3CbcSha1Kd.java

private static void test_nFold(String data, String input, String correct, int numBits) throws DecoderException {
    Hex hex = new Hex();
    byte[] output = nFold((byte[]) hex.decode(input), numBits);
    if (Arrays.equals((byte[]) hex.decode(correct), output)) {
        System.out.println("PASSED: " + numBits + "-fold of string '" + data + "'.");
    } else {/*from www .j  a va 2s .c  om*/
        System.err.println("FAILED: " + numBits + "-fold of string '" + data + "'.");
    }
}

From source file:uk.ac.ox.webauth.crypto.Des3CbcSha1Kd.java

private static void test_DR_DK(String key, String usage, String correct_dr, String correct_dk)
        throws DecoderException, GeneralSecurityException {
    Hex hex = new Hex();
    byte[] input = (byte[]) hex.decode(key);
    byte[] constant = (byte[]) hex.decode(usage);
    byte[] dr = (byte[]) hex.decode(correct_dr);
    byte[] dk = (byte[]) hex.decode(correct_dk);
    System.out.println("Testing DR/DK, usage: " + usage + ", key: " + key);
    byte[] output = dr(input, constant);
    if (Arrays.equals(output, dr)) {
        System.out.println("PASSED: DR");
    } else {/*from  w  w  w  .ja v  a2s  . co m*/
        System.err.println("FAILED: DR");
    }
    output = dk(input, constant);
    if (Arrays.equals(output, dk)) {
        System.out.println("PASSED: DK");
    } else {
        System.err.println("FAILED: DK");
    }
}