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.aoppp.gatewaysdk.internal.hw.DigestUtils2.java

/**
 * Calculates the MD2 digest and returns the value as a 32 character hex string.
 *
 * @param data//from w  w  w. j  a  va2 s.  c o  m
 *            Data to digest
 * @return MD2 digest as a hex string
 * @since 1.7
 */
public static String md2Hex(final String data) {
    return Hex.encodeHexString(md2(data));
}

From source file:de.elomagic.carafile.client.CaraFileClient.java

/**
 * Uploads data via an {@link InputStream} (Single chunk upload).
 * <p/>/*  w w  w. j a va  2 s.com*/
 * Single chunk upload means that the complete file will be upload in one step.
 *
 * @param in The input stream. It's not recommended to use a buffered stream.
 * @param filename Name of the file
 * @param contentLength Length of the content in bytes
 * @return Returns the {@link MetaData} of the uploaded stream
 * @throws IOException Thrown when unable to call REST services
 * @see CaraFileClient#uploadFile(java.net.URI, java.nio.file.Path, java.lang.String)
 */
public MetaData uploadFile(final InputStream in, final String filename, final long contentLength)
        throws IOException {
    if (registryURI == null) {
        throw new IllegalArgumentException("Parameter 'registryURI' must not be null!");
    }

    if (in == null) {
        throw new IllegalArgumentException("Parameter 'in' must not be null!");
    }

    URI peerURI = peerSelector.getURI(downloadPeerSet(), -1);

    if (peerURI == null) {
        throw new IOException("No peer for upload available");
    }

    URI uri = CaraFileUtils.buildURI(peerURI, "peer", "seedFile", filename);

    MessageDigest messageDigest = DigestUtils.getSha1Digest();

    try (BufferedInputStream bis = new BufferedInputStream(in);
            DigestInputStream dis = new DigestInputStream(bis, messageDigest)) {
        HttpResponse response = executeRequest(
                Request.Post(uri).bodyStream(dis, ContentType.APPLICATION_OCTET_STREAM)).returnResponse();

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            throw new HttpResponseException(statusCode,
                    "Unable to upload file: " + response.getStatusLine().getReasonPhrase());
        }

        MetaData md = getMetaDataFromResponse(response);

        if (!Hex.encodeHexString(messageDigest.digest()).equals(md.getId())) {
            throw new IOException("Peer response invalid SHA1 of file");
        }

        return md;
    }
}

From source file:eu.europa.esig.dss.pdf.pdfbox.PdfBoxSignatureService.java

private byte[] signDocumentAndReturnDigest(final PAdESSignatureParameters parameters,
        final byte[] signatureBytes, final File signedFile, final FileOutputStream fileOutputStream,
        final PDDocument pdDocument, final PDSignature pdSignature, final DigestAlgorithm digestAlgorithm)
        throws DSSException {

    try {/*  ww  w  .j  ava2 s  .c  om*/

        final MessageDigest digest = DSSUtils.getMessageDigest(digestAlgorithm);
        // register signature dictionary and sign interface
        SignatureInterface signatureInterface = new SignatureInterface() {

            @Override
            public byte[] sign(InputStream content) throws SignatureException, IOException {

                byte[] b = new byte[4096];
                int count;
                while ((count = content.read(b)) > 0) {
                    digest.update(b, 0, count);
                }
                return signatureBytes;
            }
        };

        SignatureOptions options = new SignatureOptions();
        options.setPreferedSignatureSize(parameters.getSignatureSize());

        if (parameters.getImageParameters() != null) {
            fillImageParameters(pdDocument, parameters.getImageParameters(), options);
        }
        pdDocument.addSignature(pdSignature, signatureInterface, options);

        saveDocumentIncrementally(parameters, signedFile, fileOutputStream, pdDocument);
        final byte[] digestValue = digest.digest();
        if (logger.isDebugEnabled()) {
            logger.debug("Digest to be signed: " + Hex.encodeHexString(digestValue));
        }
        fileOutputStream.close();
        return digestValue;
    } catch (IOException e) {
        throw new DSSException(e);
    } catch (SignatureException e) {
        throw new DSSException(e);
    }
}

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

/**
 * TODO: Change the text<br>//from  w w  w.  j  a v a2  s  .co m
 * The ID of xades:SignedProperties is contained in the signed content of the xades Signature. We must create this ID
 * in a deterministic way. The signingDate and signingCertificate are mandatory in the more basic level of signature,
 * we use them as "seed" for generating the ID.
 *
 * @return
 */
