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.redhat.rhn.common.client.ClientCertificate.java

/**
 * Returns signature of certificate./*from www .jav  a 2  s .  c o m*/
 * @param secret Server Secret for this certificate
 * @return Signature of this certificate
 * @throws InvalidCertificateException thrown if there is a problem
 * validating the certificate.
 */
public String genSignature(String secret) throws InvalidCertificateException {

    String signature = null;

    String[] strs = getValuesByName(FIELDS);

    for (int i = 0; i < strs.length; i++) {
        if (checksumFields.get(strs[i]) == null) {
            throw new InvalidCertificateException(
                    "Invalid field " + strs[i] + " provided while validating certificate");
        }
    }

    try {
        MessageDigest md = null;
        if (secret.length() == 32) {
            md = MessageDigest.getInstance("MD5");
        } else if (secret.length() == 64) {
            md = MessageDigest.getInstance("SHA-256");
        }

        // I'm not one to loop through things more than once
        // but this seems to be the algorithm found in Server.pm

        // add secret
        byte[] secretBytes = secret.getBytes("UTF-8");
        md.update(secretBytes);

        // add the values for the fields
        for (int i = 0; i < strs.length; i++) {
            String value = getValueByName(strs[i]);
            byte[] valueBytes = value.getBytes("UTF-8");
            md.update(valueBytes);
        }

        // add field names
        for (int i = 0; i < strs.length; i++) {
            byte[] fieldBytes = strs[i].getBytes("UTF-8");
            md.update(fieldBytes);
        }

        // generate the digest
        byte[] digest = md.digest();

        // hexify this puppy
        signature = new String(Hex.encodeHex(digest));
    } catch (UnsupportedEncodingException e) {
        throw new InvalidCertificateException("Problem getting bytes for signature", e);
    } catch (NoSuchAlgorithmException e) {
        throw new InvalidCertificateException("Problem getting MD5 message digest.", e);
    }

    return signature;
}

From source file:net.padlocksoftware.padlock.DefaultMacAddressProvider.java

