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.filelocker.encryption.AES_Encryption.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 vEcipher 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   ww  w .ja va2  s.  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
    vSalt = new byte[SALT_LEN];
    SecureRandom rnd = new SecureRandom();
    rnd.nextBytes(vSalt);
    Db("generated salt :" + Hex.encodeHexString(vSalt));

    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(vPassword.toCharArray(), vSalt, 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
     */
    vEcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    vEcipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = vEcipher.getParameters();

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

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

From source file:com.twitter.distributedlog.DLSN.java

/**
 * Deserialize the DLSN from bytes array.
 *
 * @param data//from   w  w w  .j a  va  2  s.c  om
 *          serialized bytes
 * @return dlsn
 */
public static DLSN deserializeBytes(byte[] data) {
    ByteBuffer bb = ByteBuffer.wrap(data);
    byte version = bb.get();
    if (VERSION0 == version) {
        if (VERSION0_LEN != data.length) {
            throw new IllegalArgumentException("Invalid version zero DLSN " + Hex.encodeHexString(data));
        }
    } else if (VERSION1 == version) {
        if (VERSION1_LEN != data.length) {
            throw new IllegalArgumentException("Invalid version one DLSN " + Hex.encodeHexString(data));
        }
    } else {
        throw new IllegalArgumentException(
                "Invalid DLSN : version = " + version + ", " + Hex.encodeHexString(data));
    }
    return new DLSN(bb.getLong(), bb.getLong(), bb.getLong());
}

From source file:at.gv.egiz.pdfas.lib.pki.impl.DefaultCertificateVerificationDataProvider.java

@Override
public CertificateVerificationData getCertificateVerificationData(
        java.security.cert.X509Certificate eeCertificate, ISettings settings)
        throws CertificateException, IOException {

    X509Certificate iaikEeCertificate = toIAIKX509Certificate(Objects.requireNonNull(eeCertificate));

    // @formatter:off
    final Set<java.security.cert.X509Certificate> certs = new LinkedHashSet<>(); // not thread-safe
    final List<byte[]> ocsps = new ArrayList<>(); // not thread-safe
    final Set<java.security.cert.X509CRL> crls = new LinkedHashSet<>(); // not thread-safe
    // @formatter:on

    StopWatch sw = new StopWatch();
    sw.start();//from   w w  w  .ja v a  2s.c  om

    if (log.isDebugEnabled()) {
        log.debug("Retrieving certificate validation info info for {}", iaikEeCertificate.getSubjectDN());
    } else if (log.isInfoEnabled()) {
        log.info("Retrieving certificate validation data for certificate (SHA-1 fingerprint): {}",
                Hex.encodeHexString(iaikEeCertificate.getFingerprintSHA()));
    }

    // retrieve certificate chain for eeCertificate
    X509Certificate[] caChainCertificates = retrieveChain(iaikEeCertificate, Objects.requireNonNull(settings));
    // build up full (sorted) chain including eeCertificate
    X509Certificate[] fullChainCertificates = Util.createCertificateChain(iaikEeCertificate,
            caChainCertificates);
    // add chain to certs list
    certs.addAll(Arrays.asList(fullChainCertificates));

    // determine revocation info, preferring OCSP
    // assume last certificate in chain is trust anchor
    OCSPClient ocspClient = OCSPClient.builder().setConnectTimeOutMillis(DEFAULT_CONNECTION_TIMEOUT_MS)
            .setSocketTimeOutMillis(DEFAULT_READ_TIMEOUT_MS).build();
    for (int i = 0; i < fullChainCertificates.length - 1; i++) {
        final X509Certificate subjectCertificate = fullChainCertificates[i];
        final X509Certificate issuerCertificate = fullChainCertificates[i + 1];
        OCSPResponse ocspResponse = null;
        if (OCSPClient.Util.hasOcspResponder(subjectCertificate)) {
            try {
                ocspResponse = ocspClient.getOcspResponse(issuerCertificate, subjectCertificate);
            } catch (Exception e) {
                log.info("Unable to retrieve OCSP response: {}", String.valueOf(e));
            }
        }

        if (ocspResponse != null) {

            ocsps.add(ocspResponse.getEncoded());

            // add ocsp signer certificate to certs
            // The currently used OCSP client support BasicOCSPResponse only, otherwise an exception would have been
            // thrown earlier. Therefore we can safely cast to BasicOCSPResponse here.
            X509Certificate ocspSignerCertificate = ((BasicOCSPResponse) ocspResponse.getResponse())
                    .getSignerCertificate();
            certs.add(ocspSignerCertificate);

        } else {

            // fall back to CRL

            CRLDistributionPoints cRLDistributionPoints;
            try {
                cRLDistributionPoints = (CRLDistributionPoints) subjectCertificate
                        .getExtension(CRLDistributionPoints.oid);
            } catch (X509ExtensionInitException e) {
                throw new IllegalStateException("Unable to initialize extension CRLDistributionPoints.", e);
            }
            X509CRL x509Crl = null;
            if (cRLDistributionPoints != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Retrieving CRL revocation info for: {}", subjectCertificate.getSubjectDN());
                } else if (log.isInfoEnabled()) {
                    log.info("Retrieving CRL revocation info for certificate (SHA-1 fingerprint): {}",
                            Hex.encodeHexString(subjectCertificate.getFingerprintSHA()));
                }

                Exception lastException = null;
                @SuppressWarnings("unchecked")
                Enumeration<DistributionPoint> e = cRLDistributionPoints.getDistributionPoints();
                while (e.hasMoreElements() && x509Crl == null) {
                    DistributionPoint distributionPoint = e.nextElement();

                    // inspect distribution point
                    if (distributionPoint.containsUriDpName()) {

                        String[] distributionPointNameURIs = distributionPoint.getDistributionPointNameURIs();
                        for (String distributionPointNameURI : distributionPointNameURIs) {
                            URL url;
                            try {
                                log.debug("Trying to download crl from distribution point: {}",
                                        distributionPointNameURI);
                                if (distributionPointNameURI.toLowerCase().startsWith("ldap://")) {
                                    url = new URL(null, distributionPointNameURI,
                                            new iaik.x509.net.ldap.Handler());
                                } else {
                                    url = new URL(distributionPointNameURI);
                                }
                                URLConnection urlConnection = url.openConnection();
                                urlConnection.setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT_MS);
                                urlConnection.setReadTimeout(DEFAULT_READ_TIMEOUT_MS);
                                try (InputStream in = urlConnection.getInputStream()) {
                                    x509Crl = new X509CRL(in);
                                    // we got crl, exit loop
                                    break;
                                } catch (CRLException e1) {
                                    lastException = e1;
                                    log.debug("Unable to parse CRL read from distribution point: {} ({})",
                                            distributionPointNameURI, e1.getMessage());
                                }
                            } catch (MalformedURLException e1) {
                                log.debug("Unsupported CRL distribution point uri: {} ({})",
                                        distributionPointNameURI, e1.getMessage());
                                lastException = e1;
                            } catch (IOException e1) {
                                log.debug("Error reading from CRL distribution point uri: {} ({})",
                                        distributionPointNameURI, e1.getMessage());
                                lastException = e1;
                            } catch (Exception e1) {
                                log.debug("Unknown error reading from CRL distribution point uri: {} ({})",
                                        distributionPointNameURI, e1.getMessage());
                                lastException = e1;
                            }
                        }

                    }

                }
                if (x509Crl != null) {
                    crls.add(x509Crl);
                } else if (lastException != null) {
                    log.info("Unable to load CRL: {}", String.valueOf(lastException));
                }
            }

        }

    }
    sw.stop();
    log.debug("Querying certificate validation info took: {}ms", sw.getTime());

    return new CertificateVerificationData() {

        @Override
        public List<byte[]> getEncodedOCSPResponses() {
            return ocsps;
        }

        @Override
        public Set<java.security.cert.X509Certificate> getChainCerts() {
            return certs;
        }

        @Override
        public Set<java.security.cert.X509CRL> getCRLs() {
            return crls;
        }
    };
}