public String getDeterministicId() {

    if (deterministicId != null) {
        return deterministicId;
    }

    try {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.update(Long.toString(getSigningDate().getTime()).getBytes());
        digest.update(getSigningCertificate().getEncoded());
        deterministicId = "id" + Hex.encodeHexString(digest.digest());
        return deterministicId;
    } catch (CertificateEncodingException ex) {
        throw new RuntimeException("Certificate encoding exception");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:io.cslinmiso.line.api.impl.LineApiImpl.java

public LoginResult login(String id, String password, String certificate) throws Exception {

    IdentityProvider provider = null;//from   w  w w. j a v a  2  s.c  om
    Map<String, String> json = null;
    String sessionKey = null;
    boolean keepLoggedIn = true;
    String accessLocation = this.ip;

    // Login to LINE server.
    if (id.matches(EMAIL_REGEX)) {
        provider = IdentityProvider.LINE; // LINE
        json = getCertResult(LINE_SESSION_LINE_URL);
    } else {
        provider = IdentityProvider.NAVER_KR; // NAVER
        json = getCertResult(LINE_SESSION_NAVER_URL);
    }

    if (id != null) {
        this.id = id;
    }

    if (password != null) {
        this.password = password;
    }

    if (StringUtils.isNotEmpty(certificate)) {
        setCertificate(certificate);
    } else {
        // read the certificate file if it exists
        try {
            List<String> readFile = Utility.readFile(LineApiImpl.CERT_FILE);
            String tmpCert = readFile != null ? readFile.get(0) : "";
            if (tmpCert != null) {
                setCertificate(tmpCert);
            }
        } catch (Exception ex) {
            setCertificate("");
        }
    }

    sessionKey = json.get("session_key");
    String tmpMsg = (char) (sessionKey.length()) + sessionKey + (char) (id.length()) + id
            + (char) (password.length()) + password;
    String message = new String(tmpMsg.getBytes(), java.nio.charset.StandardCharsets.UTF_8);
    String[] keyArr = json.get("rsa_key").split(",");
    String keyName = keyArr[0];
    String n = keyArr[1];
    String e = keyArr[2];

    BigInteger modulus = new BigInteger(n, 16);
    BigInteger pubExp = new BigInteger(e, 16);

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, pubExp);
    RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] enBytes = cipher.doFinal(message.getBytes());
    String encryptString = Hex.encodeHexString(enBytes);

    THttpClient transport = new THttpClient(LINE_HTTP_URL);
    transport.setCustomHeaders(headers);
    transport.open();

    TProtocol protocol = new TCompactProtocol(transport);
    this.client = new TalkService.Client(protocol);

    LoginResult result = this.client.loginWithIdentityCredentialForCertificate(provider, keyName, encryptString,
            keepLoggedIn, accessLocation, this.systemName, this.certificate);

    if (result.getType() == LoginResultType.REQUIRE_DEVICE_CONFIRM) {

        headers.put("X-Line-Access", result.getVerifier());
        String pinCode = result.getPinCode();

        System.out.printf("Enter PinCode '%s' to your mobile phone in 2 minutes.\n", pinCode);
        // await for pinCode to be certified, it will return a verifier afterward.
        loginWithVerifierForCertificate();
    } else if (result.getType() == LoginResultType.SUCCESS) {
        // if param certificate has passed certification
        setAuthToken(result.getAuthToken());
    }

    // Once the client passed the verification, switch connection to HTTP_IN_URL
    this.client = ready();
    return result;
}

From source file:lumbermill.internal.aws.AWSV4SignerImpl.java

private String sign(String stringToSign, LocalDateTime now, AWSCredentials credentials) {
    return Hex.encodeHexString(hmacSHA256(stringToSign, getSignatureKey(now, credentials)));
}

From source file:ch.cyberduck.core.openstack.SwiftUrlProvider.java

protected String sign(final String secret, final String body) {
    try {/*  w w w  .java2s. c  o m*/
        // Acquire an HMAC/SHA1 from the raw key bytes.
        final SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(Charset.forName("UTF-8")),
                Constants.HMAC_SHA1_ALGORITHM);
        // Acquire the MAC instance and initialize with the signing key.
        final Mac mac = Mac.getInstance(Constants.HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);
        return Hex.encodeHexString(mac.doFinal(body.getBytes(Charset.forName("UTF-8"))));
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        log.error(String.format("Error signing %s %s", body, e.getMessage()));
        return null;
    }
}

From source file:com.filelocker.encryption.AES_Encryption.java

/**
 * If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv).
 * We have the password from initializing the class. pass the iv and salt here which is
 * obtained when encrypting the file initially.
 *
 * @param inFile - The Encrypted File containing encrypted data , salt and InitVec
 * @throws NoSuchAlgorithmException//  w ww.j a  v  a 2s  .  c  om
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws DecoderException
 * @throws IOException
 */