private boolean isVirtualAddress(byte[] address) {

    // Loop through the virtual mac database to determine if this is a physical
    // interface address.
    for (Entry<String, byte[]> entry : virtualAddresses.entrySet()) {
        String name = entry.getKey();
        byte[] data = entry.getValue();

        int matchCount = 0;

        for (int x = 0; x < Math.min(data.length, address.length); x++) {
            if (data[x] == address[x]) {
                matchCount++;//w w  w  .  j a  va  2 s  .  com
            }
        }

        if (matchCount == data.length) {
            logger.log(Level.FINE, "Address {0} matches {1}, ignoring",
                    new Object[] { new String(Hex.encodeHex(address)), name });
            return true;
        }
    }

    return false;
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.datasets.DatasetLoader.java

private void fetch(File aTarget, DataPackage... aPackages) throws IOException {
    // First validate if local copies are still up-to-date
    boolean reload = false;
    packageValidationLoop: for (DataPackage pack : aPackages) {
        File cachedFile = new File(aTarget, pack.getTarget());
        if (!cachedFile.exists()) {
            continue;
        }//  w  w  w  . j  a v  a2  s .co m

        if (pack.getSha1() != null) {
            String actual = getDigest(cachedFile, "SHA1");
            if (!pack.getSha1().equals(actual)) {
                LOG.info("Local SHA1 hash mismatch on [" + cachedFile + "] - expected [" + pack.getSha1()
                        + "] - actual [" + actual + "]");
                reload = true;
                break packageValidationLoop;
            } else {
                LOG.info("Local SHA1 hash verified on [" + cachedFile + "] - [" + actual + "]");
            }
        }

        if (pack.getMd5() != null) {
            String actual = getDigest(cachedFile, "MD5");
            if (!pack.getMd5().equals(actual)) {
                LOG.info("Local MD5 hash mismatch on [" + cachedFile + "] - expected [" + pack.getMd5()
                        + "] - actual [" + actual + "]");
                reload = true;
                break packageValidationLoop;
            } else {
                LOG.info("Local MD5 hash verified on [" + cachedFile + "] - [" + actual + "]");
            }
        }

    }

    // If any of the packages are outdated, clear the cache and download again
    if (reload) {
        LOG.info("Clearing local cache for [" + aTarget + "]");
        FileUtils.deleteQuietly(aTarget);
    }

    for (DataPackage pack : aPackages) {
        File cachedFile = new File(aTarget, pack.getTarget());

        if (cachedFile.exists()) {
            continue;
        }

        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new IOException(e);
        }

        MessageDigest sha1;
        try {
            sha1 = MessageDigest.getInstance("SHA1");
        } catch (NoSuchAlgorithmException e) {
            throw new IOException(e);
        }

        cachedFile.getParentFile().mkdirs();
        URL source = new URL(pack.getUrl());

        LOG.info("Fetching [" + cachedFile + "]");

        URLConnection connection = source.openConnection();
        connection.setRequestProperty("User-Agent", "Java");

        try (InputStream is = connection.getInputStream()) {
            DigestInputStream md5Filter = new DigestInputStream(is, md5);
            DigestInputStream sha1Filter = new DigestInputStream(md5Filter, sha1);
            FileUtils.copyInputStreamToFile(sha1Filter, cachedFile);

            if (pack.getMd5() != null) {
                String md5Hex = new String(Hex.encodeHex(md5Filter.getMessageDigest().digest()));
                if (!pack.getMd5().equals(md5Hex)) {
                    String message = "MD5 mismatch. Expected [" + pack.getMd5() + "] but got [" + md5Hex + "].";
                    LOG.error(message);
                    throw new IOException(message);
                }
            }

            if (pack.getSha1() != null) {
                String sha1Hex = new String(Hex.encodeHex(sha1Filter.getMessageDigest().digest()));
                if (!pack.getSha1().equals(sha1Hex)) {
                    String message = "SHA1 mismatch. Expected [" + pack.getSha1() + "] but got [" + sha1Hex
                            + "].";
                    LOG.error(message);
                    throw new IOException(message);
                }
            }
        }
    }

    // Perform a post-fetch action such as unpacking
    for (DataPackage pack : aPackages) {
        File cachedFile = new File(aTarget, pack.getTarget());
        File postActionCompleteMarker = new File(cachedFile.getPath() + ".postComplete");
        if (pack.getPostAction() != null && !postActionCompleteMarker.exists()) {
            try {
                pack.getPostAction().run(pack);
                FileUtils.touch(postActionCompleteMarker);
            } catch (IOException e) {
                throw e;
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        }
    }
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.WsdlMimeMessageResponse.java

private void expandMtomAttachments(WsdlRequest wsdlRequest) {
    try {//from   w  w  w. j a v a2 s  .c o m
        // XmlObject xmlObject = XmlObject.Factory.parse( getContentAsString()
        // );
        XmlObject xmlObject = XmlUtils.createXmlObject(getContentAsString());
        XmlObject[] includes = xmlObject
                .selectPath("declare namespace xop='http://www.w3.org/2004/08/xop/include'; //xop:Include");

        for (XmlObject include : includes) {
            Element elm = (Element) include.getDomNode();
            String href = elm.getAttribute("href");
            Attachment attachment = getMmSupport().getAttachmentWithContentId("<" + href.substring(4) + ">");
            if (attachment != null) {
                ByteArrayOutputStream data = Tools.readAll(attachment.getInputStream(), 0);
                byte[] byteArray = data.toByteArray();

                XmlCursor cursor = include.newCursor();
                cursor.toParent();
                XmlObject parentXmlObject = cursor.getObject();
                cursor.dispose();

                SchemaType schemaType = parentXmlObject.schemaType();
                Node parentNode = elm.getParentNode();

                if (schemaType.isNoType()) {
                    SchemaTypeSystem typeSystem = wsdlRequest.getOperation().getInterface().getWsdlContext()
                            .getSchemaTypeSystem();
                    SchemaGlobalElement schemaElement = typeSystem
                            .findElement(new QName(parentNode.getNamespaceURI(), parentNode.getLocalName()));
                    if (schemaElement != null) {
                        schemaType = schemaElement.getType();
                    }
                }

                String txt = null;

                if (SchemaUtils.isInstanceOf(schemaType, XmlHexBinary.type)) {
                    txt = new String(Hex.encodeHex(byteArray));
                } else {
                    txt = new String(Base64.encodeBase64(byteArray));
                }

                parentNode.replaceChild(elm.getOwnerDocument().createTextNode(txt), elm);
            }
        }

        getMmSupport().setResponseContent(xmlObject.toString());
    } catch (Exception e) {
        SoapUI.logError(e);
    }
}

From source file:com.hivewallet.androidclient.wallet.AddressBookProvider.java

/**
 * Resizes the provided bitmap and stores it in private storage, returning a URI to it.
 * It will be deleted on the next clean up cycle, unless marked as permanent in the mean time.  */
public static Uri storeBitmap(@Nonnull Context context, @Nonnull Bitmap bitmap) {
    if (bitmap == null)
        return null;

    Bitmap bitmapScaled = ensureReasonableSize(bitmap);
    if (bitmapScaled == null)
        return null;

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    bitmapScaled.compress(CompressFormat.PNG, 100, outStream);
    byte[] photoScaled = outStream.toByteArray();

    Uri photoUri = null;//from  ww  w  . j a  v  a 2 s .  c o m
    try {
        /* for some reason calling DigestUtils.sha1Hex() does not work on Android */
        String hash = new String(Hex.encodeHex(DigestUtils.sha1(photoScaled)));

        /* create photo asset and database entry */
        File dir = context.getDir(Constants.PHOTO_ASSETS_FOLDER, Context.MODE_PRIVATE);
        File photoAsset = new File(dir, hash + ".png");
        photoUri = Uri.fromFile(photoAsset);
        boolean alreadyPresent = AddressBookProvider.insertOrUpdatePhotoUri(context, photoUri);
        if (!alreadyPresent) {
            FileUtils.writeByteArrayToFile(photoAsset, photoScaled);
            log.info("Saved photo asset with uri {}", photoUri);
        }

        /* use opportunity to clean up photo assets */
        List<Uri> stalePhotoUris = AddressBookProvider.deleteStalePhotoAssets(context);
        for (Uri stalePhotoUri : stalePhotoUris) {
            File stalePhotoAsset = new File(stalePhotoUri.getPath());
            FileUtils.deleteQuietly(stalePhotoAsset);
            log.info("Deleting stale photo asset with uri {}", stalePhotoUri);
        }
    } catch (IOException ignored) {
    }

    return photoUri;
}

From source file:fi.okm.mpass.shibboleth.authn.impl.BaseInitializeWilmaContext.java

/**
 * Calculates the checksum for the given string, using the given Mac instance and secret key.
 * @param mac The Mac instance.//from ww w.j  a va 2s  .c om
 * @param string The seed.
 * @param key The secret key used for calculating the checksum.
 * @return The checksum value.
 */
public static String calculateChecksum(final Mac mac, final String string, final SecretKey key) {
    try {
        mac.init(key);
        final byte[] bytes = mac.doFinal(string.getBytes("UTF-8"));
        return new String(Hex.encodeHex(bytes));
    } catch (InvalidKeyException | UnsupportedEncodingException e) {
        LoggerFactory.getLogger(InitializeStaticWilmaContext.class)
                .error("Could not sign the input data {} with the key", string);
    }
    return null;
}

From source file:at.diamonddogs.util.Utils.java

/**
 * Computes a MD5 hash from an input string
 *
 * @param input the input string/*from  w ww  .j  a  va  2  s.  c  o m*/
 * @return the MD5 hash or <code>null</code> if an error occured
 */
public static String getMD5Hash(String input) {
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("MD5");
        return new String(Hex.encodeHex(md.digest(input.getBytes())));
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, e.getMessage(), e);
    }
    return null;
}

