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.vmware.o11n.plugin.crypto.service.CryptoEncodingService.java

/**
 *
 * @param b32data//from   ww  w .java  2  s.  c o m
 * @return
 */
public String base32toHex(String b32data) {
    //decode base32
    Base32 b32 = new Base32();
    byte[] data = b32.decode(b32data);
    //encode hex
    String hexDataString = Hex.encodeHexString(data);
    return hexDataString;
}

From source file:com.streamsets.lib.security.http.PasswordHasher.java

protected String computeHash(String version, int iterations, byte[] salt, String valueTohash) {
    long start = System.currentTimeMillis();
    try {/*from w ww  .j av  a  2s .  c om*/
        // yield CPU when this method is run in a tight loop
        Thread.yield();
        PBEKeySpec spec = new PBEKeySpec(valueTohash.toCharArray(), salt, iterations, getKeyLength());
        byte[] hash = SECRET_KEY_FACTORIES.get(version).generateSecret(spec).getEncoded();
        return version + ":" + iterations + ":" + Hex.encodeHexString(salt) + ":" + Hex.encodeHexString(hash);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        LOG.trace("Computing password hash '{}' with '{}' iterations took '{}msec'", version, iterations,
                System.currentTimeMillis() - start);
    }
}

From source file:fr.eo.util.dumper.Dumper.java

