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:libepg.epg.section.descriptor.Descriptor.java

@Override
public String toString() {
    Object[] parameters = { this.data.toString(), this.getDescriptor_tag_const(), this.getDescriptor_length(),
            Hex.encodeHexString(this.getDescriptor_Body()) };
    return DESC.format(parameters);
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileT.java

private XAdESTimeStampType createUnsignedXAdESProperties(byte[] data) throws IOException {

    UnsignedPropertiesType unsigned = xadesObjectFactory.createUnsignedPropertiesType();

    try {/*from   w  w w .ja  v a  2  s  .  c  o  m*/
        /* Create a timestamp over the signature value */
        LOG.info("C14n " + Hex.encodeHexString(data));

        MessageDigest digest = MessageDigest.getInstance(DigestAlgorithm.SHA1.getName());
        digest.update(data);
        byte[] digestValue = digest.digest();
        LOG.info("Digest " + Hex.encodeHexString(digestValue));

        XAdESTimeStampType timestamp = createXAdESTimeStamp(DigestAlgorithm.SHA1, digestValue);

        UnsignedSignaturePropertiesType properties = unsigned.getUnsignedSignatureProperties();
        if (properties == null) {
            properties = xadesObjectFactory.createUnsignedSignaturePropertiesType();
            unsigned.setUnsignedSignatureProperties(properties);
        }

        properties.getCounterSignatureOrSignatureTimeStampOrCompleteCertificateRefs()
                .add(xadesObjectFactory.createSignatureTimeStamp(timestamp));

        return timestamp;

    } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException("Cannot find algorithm");
    }

}

From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox.PDFAsVisualSignatureBuilder.java

public String createHashedId(String value) {
    try {//from  w ww.j a va  2 s . c o m
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.reset();
        return Hex.encodeHexString(md.digest(value.getBytes("UTF-8")));
    } catch (Throwable e) {
        logger.warn("Failed to generate ID for Image using value", e);
        return value;
    }
}

From source file:de.elomagic.carafile.server.bl.SeedBean.java

public void seedChunk(final InputStream inputStream, final String chunkId)
        throws IOException, GeneralSecurityException, JMSException {
    LOG.debug("Seeding chunk " + chunkId);
    Chunk chunk = chunkDAO.findByIdentifier(chunkId);

    if (chunk == null) {
        throw new FileNotFoundException(
                "Chunk id " + chunkId + " not found. File already registered at registry?");
    }/*from   www. j  a va2  s .c  om*/

    byte[] buf = new byte[chunk.getFileMeta().getChunkSize()];
    int bufferSize;
    try (InputStream in = inputStream) {
        bufferSize = readBlock(in, buf);
    } catch (IOException ex) {
        throw ex;
    }

    // Check SHA-1
    String sha1 = Hex.encodeHexString(DigestUtils.sha1(Arrays.copyOf(buf, bufferSize)));
    if (!chunk.getHash().equalsIgnoreCase(sha1)) {
        throw new GeneralSecurityException(
                "Chunk SHA-1 validation failed (Expected " + chunk.getHash() + ", but is " + sha1 + ")");
    }

    repositoryBean.writeChunk(chunkId, buf, bufferSize);

    LOG.debug("Chunk id " + chunkId + " seed");

    // Initiate to register at tracker
    LOG.debug("Queue up new file for registration.");
    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer messageProducer = session.createProducer(chunkQueue);

    TextMessage message = session.createTextMessage(chunkId);
    messageProducer.send(message);
    connection.close();
}

From source file:libepg.util.db.AboutDB.java

/**
 * (???)/*from   w  w  w  . j a  v a 2s. c o m*/
 *
 * @param conn ??DB??
 * @throws java.sql.SQLException
 */
public static void debug_dump_table(Connection conn) throws SQLException {
    if (LOG.isDebugEnabled()) {
        final String DUMP = "SELECT * FROM " + TABLE_NAME + " ORDER BY number ASC";
        ResultSet rs = conn.createStatement().executeQuery(DUMP);
        while (rs.next()) {
            StringBuilder sb1 = new StringBuilder();
            sb1.append(NUMBER);
            sb1.append(" = ");
            sb1.append(rs.getInt(NUMBER));
            sb1.append("####");
            sb1.append(PID);
            sb1.append(" = ");
            sb1.append(rs.getInt(PID));
            sb1.append("####");
            sb1.append(CONTINUITY_CONTROL);
            sb1.append(" = ");
            sb1.append(rs.getInt(CONTINUITY_CONTROL));
            sb1.append("####");
            sb1.append(LACKFLAG);
            sb1.append(" = ");
            sb1.append(rs.getInt(LACKFLAG));
            sb1.append("####");
            sb1.append(PACKET);
            sb1.append(" = ");
            sb1.append(Hex.encodeHexString(rs.getBytes(PACKET)));
            LOG.debug(sb1.toString());
        }
    }
}

From source file:com.rramos.bigdata.utils.GenericUDFSha2.java