From source file:com.zimbra.cs.octosync.PatchInputStream.java

private InputStream nextInputStream() throws IOException, ServiceException {
    if (!patchReader.hasMoreRecordInfos()) {
        return null;
    }/*  w  w  w .j av  a2 s  .c  o  m*/

    PatchReader.RecordInfo ri = patchReader.getNextRecordInfo();

    InputStream nextStream = null;

    if (ri.type == PatchReader.RecordType.DATA) {

        log.debug("Patch data, length: " + ri.length);
        nextStream = patchReader.popData();

    } else if (ri.type == PatchReader.RecordType.REF) {

        PatchRef patchRef = patchReader.popRef();
        log.debug("Patch reference " + patchRef);

        if (patchRef.length > MAX_REF_LENGTH) {
            throw new InvalidPatchReferenceException(
                    "referenced data too large: " + patchRef.length + " > " + MAX_REF_LENGTH);
        }

        if (manifest != null) {
            int[] actualRef = blobAccess.getActualReference(patchRef.fileId, patchRef.fileVersion);
            manifest.addReference(actualRef[0], actualRef[1], patchRef.length);
        }

        try {
            InputStream blobIs = blobAccess.getBlobInputStream(patchRef.fileId, patchRef.fileVersion);

            blobIs.skip(patchRef.offset);

            byte[] chunkBuf = new byte[patchRef.length];

            DataInputStream dis = new DataInputStream(blobIs);
            dis.readFully(chunkBuf);
            dis.close();

            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(chunkBuf);
            byte[] calcHash = md.digest();

            if (!Arrays.equals(patchRef.hashKey, calcHash)) {
                throw new InvalidPatchReferenceException("refrenced data hash mismatch, actual hash: "
                        + new String(Hex.encodeHex(calcHash)) + "; " + patchRef);
            }

            nextStream = new ByteArrayInputStream(chunkBuf);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            assert false : "SHA-256 must be supported";
        }
    } else {
        assert false : "Invalid record type: " + ri.type;
    }

    assert nextStream != null : "Stream returned here must be non-null";
    return nextStream;
}