public void setupDecrypt(File inFile)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, DecoderException, IOException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;
    SecretKey secret = null;

    byte[] vSalt = new byte[8];
    byte[] vInitVec = new byte[16];

    RandomAccessFile vFile = new RandomAccessFile(inFile, "rw");

    //The last 8 bits are salt so seek to length of file minus 9 bits
    vFile.seek(vFile.length() - 8);
    vFile.readFully(vSalt);

    //The last 8 bits are salt and 16 bits before last 8 are Initialization Vectory so 8+16=24
    //Thus to seek to length of file minus 24 bits
    vFile.seek(vFile.length() - 24);
    vFile.readFully(vInitVec);
    vFile.seek(0);

    File tmpFile = new File(inFile.getAbsolutePath() + ".tmpEncryption.file");

    RandomAccessFile vTmpFile = new RandomAccessFile(tmpFile, "rw");

    for (int i = 0; i < (vFile.length() - 24); ++i) {
        vTmpFile.write(vFile.readByte());
    }
    vFile.close();
    vTmpFile.close();

    inFile.delete();
    tmpFile.renameTo(inFile);

    Db("got salt " + Hex.encodeHexString(vSalt));

    Db("got initvector :" + Hex.encodeHexString(vInitVec));

    /* 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
    // PBKDF2WithHmacSHA1,Constructs secret keys using the Password-Based Key Derivation Function function
    //found in PKCS #5 v2.0. (PKCS #5: Password-Based Cryptography Standard)

    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(vPassword.toCharArray(), vSalt, ITERATIONS, KEYLEN_BITS);

    tmp = factory.generateSecret(spec);
    secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    // Decrypt the message, given derived key and initialization vector.
    vDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    vDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(vInitVec));
}

From source file:com.inventage.nexusaptplugin.DebianIndexCreator.java

@Override
public void populateArtifactInfo(ArtifactContext ac) throws IOException {
    if (ac.getArtifact() != null && "deb".equals(ac.getArtifactInfo().packaging)) {
        List<String> control = GetControl.doGet(ac.getArtifact());
        ac.getArtifactInfo().getAttributes().putAll(DebControlParser.parse(control));
        ac.getArtifactInfo().getAttributes().put("Filename", getRelativeFileNameOfArtifact(ac));

        FileInputStream is = null;
        try {/*from  www.j a va  2  s  . c o m*/
            is = new FileInputStream(ac.getArtifact());
            MessageDigest md5d = DigestUtils.getMd5Digest();
            MessageDigest sha256 = DigestUtils.getSha256Digest();
            MessageDigest sha512 = DigestUtils.getSha512Digest();

            int count;
            byte[] b = new byte[512];
            while ((count = is.read(b)) >= 0) {
                md5d.update(b, 0, count);
                sha256.update(b, 0, count);
                sha512.update(b, 0, count);
            }

            ac.getArtifactInfo().md5 = Hex.encodeHexString(md5d.digest());
            ac.getArtifactInfo().getAttributes().put(DEBIAN.SHA256.getFieldName(),
                    Hex.encodeHexString(sha256.digest()));
            ac.getArtifactInfo().getAttributes().put(DEBIAN.SHA512.getFieldName(),
                    Hex.encodeHexString(sha512.digest()));
        } finally {
            is.close();
        }
    }
}

From source file:be.e_contract.eid.applet.service.impl.handler.IdentityDataMessageHandler.java

/**
 * Tries to parse the X509 certificate.//from ww w  . ja  v a2s  . c o m
 * 
 * @param certFile
 * @return the X509 certificate, or <code>null</code> in case of a DER
 *         decoding error.
 */
private X509Certificate getCertificate(byte[] certFile) {
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
        X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(certFile));
        return certificate;
    } catch (CertificateException e) {
        LOG.warn("certificate error: " + e.getMessage(), e);
        LOG.debug("certificate size: " + certFile.length);
        LOG.debug("certificate file content: " + Hex.encodeHexString(certFile));
        /*
         * Missing eID authentication and eID non-repudiation certificates
         * could become possible for future eID cards. A missing certificate
         * is represented as a block of 1300 null bytes.
         */
        if (1300 == certFile.length) {
            boolean missingCertificate = true;
            for (int idx = 0; idx < certFile.length; idx++) {
                if (0 != certFile[idx]) {
                    missingCertificate = false;
                }
            }
            if (missingCertificate) {
                LOG.debug("the certificate data indicates a missing certificate");
            }
        }
        return null;
    }
}