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.metadata.source.impl.MetadataSourceBase.java

protected boolean updateDigest(byte[] newDigest) {
    // Construct string from both digests to form log statement
    String newDigestString = new String(Hex.encodeHex(newDigest));
    String digestString = new String(Hex.encodeHex(this.digest));
    this.logger.debug("Metadata source {} - comparing new digest {} to previous {}.",
            new Object[] { this.getLocation(), newDigestString, digestString });

    // Compare and update
    if (!MessageDigest.isEqual(this.digest, newDigest)) {
        this.digest = newDigest;

        this.logger.info(
                "Metadata source {} - document has been updated and will be updated in the cache. New hash: {}. Old hash: {}",
                new Object[] { this.getLocation(), newDigestString, digestString });

        return true;
    }//from w  ww .j a  v  a  2  s . co m

    return false;
}

From source file:eu.peppol.security.OxalisCipherConverter.java

/**
 * Encrypts the secret key (symmetric key) held inside the OxalisCipher instance using the supplied PublicKey, after
 * which the resulting wrapped secret key is transformed into a hex string suitable for transmission, persistence etc.
 *
 * @param publicKey the public asymmetric key to use for encrypting the secret symmetric key
 * @param oxalisCipher the instance of OxalisCipher in which the secret symmetric key is held.
 * @return// w  w  w.  j a va2  s.  com
 */
public String getWrappedSymmetricKeyAsString(PublicKey publicKey, OxalisCipher oxalisCipher) {

    try {
        Cipher cipher = Cipher.getInstance(StatisticsKeyTool.ASYMMETRIC_KEY_ALGORITHM);
        cipher.init(Cipher.WRAP_MODE, publicKey);
        SecretKey secretKey = oxalisCipher.getSecretKey();
        byte[] encodedBytes = cipher.wrap(secretKey);

        return new String(Hex.encodeHex(encodedBytes));

    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(
                "Unable to create cipher with algorithm: " + StatisticsKeyTool.ASYMMETRIC_KEY_ALGORITHM, e);
    } catch (NoSuchPaddingException e) {
        throw new IllegalStateException("Unable to create cipher with default padding for algorithm "
                + StatisticsKeyTool.ASYMMETRIC_KEY_ALGORITHM, e);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException("The public key is invalid " + e.getMessage(), e);
    } catch (IllegalBlockSizeException e) {
        throw new IllegalStateException("Error during encryption of symmetric key: " + e.getMessage(), e);
    }
}

From source file:com.amazonaws.tvm.Utilities.java

public static String generateRandomString() {
    byte[] randomBytes = RANDOM.generateSeed(16);
    String randomString = new String(Hex.encodeHex(randomBytes));
    return randomString;
}

From source file:com.annuletconsulting.homecommand.node.AsyncSend.java

/**
 * Creates the signature from the timestamp using the sharedKey.  This same method will be used
 * on the server and the results compared to authenticate the request.
 * //  w  w w  . jav a2 s .c  o m
 * @param timeStamp
 * @return
 */