From source file:be.fedict.trust.PublicKeyTrustLinker.java

public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData) {
    if (false == childCertificate.getIssuerX500Principal().equals(certificate.getSubjectX500Principal())) {
        LOG.debug("child certificate issuer not the same as the issuer certificate subject");
        LOG.debug("child certificate: " + childCertificate.getSubjectX500Principal());
        LOG.debug("certificate: " + certificate.getSubjectX500Principal());
        LOG.debug("child certificate issuer: " + childCertificate.getIssuerX500Principal());
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                "child certificate issuer not the same as the issuer certificate subject");
    }//  w w w  .  j av  a2s  .  c  om
    try {
        childCertificate.verify(certificate.getPublicKey());
    } catch (Exception e) {
        LOG.debug("verification error: " + e.getMessage(), e);
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_SIGNATURE,
                "verification error: " + e.getMessage());
    }
    if (true == childCertificate.getNotAfter().after(certificate.getNotAfter())) {
        LOG.warn("child certificate validity end is after certificate validity end");
        LOG.warn("child certificate validity end: " + childCertificate.getNotAfter());
        LOG.warn("certificate validity end: " + certificate.getNotAfter());
    }
    if (true == childCertificate.getNotBefore().before(certificate.getNotBefore())) {
        LOG.warn("child certificate validity begin before certificate validity begin");
        LOG.warn("child certificate validity begin: " + childCertificate.getNotBefore());
        LOG.warn("certificate validity begin: " + certificate.getNotBefore());
    }
    if (true == validationDate.before(childCertificate.getNotBefore())) {
        LOG.debug("certificate is not yet valid");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL,
                "certificate is not yet valid");
    }
    if (true == validationDate.after(childCertificate.getNotAfter())) {
        LOG.debug("certificate already expired");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL,
                "certificate already expired");
    }
    if (-1 == certificate.getBasicConstraints()) {
        LOG.debug("certificate not a CA");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "certificate not a CA");
    }
    if (0 == certificate.getBasicConstraints() && -1 != childCertificate.getBasicConstraints()) {
        LOG.debug("child should not be a CA");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "child should not be a CA");
    }

    /*
     * SKID/AKID sanity check
     */
    boolean isCa = isCa(certificate);
    boolean isChildCa = isCa(childCertificate);

    byte[] subjectKeyIdentifierData = certificate
            .getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId());
    byte[] authorityKeyIdentifierData = childCertificate
            .getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());

    if (isCa && null == subjectKeyIdentifierData) {
        LOG.debug("certificate is CA and MUST contain a Subject Key Identifier");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                "certificate is CA and  MUST contain a Subject Key Identifier");
    }

    if (isChildCa && null == authorityKeyIdentifierData) {
        LOG.debug("child certificate is CA and MUST contain an Authority Key Identifier");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                "child certificate is CA and MUST contain an Authority Key Identifier");
    }

    if (null != subjectKeyIdentifierData && null != authorityKeyIdentifierData) {

        AuthorityKeyIdentifierStructure authorityKeyIdentifierStructure;
        try {
            authorityKeyIdentifierStructure = new AuthorityKeyIdentifierStructure(authorityKeyIdentifierData);
        } catch (IOException e) {
            LOG.debug("Error parsing authority key identifier structure");
            return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                    "Error parsing authority key identifier structure");
        }
        String akidId = new String(Hex.encodeHex(authorityKeyIdentifierStructure.getKeyIdentifier()));

        SubjectKeyIdentifierStructure subjectKeyIdentifierStructure;
        try {
            subjectKeyIdentifierStructure = new SubjectKeyIdentifierStructure(subjectKeyIdentifierData);
        } catch (IOException e) {
            LOG.debug("Error parsing subject key identifier structure");
            return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                    "Error parsing subject key identifier structure");
        }
        String skidId = new String(Hex.encodeHex(subjectKeyIdentifierStructure.getKeyIdentifier()));

        if (!skidId.equals(akidId)) {
            LOG.debug(
                    "certificate's subject key identifier does not match child certificate's authority key identifier");
            return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                    "certificate's subject key identifier does not match child certificate's authority key identifier");
        }
    }

    /*
     * We don't check pathLenConstraint since this one is only there to
     * protect the PKI business.
     */
    return null;
}

From source file:jp.co.opentone.bsol.linkbinder.util.ValueFormatter.java

/**
 * ??SHA256???//from   www  .  j  av  a 2s.c om
 * @param value ??
 * @param key 
 * @return ??
 */
public static String formatValueToHash(String value, String key) {
    byte[] result;
    try {
        SecretKeySpec sk = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(sk);
        result = mac.doFinal(value.getBytes("UTF-8"));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return new String(Hex.encodeHex(result));

}