From source file:com.google.u2f.server.impl.U2FServerReferenceImpl.java

@Override
public SecurityKeyData processRegistrationResponse(RegistrationResponse registrationResponse,
        long currentTimeInMillis) throws U2FException {
    Log.info(">> processRegistrationResponse");

    String sessionId = registrationResponse.getSessionId();
    String clientDataBase64 = registrationResponse.getClientData();
    String rawRegistrationDataBase64 = registrationResponse.getRegistrationData();

    Log.info(">> rawRegistrationDataBase64: " + rawRegistrationDataBase64);
    EnrollSessionData sessionData = dataStore.getEnrollSessionData(sessionId);

    if (sessionData == null) {
        throw new U2FException("Unknown session_id");
    }/*from ww  w  .java  2  s .  c  om*/

    String appId = sessionData.getAppId();
    String clientData = new String(Base64.decodeBase64(clientDataBase64));
    byte[] rawRegistrationData = Base64.decodeBase64(rawRegistrationDataBase64);
    Log.info("-- Input --");
    Log.info("  sessionId: " + sessionId);
    Log.info("  challenge: " + Hex.encodeHexString(sessionData.getChallenge()));
    Log.info("  accountName: " + sessionData.getAccountName());
    Log.info("  clientData: " + clientData);
    Log.info("  rawRegistrationData: " + Hex.encodeHexString(rawRegistrationData));

    RegisterResponse registerResponse = RawMessageCodec.decodeRegisterResponse(rawRegistrationData);

    byte[] userPublicKey = registerResponse.getUserPublicKey();
    byte[] keyHandle = registerResponse.getKeyHandle();
    X509Certificate attestationCertificate = registerResponse.getAttestationCertificate();
    byte[] signature = registerResponse.getSignature();
    List<Transports> transports = null;
    try {
        transports = U2fAttestation.Parse(attestationCertificate).getTransports();
    } catch (CertificateParsingException e) {
        Log.warning("Could not parse transports extension " + e.getMessage());
    }

    Log.info("-- Parsed rawRegistrationResponse --");
    Log.info("  userPublicKey: " + Hex.encodeHexString(userPublicKey));
    Log.info("  keyHandle: " + Hex.encodeHexString(keyHandle));
    Log.info("  attestationCertificate: " + attestationCertificate.toString());
    Log.info("  transports: " + transports);
    try {
        Log.info("  attestationCertificate bytes: " + Hex.encodeHexString(attestationCertificate.getEncoded()));
    } catch (CertificateEncodingException e) {
        throw new U2FException("Cannot encode certificate", e);
    }
    Log.info("  signature: " + Hex.encodeHexString(signature));

    byte[] appIdSha256 = crypto.computeSha256(appId.getBytes());
    byte[] clientDataSha256 = crypto.computeSha256(clientData.getBytes());
    byte[] signedBytes = RawMessageCodec.encodeRegistrationSignedBytes(appIdSha256, clientDataSha256, keyHandle,
            userPublicKey);

    Set<X509Certificate> trustedCertificates = dataStore.getTrustedCertificates();
    if (!trustedCertificates.contains(attestationCertificate)) {
        Log.warning("attestion cert is not trusted");
    }

    verifyBrowserData(new JsonParser().parse(clientData), "navigator.id.finishEnrollment", sessionData);

    Log.info("Verifying signature of bytes " + Hex.encodeHexString(signedBytes));
    if (!crypto.verifySignature(attestationCertificate, signedBytes, signature)) {
        throw new U2FException("Signature is invalid");
    }

    // The first time we create the SecurityKeyData, we set the counter value to 0.
    // We don't actually know what the counter value of the real device is - but it will
    // be something bigger (or equal) to 0, so subsequent signatures will check out ok.
    SecurityKeyData securityKeyData = new SecurityKeyData(currentTimeInMillis, transports, keyHandle,
            userPublicKey, attestationCertificate, /* initial counter value */ 0);
    dataStore.addSecurityKeyData(sessionData.getAccountName(), securityKeyData);

    Log.info("<< processRegistrationResponse");
    return securityKeyData;
}