private static String getSignature(String timeStamp) {
    if (sharedKey != null)
        try {
            byte[] data = timeStamp.getBytes(ENCODING_FORMAT);
            Mac mac = Mac.getInstance(SIGNATURE_METHOD);
            mac.init(new SecretKeySpec(sharedKey.getBytes(ENCODING_FORMAT), SIGNATURE_METHOD));
            char[] signature = Hex.encodeHex(mac.doFinal(data));
            return new String(signature);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    return "Error in getSignature()";
}

From source file:be.fedict.eid.applet.service.impl.UserIdentifierUtil.java

/**
 * Gives back a non-reversible citizen identifier (NRCID).
 * /*from  w  w  w .  j  a  v a 2s.c o  m*/
 * @param userId
 *            the primary user identifier, i.e. the national registry
 *            number.
 * @param orgId
 *            the optional organization identifier.
 * @param appId
 *            the optional application identifier.
 * @param secret
 *            the application specific secret. Should be at least 128 bit
 *            long. Encoded in hexadecimal format.
 * @return
 */
public static String getNonReversibleCitizenIdentifier(String userId, String orgId, String appId,
        String secret) {
    if (null == secret) {
        throw new IllegalArgumentException("secret key is null");
    }
    /*
     * Avoid XML formatting issues introduced by some web.xml XML editors.
     */
    secret = secret.trim();
    if (null != orgId) {
        orgId = orgId.trim();
    } else {
        LOG.warn("it is advised to use an orgId");
    }
    if (null != appId) {
        appId = appId.trim();
    } else {
        LOG.warn("it is advised to use an appId");
    }

    /*
     * Decode the secret key.
     */
    byte[] secretKey;
    try {
        secretKey = Hex.decodeHex(secret.toCharArray());
    } catch (DecoderException e) {
        LOG.error("secret is not hexadecimal encoded: " + e.getMessage());
        throw new IllegalArgumentException("secret is not hexadecimal encoded");
    }
    if ((128 / 8) > secretKey.length) {
        /*
         * 128 bit is seen as secure these days.
         */
        LOG.warn("secret key is too short");
        throw new IllegalArgumentException("secret key is too short");
    }

    /*
     * Construct the HMAC input sequence.
     */
    String input = userId;
    if (null != appId) {
        input += appId;
    }
    if (null != orgId) {
        input += orgId;
    }
    byte[] inputData = input.getBytes();

    SecretKey macKey = new SecretKeySpec(secretKey, HMAC_ALGO);
    Mac mac;
    try {
        mac = Mac.getInstance(macKey.getAlgorithm());
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("HMAC algo not available: " + e.getMessage());
    }
    try {
        mac.init(macKey);
    } catch (InvalidKeyException e) {
        LOG.error("invalid secret key: " + e.getMessage(), e);
        throw new RuntimeException("invalid secret");
    }
    mac.update(inputData);
    byte[] resultHMac = mac.doFinal();
    String resultHex = new String(Hex.encodeHex(resultHMac)).toUpperCase();
    return resultHex;
}

From source file:it.staiger.jmeter.services.FileContentServer.java

/**
 * Get String of SHA256 hash for provided byte array,
 * @param content byte array/*www  .j  ava  2  s.  co m*/
 * @return String SHA256 hash
 */
private String getSHA256(byte[] content) {
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        return new String(Hex.encodeHex(md.digest(content)));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.ccstats.crypto.AESWorker.java

/**
 * Through the power of the advanced encryption standard, a plaintext will be encrypted with a parameter-specified
 * password, an extra protective layer (salt), and a specified key length. Make sure to acquire the salt and ivBytes
 * as they are necessary for decrypting the encrypted result.
 *
 * Firstly, The password is obtained and instantly overridden with the hashed version of the password, allowing
 * for stronger security as the plaintext password will not be used. Second, an arbitrary salt is securely
 * generated. Finally, the encryption standard is carried out and the encrypted text is obtained.
 *
 * @param password the password as a char array.
 * @param text The plaintext bytes to be encrypted.
 *
 * @return The Encrypted text in hexadecimal format.
 *//*from   w w  w .j av a2s. com*/
public char[] encrypt(char[] password, byte[] text)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        InvalidParameterSpecException, BadPaddingException, IllegalBlockSizeException {

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    if (Cipher.getMaxAllowedKeyLength("AES") < this.keyLength) {
        this.keyLength = Cipher.getMaxAllowedKeyLength("AES");
        System.err.printf(
                "WARNING: YOUR MAXIMUM AES KEY LENGTH POLICY IS %d BITS. KEY LENGTH LIMITED TO %d BITS.\n",
                this.keyLength, this.keyLength);
    }

    // hash the password and acquire a securely and randomly generated salt
    password = hash(new String(password).getBytes(StandardCharsets.UTF_8));
    byte[] salt = new byte[20];
    new SecureRandom().nextBytes(salt);

    // acquire the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password, salt, 16384, this.keyLength);
    SecretKey key = factory.generateSecret(spec);
    SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");

    // init the cipher and process the encryption
    cipher.init(Cipher.ENCRYPT_MODE, keySpec);
    AlgorithmParameters ap = cipher.getParameters();
    byte[] ivBytes = ap.getParameterSpec(IvParameterSpec.class).getIV();
    byte[] result = cipher.doFinal(text);

    return Hex.encodeHex(mergeByteArrays(ivBytes, result, salt));
}

From source file:de.innovationgate.webgate.api.jdbc.filehandling.CS5P4FileHandling.java

public void storeFileContents(CS5P4FileAttachmentEntity fileMeta, CS41FileEntityDescriptor descriptor,
        InputStream in) throws IOException, NoSuchAlgorithmException, InstantiationException,
        IllegalAccessException, WGAPIException {

    Session session = getParent().getSession();

    // create digest for checksum computation
    MessageDigest digestMd5 = MessageDigest.getInstance("MD5");
    MessageDigest digestSha512 = MessageDigest.getInstance("SHA-512");

    ContentFileContent fileContent = storeFileContents(descriptor, in, session, digestMd5, digestSha512);

    // store digests on meta
    fileMeta.setChecksum(new String(Hex.encodeHex(digestMd5.digest())));
    fileMeta.setChecksumSha512(fileContent.getChecksumSha512());
    if (getParent().isSaveIsolationActive()) {
        session.update(fileMeta);/*from   ww w.  ja  va  2  s .  c  o m*/
    }
}

From source file:com.googlecode.dex2jar.util.ASMifierFileV.java

@Override
public void visitDepedence(String name, byte[] checksum) {
    file.s("((OdexFileVisitor)v).visitDepedence(%s,decodeHex(%s.toCharArray()));", Escape.v(name),
            Escape.v(new String(Hex.encodeHex(checksum))));
}

From source file:jenkins.security.seed.UserSeedProperty.java

private void renewSeedInternal() {
    String currentSeed = this.seed;
    String newSeed = currentSeed;
    byte[] bytes = new byte[SEED_NUM_BYTES];
    while (Objects.equals(newSeed, currentSeed)) {
        RANDOM.nextBytes(bytes);//from w w w  .j a  va  2s . c o  m
        newSeed = new String(Hex.encodeHex(bytes));
    }
    this.seed = newSeed;
}