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:Crypto.java

/**
 * this must be called after creating the initial Crypto object. It creates a salt of SALT_LEN bytes
 * and generates the salt bytes using secureRandom().  The encryption secret key is created 
 * along with the initialization vectory. The member variable mEcipher is created to be used
 * by the class later on when either creating a CipherOutputStream, or encrypting a buffer
 * to be written to disk./*from   www.j a v  a 2s  . c  o m*/
 *  
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidParameterSpecException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws UnsupportedEncodingException
 * @throws InvalidKeyException
 */
public void setupEncrypt() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException,
        UnsupportedEncodingException, InvalidKeyException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;

    // crate secureRandom salt and store  as member var for later use
    mSalt = new byte[SALT_LEN];
    SecureRandom rnd = new SecureRandom();
    rnd.nextBytes(mSalt);
    Db("generated salt :" + Hex.encodeHexString(mSalt));

    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

    /* 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
     */
    KeySpec spec = new PBEKeySpec(mPassword.toCharArray(), mSalt, ITERATIONS, KEYLEN_BITS);
    tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    /* Create the Encryption cipher object and store as a member variable
     */
    mEcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    mEcipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = mEcipher.getParameters();

    // get the initialization vectory and store as member var 
    mInitVec = params.getParameterSpec(IvParameterSpec.class).getIV();

    Db("mInitVec is :" + Hex.encodeHexString(mInitVec));
}

From source file:com.imaginea.kodebeagle.base.util.Utils.java

@NotNull
public String getDigestAsString(final String trimmedFileName)
        throws UnsupportedEncodingException, NoSuchAlgorithmException {
    MessageDigest crypt = MessageDigest.getInstance("SHA-1");
    crypt.reset();/*from ww  w. j  av  a  2  s  . c o m*/
    crypt.update(trimmedFileName.getBytes(StandardCharsets.UTF_8));
    // We think 10 chars is safe enough to rely on.
    return Hex.encodeHexString(crypt.digest()).substring(0, 10);
}

From source file:net.solarnetwork.node.hw.sma.test.SmaPacketTest.java

@Test
public void encodeGetChannelInfo() {
    SmaPacket p = SmaPacket.getChannelInfoPacket(8888, 2);
    byte[] packet = p.getPacket();
    log.debug("Got packet: " + Hex.encodeHexString(packet));
    assertNotNull("Packet", packet);
    assertArrayEquals(TestUtils.bytesFromHexString("B8 22 02 00 00 00 09"), packet);
}

From source file:com.hp.autonomy.hod.client.util.Hmac.java

private <T> String createBodyHash(final Map<String, List<T>> body) {
    if (body == null || body.isEmpty()) {
        // If no body, the body hash must be the empty string
        return EMPTY;
    } else {/*w  w  w . j  a  va2s.  co  m*/
        final List<String> components = encodeAndSpreadParameterMap(body, input -> {
            final byte[] bytes;

            if (input instanceof byte[]) {
                bytes = (byte[]) input;
            } else {
                bytes = bytesFromString(input.toString());
            }

            return Hex.encodeHexString(md5Hash(bytes));
        });

        final String bodyRepresentation = StringUtils.join(components, NEW_LINE);
        return base64EncodeForUri(md5Hash(bytesFromString(bodyRepresentation)));
    }
}

From source file:eu.xworlds.util.raknet.protocol.OpenConnectionRequest1.java

@Override
public String toString() {
    return "OpenConnectionRequest1 [magic=" + tohex(this.magic) + ", procotolVersion=" + this.procotolVersion //$NON-NLS-1$//$NON-NLS-2$
            + ", mtuPayload=" + Hex.encodeHexString(this.mtuPayload) + "]"; //$NON-NLS-1$ //$NON-NLS-2$
}

From source file:co.edu.uniandes.csw.Arquidalgos.usuario.service.UsuarioService.java