From source file:com.joyent.manta.client.multipart.EncryptionState.java

ByteArrayOutputStream remainderAndLastPartAuth() throws IOException {
    if (!getLock().isHeldByCurrentThread()) {
        throw new IllegalStateException("remainderAndLastPartAuth called without lock owned");
    }/*w w w  .j ava  2s.co  m*/
    if (isLastPartAuthWritten()) {
        final String msg = "final CSE auth already written (complete called multiple times or "
                + "parts below min size)";
        MantaMultipartException mme = new MantaMultipartException(new IllegalStateException(msg));
        mme.setContextValue("lastPartNumber", getLastPartNumber());
        throw mme;
    }
    ByteArrayOutputStream remainderStream = new ByteArrayOutputStream();
    getMultipartStream().setNext(remainderStream);
    getCipherStream().close();
    remainderStream.write(getMultipartStream().getRemainder());

    if (getCipherStream().getClass().equals(HmacOutputStream.class)) {
        HMac hmac = ((HmacOutputStream) getCipherStream()).getHmac();
        byte[] hmacBytes = new byte[hmac.getMacSize()];
        hmac.doFinal(hmacBytes, 0);

        final int hmacSize = encryptionContext.getCipherDetails().getAuthenticationTagOrHmacLengthInBytes();

        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));
        }
        remainderStream.write(hmacBytes);
    }
    lastPartAuthWritten = true;
    return remainderStream;
}