private static String getCompressedString(String value) {

    byte[] output = new byte[8096];

    try {//from   ww  w .  j a va2  s  .  c  om
        byte[] input = value.getBytes("UTF-8");
        Deflater compresser = new Deflater(Deflater.BEST_COMPRESSION, true);
        compresser.setInput(input);
        compresser.finish();
        int compressedDataLength = compresser.deflate(output);
        return "X'" + Hex.encodeHexString(Arrays.copyOf(output, compressedDataLength)) + "'";
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:Crypto.java

/**
 * If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv). 
 * We have the password from initializing the class. pass the iv and salt here which is
 * obtained when encrypting the file initially.
 *   //from w  ww . ja v a  2s . co  m
 * @param initvec
 * @param salt
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws DecoderException
 */
public void setupDecrypt(String initvec, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException,
        NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, DecoderException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;
    SecretKey secret = null;

    // since we pass it as a string of input, convert to a actual byte buffer here
    mSalt = Hex.decodeHex(salt.toCharArray());
    Db("got salt " + Hex.encodeHexString(mSalt));

    // get initialization vector from passed string
    mInitVec = Hex.decodeHex(initvec.toCharArray());
    Db("got initvector :" + Hex.encodeHexString(mInitVec));

    /* Derive the key, given password and salt. */
    // in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
    // The end user must also install them (not compiled in) so beware. 
    // see here: 
    // http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(mPassword.toCharArray(), mSalt, ITERATIONS, KEYLEN_BITS);

    tmp = factory.generateSecret(spec);
    secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    /* Decrypt the message, given derived key and initialization vector. */
    mDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    mDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(mInitVec));
}

From source file:com.bitbreeds.webrtc.sctp.impl.SCTPImpl.java

/**
 * Handle message and create a response/*  w w  w.j  a  v a 2  s  .c o m*/
 * @param input the incoming message
 * @return a byte response, an empty array is equal to no response.
 */
public List<byte[]> handleRequest(byte[] input) {
    SCTPMessage inFullMessage = SCTPMessage.fromBytes(input);

    logger.debug("Input Parsed: " + inFullMessage);

    logger.debug("Flags: " + Hex.encodeHexString(new byte[] { input[13] }));

    SCTPHeader inHdr = inFullMessage.getHeader();
    List<SCTPChunk> inChunks = inFullMessage.getChunks();

    return inChunks.stream().map(chunk -> {
        MessageHandler handler = handlerMap.get(chunk.getType());
        if (handler != null) {

            Optional<SCTPMessage> out = handler.handleMessage(this, context, inHdr, chunk);
            return out.map(i -> SCTPUtil.addChecksum(i).toBytes()).orElse(new byte[] {});
        } else {
            logger.warn("Not handled messagetype: " + chunk.getType());
            return new byte[] {};
        }
    }).collect(Collectors.toList());
}

From source file:com.bitbreeds.webrtc.sctp.model.SCTPChunk.java

@Override
public String toString() {
    return "SCTPChunk{" + "type=" + type + ", flags=" + flags + ", length=" + length + ", fixed=" + fixed
            + ", variable=" + variable + ", rest=" + Hex.encodeHexString(rest) + '}';
}

From source file:edu.umkc.sce.VpQuery.java

private void runTestQuery(int queryIndex, Model model, String query) {
    System.out.printf("executing [%d] %s", queryIndex, query);
    QueryExecution qe = null;/*w w w  .  ja v a 2 s . co m*/
    String result = null;
    try {

        qe = QueryExecutionFactory.create(query, model);
        ResultSet results = qe.execSelect();
        byte[] hash = getResultHash(results);

        result = Hex.encodeHexString(hash);

        ResultSetFormatter.out(System.out, results);
    } finally {

        qe.close();
    }
    System.out.flush();
    if (hashes[queryIndex].equalsIgnoreCase(result)) {
        System.out.printf("\nQuery [%d] passed assertion\n\n", queryIndex);

    } else {
        System.err.printf("\nQuery [%d] failed assertion %s\n", queryIndex, result);
    }
}

From source file:com.threadswarm.imagefeedarchiver.processor.RssItemProcessor.java

private void downloadRssMediaContent(ProcessedRssItem processedItem, RssMediaContent mediaContent) {
    DownloadStatus downloadStatus = DownloadStatus.FAILED;
    HttpEntity responseEntity = null;/*from w  w w .ja v a2  s .co  m*/
    try {
        String targetUrlString = mediaContent.getUrlString();
        if (forceHttps)
            targetUrlString = FeedUtils.rewriteUrlStringToHttps(targetUrlString);

        URI targetURI = FeedUtils.getUriFromUrlString(targetUrlString);

        boolean freshURI = processedURISet.add(targetURI);
        if (!freshURI) {
            LOGGER.warn("Skipping previously processed URI: {}", targetURI);
            return; //abort processing
        }

        LOGGER.info("Attempting to download {}", targetURI);
        HttpGet imageGet = new HttpGet(targetURI);

        for (Header header : headerList)
            imageGet.addHeader(header);

        HttpResponse imageResponse = httpClient.execute(imageGet);

        String originalFileName = StringUtils.stripStart(targetURI.toURL().getFile(), "/");
        originalFileName = StringUtils.replace(originalFileName, "/", "_");
        File outputFile = getOutputFile(originalFileName);

        long expectedContentLength = FeedUtils.calculateBestExpectedContentLength(imageResponse, mediaContent);
        responseEntity = imageResponse.getEntity();

        BufferedInputStream bis = null;
        DigestOutputStream fos = null;
        int bytesRead = 0;
        try {
            bis = new BufferedInputStream(responseEntity.getContent());
            fos = new DigestOutputStream(new FileOutputStream(outputFile), MessageDigest.getInstance("SHA"));

            byte[] buffer = new byte[8192];
            while ((bytesRead = bis.read(buffer, 0, buffer.length)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            fos.flush();

            MessageDigest messageDigest = fos.getMessageDigest();
            byte[] digestBytes = messageDigest.digest();
            String digestString = Hex.encodeHexString(digestBytes);
            LOGGER.info("Downloaded - {} (SHA: {})", targetURI, digestString);

            processedItem.setDownloadDate(new Date());
            downloadStatus = DownloadStatus.COMPLETED;
            processedItem.setHash(digestString);
            processedItem.setFilename(outputFile.toString());
        } catch (ConnectionClosedException e) {
            LOGGER.error("An Exception was thrown while attempting to read HTTP entity content", e);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("The SHA-1 hashing algorithm is not available on this JVM", e);
        } finally {
            IOUtils.closeQuietly(bis);
            IOUtils.closeQuietly(fos);
            EntityUtils.consumeQuietly(responseEntity);
            if (downloadStatus == DownloadStatus.FAILED
                    || (outputFile.exists() && outputFile.length() != expectedContentLength)) {
                LOGGER.warn("Deleted partial/failed file: {}", outputFile);
                outputFile.delete();
                processedItem.setDownloadStatus(DownloadStatus.FAILED);
            }
        }
    } catch (IOException e) {
        LOGGER.error("An Exception was thrown while attempting to download image content", e);
    } catch (URISyntaxException e) {
        LOGGER.error("The supplied URI, {}, violates syntax rules", e);
    } finally {
        EntityUtils.consumeQuietly(responseEntity);
    }

    processedItem.setDownloadStatus(downloadStatus);
    itemDAO.save(processedItem);
}

From source file:com.weblyzard.lib.string.nilsimsa.Nilsimsa.java

/**
 * @return a String representation of the current state of
 *          the Nilsimsa object. 
 */
public String hexdigest() {
    return Hex.encodeHexString(digest());
}

From source file:alfio.plugin.mailchimp.MailChimpPlugin.java

static String getMd5Email(String email) {
    try {/*  w  w w . ja va 2 s. c  om*/
        return Hex.encodeHexString(MessageDigest.getInstance("MD5").digest(email.trim().getBytes("UTF-8")));
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
        return email;//should never happen...
    }
}