@POST
@Path("/darAmigos")
public List<UsuarioDTO> darAmigos(UsuarioDTO usuario) throws Exception {
    System.out.println("Dar amigos service de: " + usuario.getFacebookId());
    Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    String key = "123";
    SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256");
    sha256_HMAC.init(secret_key);//ww w  .  j a  va 2  s  .c  o  m

    System.out.println("TO String: " + usuario.toString());

    String hash = Hex.encodeHexString(sha256_HMAC.doFinal(usuario.toString().getBytes()));
    System.out.println("CODIGO HASH: " + hash);
    System.out.println("CODIGO HASH JSON " + usuario.getHash());

    boolean alterado = !(hash.equalsIgnoreCase(usuario.getHash()));
    System.out.println("Alterado: " + alterado);

    if (alterado) {
        throw new Exception("Se han alterado los datos");
    }

    return this.usuarioLogicService.darAmigosUsuario(usuario.getFacebookId());
}

From source file:eu.europa.esig.dss.pades.signature.PAdESLevelLTTest.java

@Override
protected void onDocumentSigned(byte[] byteArray) {
    try {/* www  .  j  a v  a  2  s. c  om*/
        ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);

        PDDocument pdDoc = PDDocument.load(bais);
        List<PDSignature> sigs = pdDoc.getSignatureDictionaries();
        PDSignature pdSignature = sigs.get(0);
        byte[] contents = pdSignature.getContents(byteArray);

        byte[] digest = DSSUtils.digest(DigestAlgorithm.SHA1, contents);
        String hex = Hex.encodeHexString(digest).toUpperCase();

        String pdfString = new String(byteArray, "UTF-8");
        assertTrue(pdfString.contains(hex));
    } catch (Exception e) {
        throw new DSSException(e);
    }
}

From source file:com.edwardsit.spark4n6.piggybank.evaluation.hash.Hash.java

/**
 * @see org.apache.pig.EvalFunc#exec(org.apache.pig.data.Tuple)
 * The first argument in scripts must be a string, the 
 * {@link java.security.MessageDigest} algorithm to calculate, and the 
 * second is the field containing the data to be hashed.
 *///ww  w .  j  a  v a2s . c om
@Override
public String exec(Tuple input) throws IOException {
    String algo = null;
    DataBag bag = null;
    Tuple t = null;
    if (md == null && input.get(0) instanceof String) {
        try {
            algo = (String) input.get(0);
            md = MessageDigest.getInstance(algo);
        } catch (NoSuchAlgorithmException e) {
            throw new IOException("No such algorithm '" + algo + "'", e);
        }
    }
    if (input.get(1) instanceof DataBag) {
        bag = (DataBag) input.get(1);
        if (algo == null || bag == null)
            throw new IOException(this.getClass().getName() + "(algorithm: chararray, dataField: bag)");
        for (Iterator<Tuple> it = bag.iterator(); it.hasNext();) {
            t = it.next();
            if (t != null && t.size() > 0 && t.get(0) != null && (t.get(0)) instanceof DataByteArray) {
                md.update(((DataByteArray) t.get(0)).get());
            }
        }
    }
    return Hex.encodeHexString(md.digest());
}

From source file:com.coinkite.CoinkiteSigningRequestInterceptor.java

public String[] createSigAndTimestamp(String url) throws NoSuchAlgorithmException, InvalidKeyException {
    String apiSecret = getApiSecret();
    SecretKeySpec signingKey = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), HMAC_SHA512_ALG);

    Mac mac = Mac.getInstance(HMAC_SHA512_ALG);
    mac.init(signingKey);/*  www .  java2s  . co  m*/

    String ts = getDateTime().format(ISO_DATE_TIME);

    byte[] bytes = mac.doFinal(getData(url, ts));
    String encoded = Hex.encodeHexString(bytes);

    return new String[] { encoded, ts };
}

From source file:com.lightboxtechnologies.nsrl.HashRecordProcessorTest.java

@Test
public void processJustRightCols() throws BadDataException, DecoderException {
    final HashData hd = new HashData(sha1, md5, crc32, name, size, prod_code, os_code, special_code);

    final RecordProcessor<HashData> proc = new HashRecordProcessor();

    assertEquals(hd,//from w ww .jav a2 s  . com
            proc.process(new String[] { Hex.encodeHexString(sha1), Hex.encodeHexString(md5),
                    Hex.encodeHexString(crc32), name, String.valueOf(size), String.valueOf(prod_code), os_code,
                    special_code }));
}