From source file:com.petercho.Encoder.java

public static String hmacHex(String pass, String selectedText, String alg) {
    return Hex.encodeHexString(getHmac(pass, selectedText, alg));
}

From source file:com.joyent.manta.client.multipart.EncryptedMultipartManagerTest.java

public void canDoMultipartUpload() throws Exception {
    MantaMetadata metadata = new MantaMetadata();
    metadata.put("m-my-key", "my value");
    metadata.put("e-my-key-1", "my value 1");
    metadata.put("e-my-key-2", "my value 2");

    MantaHttpHeaders headers = new MantaHttpHeaders();

    String path = "/user/stor/testobject";

    EncryptedMultipartUpload<TestMultipartUpload> upload = manager.initiateUpload(path, 35L, metadata, headers);

    ArrayList<String> lines = new ArrayList<>();
    lines.add("01234567890ABCDEF|}{");
    lines.add("ZYXWVUTSRQPONMLKJIHG");
    lines.add("!@#$%^&*()_+-=[]/,.<");
    lines.add(">~`?abcdefghijklmnop");
    lines.add("qrstuvxyz");

    String expected = StringUtils.join(lines, "");

    MantaMultipartUploadPart[] parts = new MantaMultipartUploadPart[5];

    for (int i = 0; i < lines.size(); i++) {
        parts[i] = manager.uploadPart(upload, i + 1, lines.get(i));
    }/*from  w ww  .ja va 2s.c  o m*/

    Stream<MantaMultipartUploadTuple> partsStream = Stream.of(parts);

    manager.complete(upload, partsStream);

    TestMultipartUpload actualUpload = upload.getWrapped();

    MantaMetadata actualMetadata = MantaObjectMapper.INSTANCE.readValue(actualUpload.getMetadata(),
            MantaMetadata.class);

    Assert.assertEquals(actualMetadata, metadata, "Metadata wasn't stored correctly");

    MantaHttpHeaders actualHeaders = MantaObjectMapper.INSTANCE.readValue(actualUpload.getHeaders(),
            MantaHttpHeaders.class);

    Assert.assertEquals(actualHeaders, headers, "Headers were stored correctly");

    {
        Cipher cipher = cipherDetails.getCipher();
        byte[] iv = upload.getEncryptionState().getEncryptionContext().getCipher().getIV();
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, cipherDetails.getEncryptionParameterSpec(iv));

        byte[] assumedCiphertext = cipher.doFinal(expected.getBytes(StandardCharsets.US_ASCII));
        byte[] contents = FileUtils.readFileToByteArray(upload.getWrapped().getContents());
        byte[] actualCiphertext = Arrays.copyOf(contents,
                contents.length - cipherDetails.getAuthenticationTagOrHmacLengthInBytes());

        try {
            AssertJUnit.assertEquals(assumedCiphertext, actualCiphertext);
        } catch (AssertionError e) {
            System.err.println("expected: " + Hex.encodeHexString(assumedCiphertext));
            System.err.println("actual  : " + Hex.encodeHexString(actualCiphertext));
            throw e;
        }
    }

    EncryptionContext encryptionContext = upload.getEncryptionState().getEncryptionContext();

    MantaHttpHeaders responseHttpHeaders = new MantaHttpHeaders();
    responseHttpHeaders.setContentLength(actualUpload.getContents().length());

    final String hmacName = SupportedHmacsLookupMap
            .hmacNameFromInstance(encryptionContext.getCipherDetails().getAuthenticationHmac());

    responseHttpHeaders.put(MantaHttpHeaders.ENCRYPTION_HMAC_TYPE, hmacName);
    responseHttpHeaders.put(MantaHttpHeaders.ENCRYPTION_IV,
            Base64.getEncoder().encodeToString(encryptionContext.getCipher().getIV()));
    responseHttpHeaders.put(MantaHttpHeaders.ENCRYPTION_KEY_ID, cipherDetails.getCipherId());

    MantaObjectResponse response = new MantaObjectResponse(path, responseHttpHeaders, metadata);

    CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class);

    try (InputStream fin = new FileInputStream(actualUpload.getContents());
            EofSensorInputStream eofIn = new EofSensorInputStream(fin, null);
            MantaObjectInputStream objIn = new MantaObjectInputStream(response, httpResponse, eofIn);
            InputStream in = new MantaEncryptedObjectInputStream(objIn, cipherDetails, secretKey, true)) {
        String actual = IOUtils.toString(in, StandardCharsets.UTF_8);

        Assert.assertEquals(actual, expected);
    }
}