@Override
public Object evaluate(DeferredObject[] arguments) throws HiveException {
    if (digest == null) {
        return null;
    }//w w w  . j av  a2  s . c  o m

    digest.reset();
    if (isStr) {
        Text n = GenericUDFParamUtils.getTextValue(arguments, 0, converters);
        if (n == null) {
            return null;
        }
        digest.update(n.getBytes(), 0, n.getLength());
    } else {
        BytesWritable bWr = GenericUDFParamUtils.getBinaryValue(arguments, 0, converters);
        if (bWr == null) {
            return null;
        }
        digest.update(bWr.getBytes(), 0, bWr.getLength());
    }
    byte[] resBin = digest.digest();
    String resStr = Hex.encodeHexString(resBin);

    output.set(resStr);
    return output;
}

From source file:edu.nps.moves.mmowgli.CACManager.java

private static void parseCert(String cert, CACData data) {
    cert = cert.replace(' ', '\r');
    cert = cert.replace("BEGIN\rCERTIFICATE", "BEGIN CERTIFICATE");
    cert = cert.replace("END\rCERTIFICATE", "END CERTIFICATE");
    PEMParser pr = new PEMParser(new StringReader(cert));
    try {//from w ww.j  a  va2  s .  c o  m
        Object o = pr.readObject();
        pr.close();
        if (o instanceof X509CertificateHolder) {
            X509CertificateHolder x509 = (X509CertificateHolder) o;
            X500Name x500name = x509.getSubject();
            RDN cnRdns[] = x500name.getRDNs(BCStyle.CN);

            String cn = IETFUtils.valueToString(cnRdns[0].getFirst().getValue());
            parseCN(cn, data);

            GeneralNames gns = GeneralNames.fromExtensions(x509.getExtensions(),
                    Extension.subjectAlternativeName);
            if (gns != null) {
                GeneralName[] subjectAltNames = gns.getNames();
                for (GeneralName gn : subjectAltNames) {
                    if (gn.getTagNo() == GeneralName.rfc822Name) { // check for email
                        String s = DERIA5String.getInstance(gn.getName()).getString();
                        if (s.contains("@")) {
                            data.userEmail = s;
                            break;
                        }
                    }
                }
            }

            // Create the unique card identifier (issuer+serial) which when hashed goes into the database for quick login
            String uniqueCertId = x509.getIssuer().toString() + " " + x509.getSerialNumber().toString();

            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(uniqueCertId.getBytes("UTF-8")); // or UTF-16
            byte[] digest = md.digest();
            data.cacId = Hex.encodeHexString(digest);

            /* Alternatively, this will do a salted hash, but the output is not the same for the same input; better security
             * but the login performance would be bad since the user list has to be polled instead of indexed
             try {
               data.cacId = PasswordHash.createHash(uniqueCertId);
             }
             catch(Exception ex) {
               MSysOut.println(MmowgliConstants.SYSTEM_LOGS,"Program error, could not create CAC hash; auto-login disabled");
               data.cacId = null;
             }
             System.out.println("data cacId: "+data.cacId); */

        }
    } catch (IOException | NoSuchAlgorithmException ex) {
        MSysOut.println(MmowgliConstants.SYSTEM_LOGS,
                ex.getClass().getSimpleName() + ": Program error, could not parse CAC");
        data.cacId = null;
        data.isCACPresent = false;
    }

    // Some informational stuff
    /* this gives same info as the x509 methods below  
         RDN rdns[] = x500name.getRDNs();
         for(RDN rdn : rdns) {
            AttributeTypeAndValue[] tandV = rdn.getTypesAndValues();
            for(AttributeTypeAndValue tv : tandV) {
     System.out.println(tv.getType());
     System.out.println(IETFUtils.valueToString(tv.getType()));
     System.out.println(tv.getValue());
     System.out.println(IETFUtils.valueToString(tv.getValue()));
            }
         }
         */
    /*
    System.out.println("X509 version: "+x509.getVersionNumber());
    System.out.println("X509 Serial num: "+x509.getSerialNumber());
    System.out.println("X509 Sig algo: "+x509.getSignatureAlgorithm().getAlgorithm().toASN1Primitive());
    System.out.println("X509 Issuer: "+x509.getIssuer());
    System.out.println("X509 Not before: "+x509.getNotBefore());
    System.out.println("X509 Not after: "+x509.getNotAfter());
    System.out.println("X509 Subject: "+x509.getSubject());
    System.out.println("X509 Subject Public Key Info: "+x509.getSubjectPublicKeyInfo().getAlgorithm().getAlgorithm());
    */
    /* 
     System.out.println("CriticalExtensionOIDs: ");
     Set<?> set = x509.getCriticalExtensionOIDs();
     Iterator<?> itr = set.iterator();
     while(itr.hasNext()) {
       ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)itr.next();
       System.out.println(oid.toString()+" : "+x509.getExtension(oid).getParsedValue());
     }
               
     System.out.println("NonCriticalExtensionOIDs: ");
     set = x509.getNonCriticalExtensionOIDs();
     itr = set.iterator();
     while(itr.hasNext()) {
       ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)itr.next();
       System.out.println(oid.toString()+" : "+x509.getExtension(oid).getParsedValue());
     }
             
     System.out.println("Other api: getExtensionOIDs");
     List<?> lis = x509.getExtensionOIDs();
     itr = lis.iterator();
     while(itr.hasNext()) {
       ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)itr.next();
       System.out.println(oid.toString()+" : "+x509.getExtension(oid).getParsedValue());
     }
            
     System.out.println("From the extensions \"block\"");
     Extensions exts = x509.getExtensions();
     ASN1ObjectIdentifier[] ids = exts.getExtensionOIDs();
     for(ASN1ObjectIdentifier oid : ids) {
       org.bouncycastle.asn1.x509.Extension ext = exts.getExtension(oid);
       System.out.println(oid.toString()+": "+IETFUtils.valueToString(ext.getParsedValue()));
     }
    //     */
}