From source file:ch.cyberduck.core.http.HttpUploadFeature.java

protected void verify(final Path file, final MessageDigest digest, final Checksum checksum)
        throws ChecksumException {
    if (file.getType().contains(Path.Type.encrypted)) {
        log.warn(String.format("Skip checksum verification for %s with client side encryption enabled", file));
        return;//  w w  w.  j ava 2s .  c o m
    }
    if (null == digest) {
        log.debug(String.format("Digest disabled for file %s", file));
        return;
    }
    if (null == checksum || !checksum.algorithm.equals(HashAlgorithm.md5)) {
        log.warn("ETag returned by server is unknown checksum algorithm");
        return;
    }
    if (!checksum.algorithm.equals(HashAlgorithm.md5)) {
        log.warn(String.format("ETag %s returned by server is %s but expected MD5", checksum.hash,
                checksum.algorithm));
        return;
    }
    // Obtain locally-calculated MD5 hash.
    final String expected = Hex.encodeHexString(digest.digest());
    // Compare our locally-calculated hash with the ETag returned by S3.
    if (!checksum.equals(Checksum.parse(expected))) {
        throw new ChecksumException(
                MessageFormat.format(LocaleFactory.localizedString("Upload {0} failed", "Error"),
                        file.getName()),
                MessageFormat.format(
                        "Mismatch between MD5 hash {0} of uploaded data and ETag {1} returned by the server",
                        expected, checksum.hash));
    }
}

From source file:com.tcloud.bee.key.server.service.impl.SaslServiceImpl.java

private SaslParam authendicate(SaslParam saslParam) throws SaslException {
    SaslParam param = new SaslParam(saslParam.getCommand());
    KeySaslServer saslServer = this.getServer(saslParam.getSaslId());
    if (saslServer == null) {
        param.setChallenge("".getBytes());
        logger.warn("Abnormal behavior! saslServer is null.");
    } else {/* www  . jav  a  2 s  .co  m*/
        logger.debug("response:" + Hex.encodeHexString(saslParam.getResponse()));
        byte[] challenge = saslServer.auth(saslParam.getResponse());
        param.setChallenge(challenge);
        logger.debug("challenge2:" + Hex.encodeHexString(param.getChallenge()));
    }

    return param;
}

From source file:gobblin.metrics.reporter.util.SchemaRegistryVersionWriter.java

@Override
public Schema readSchemaVersioningInformation(DataInputStream inputStream) throws IOException {
    if (inputStream.readByte() != KafkaAvroSchemaRegistry.MAGIC_BYTE) {
        throw new IOException("MAGIC_BYTE not found in Avro message.");
    }/*from  ww w.j a v a 2 s  .com*/

    byte[] byteKey = new byte[schemaIdLengthBytes];
    int bytesRead = inputStream.read(byteKey, 0, schemaIdLengthBytes);
    if (bytesRead != schemaIdLengthBytes) {
        throw new IOException(
                String.format("Could not read enough bytes for schema id. Expected: %d, found: %d.",
                        schemaIdLengthBytes, bytesRead));
    }
    String hexKey = Hex.encodeHexString(byteKey);

    try {
        return this.registry.getSchemaByKey(hexKey);
    } catch (SchemaRegistryException sre) {
        throw new IOException("Failed to retrieve schema for key " + hexKey, sre);
    }
}