From source file:com.thoughtworks.go.server.service.plugins.AnalyticsPluginAssetsService.java

private String sha2Digest(byte[]... bytes) {
    try {/*from w  ww .  j  av a 2 s .  com*/
        MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM);

        for (byte[] data : bytes) {
            md.update(data);
        }

        return Hex.encodeHexString(md.digest());
    } catch (Exception e) {
        LOGGER.error("Error generating {} hash", HASH_ALGORITHM, e);
        ExceptionUtils.bomb(e);
    }

    return null;
}

From source file:com.joyent.manta.client.crypto.EncryptingEntity.java

@Override
public void writeTo(final OutputStream httpOut) throws IOException {
    /*/*from w  w w.  j a va 2 s. co m*/
     * Construct a fresh EncryptionContext each time we attempt to write out the entity.
     * Calling encryptionContext.initializeCipher(getCipher().getIV()) from here would be ideal
     * but is not compatible with AES-GCM
     */
    this.encryptionContext = new EncryptionContext(encryptionContext.getSecretKey(),
            encryptionContext.getCipherDetails(), encryptionContext.getCipher().getIV());

    OutputStream out = EncryptingEntityHelper.makeCipherOutputForStream(httpOut, encryptionContext);

    copyContentToOutputStream(out);
    /* We don't close quietly because we want the operation to fail if
     * there is an error closing out the CipherOutputStream. */
    out.close();

    if (out instanceof HmacOutputStream) {
        final HMac hmac = ((HmacOutputStream) out).getHmac();
        final int hmacSize = hmac.getMacSize();
        final byte[] hmacBytes = new byte[hmacSize];
        hmac.doFinal(hmacBytes, 0);

        Validate.isTrue(hmacBytes.length == hmacSize,
                "HMAC actual bytes doesn't equal the number of bytes expected");

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("HMAC: {}", Hex.encodeHexString(hmacBytes));
        }

        httpOut.write(hmacBytes);
    }
}

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

private void includeToDssDictionary(ModelPdfDict dssDictionary, SignatureValidationCallBack callback)
        throws IOException {

    ModelPdfDict vriDictionary = ensureNotNull(dssDictionary, "VRI");

    ModelPdfDict sigVriDictionary = new ModelPdfDict();

    PAdESSignature signature = callback.getSignature();
    final byte[] digest = DSSUtils.digest(DigestAlgorithm.SHA1,
            signature.getCAdESSignature().getCmsSignedData().getEncoded());
    String hexHash = Hex.encodeHexString(digest).toUpperCase();

    if (CollectionUtils.isNotEmpty(callback.getCertificates())) {
        ModelPdfArray vriCertArray = new ModelPdfArray();
        for (CertificateToken token : callback.getCertificates()) {
            ModelPdfStream stream = new ModelPdfStream(token.getEncoded());
            vriCertArray.add(stream);// w  w w.java2 s  . c  o  m
            dssCertArray.add(stream);
        }
        sigVriDictionary.add("Cert", vriCertArray);
    }

    if (CollectionUtils.isNotEmpty(callback.getCrls())) {
        ModelPdfArray vriCrlArray = new ModelPdfArray();
        for (CRLToken token : callback.getCrls()) {
            ModelPdfStream stream = new ModelPdfStream(token.getEncoded());
            vriCrlArray.add(stream);
            dssCrlArray.add(stream);
        }
        sigVriDictionary.add("CRL", vriCrlArray);
    }

    if (CollectionUtils.isNotEmpty(callback.getOcsps())) {
        ModelPdfArray vriOcspArray = new ModelPdfArray();
        for (OCSPToken token : callback.getOcsps()) {
            ModelPdfStream stream = new ModelPdfStream(token.getEncoded());
            vriOcspArray.add(stream);
            dssOcspArray.add(stream);
        }
        sigVriDictionary.add("OCSP", vriOcspArray);
    }

    vriDictionary.add(hexHash, sigVriDictionary);

}