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.msd.gin.halyard.common.HalyardTableUtilsCalculateSplitsTest.java

@Test
public void testCalculateSplits() {
    Map<String, Integer> cMap = new HashMap<>();
    if (context != null) {
        cMap.put(context, splits);//from  w w w  . j av  a2s.  c  o  m
    }
    byte bb[][] = HalyardTableUtils.calculateSplits(splits, cMap);
    if (expected == null) {
        assertNull(bb);
    } else {
        assertEquals(expected.length, bb.length);
        for (int i = 0; i < expected.length; i++) {
            assertEquals(expected[i], Hex.encodeHexString(bb[i]));
        }
    }
}

From source file:inti.ws.spring.resource.template.TemplateResource.java

@Override
public void update() throws Exception {
    ExpressionFactory factory;/*from   ww w. jav a 2 s  .co  m*/
    ValueExpression var;
    Object val;
    StringBuilder builder = new StringBuilder(2048);
    MessageDigest digest = DIGESTS.get();

    factory = ExpressionFactory.newInstance();

    for (WebResource file : files) {
        if (file.hasChanged()) {
            file.update();
        }
        builder.append(applyTemplate(factory, file.getName(), file.getContent().replaceAll("\\s+", " ")));
        builder.append(',');
    }
    builder.delete(builder.length() - 1, builder.length());

    super.update();

    content = factory.createValueExpression(context, compressedFile, String.class);

    var = factory.createValueExpression(context, "${files}", String.class);
    var.setValue(context, builder.toString());

    if (parameters != null) {

        for (Map.Entry<String, Object> parameter : parameters.entrySet()) {
            var = factory.createValueExpression(context, "${" + parameter.getKey() + '}', String.class);
            val = parameter.getValue();

            if ("$filename".equals(val)) {
                val = resource.getFile();
            } else if ("$modulename".equals(val)) {
                val = moduleName;
            }

            var.setValue(context, val);
        }

    }
    compressedFile = (String) content.getValue(context);
    builder.delete(0, builder.length());

    digest.reset();
    builder.append(Hex.encodeHexString(digest.digest(compressedFile.getBytes(StandardCharsets.UTF_8))));
    messageDigest = builder.toString();
    builder.delete(0, builder.length());

    DATE_FORMATTER.formatDate(lastModified, builder);
    lastModifiedString = builder.toString();
}

From source file:com.tremolosecurity.proxy.auth.saml2.Saml2SingleLogout.java

@Override
public void handleLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    if (request == null || response == null) {
        //do nothing
        return;//from w  w w  . j  ava  2 s. co  m
    }

    String xmlAlg = SAML2Auth.xmlDigSigAlgs.get(digSigAlg);

    if (xmlAlg == null) {
        throw new ServletException("Unknown Signiture algorithm : '" + digSigAlg + "'");
    }

    String javaAlg = SAML2Auth.javaDigSigAlgs.get(digSigAlg);

    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);

    ConfigManager cfgMgr = holder.getConfig();

    LogoutRequestBuilder lrb = new LogoutRequestBuilder();
    LogoutRequest lr = lrb.buildObject();

    DateTime dt = new DateTime();
    lr.setIssueInstant(dt);

    lr.setDestination(logoutURL);

    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);

    String id = "f" + Hex.encodeHexString(idBytes);
    lr.setID(id);

    IssuerBuilder ib = new IssuerBuilder();
    Issuer issuer = ib.buildObject();
    issuer.setValue(assertionConsumerServiceURL);
    lr.setIssuer(issuer);

    NameIDBuilder nidbpb = new NameIDBuilder();
    NameID nid = nidbpb.buildObject();
    //nidp.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
    nid.setFormat(nameIDFormat);

    //nid.setSPNameQualifier(assertionConsumerServiceURL);
    nid.setValue(nameID);
    lr.setNameID(nid);

    SessionIndexBuilder sib = new SessionIndexBuilder();
    SessionIndex si = sib.buildObject();
    si.setSessionIndex(sessionIndex);
    lr.getSessionIndexes().add(si);

    try {
        // Get the Subject marshaller
        Marshaller marshaller = new LogoutRequestMarshaller();

        // Marshall the Subject
        //Element assertionElement = marshaller.marshall(lr);

        String xml = OpenSAMLUtils.xml2str(lr);
        xml = xml.substring(xml.indexOf("?>") + 2);

        if (logger.isDebugEnabled()) {
            logger.debug("=======AuthnRequest============");
            logger.debug(xml);
            logger.debug("=======AuthnRequest============");
        }

        byte[] bxml = xml.getBytes("UTF-8");

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        DeflaterOutputStream compressor = new DeflaterOutputStream(baos,
                new Deflater(Deflater.BEST_COMPRESSION, true));

        compressor.write(bxml);
        compressor.flush();
        compressor.close();

        String b64 = new String(Base64.encodeBase64(baos.toByteArray()));
        StringBuffer redirURL = new StringBuffer();
        StringBuffer query = new StringBuffer();

        idBytes = new byte[20];
        random.nextBytes(idBytes);

        query.append("SAMLRequest=").append(URLEncoder.encode(b64, "UTF-8")).append("&RelayState=")
                .append(URLEncoder.encode(Hex.encodeHexString(idBytes), "UTF-8"));

        query.append("&SigAlg=").append(URLEncoder.encode(xmlAlg, "UTF-8"));
        //http://www.w3.org/2000/09/xmldsig#rsa-sha1

        java.security.Signature signer = java.security.Signature.getInstance(javaAlg);

        PrivateKey sigKey = cfgMgr.getPrivateKey(signingKeyAlias);

        if (sigKey == null) {
            throw new ServletException("Signing Key : '" + signingKeyAlias + "' not found");
        }

        signer.initSign(sigKey);
        signer.update(query.toString().getBytes("UTF-8"));
        String base64Sig = new String(Base64.encodeBase64(signer.sign()));
        query.append("&Signature=").append(URLEncoder.encode(base64Sig, "UTF-8"));

        redirURL.append(logoutURL).append("?").append(query.toString());

        if (logger.isDebugEnabled()) {
            logger.debug("Logout URL : '" + redirURL.toString() + "'");
        }

        //((ProxyResponse) response).removeHeader("Location");
        response.sendRedirect(redirURL.toString());

    } catch (Exception e) {
        throw new ServletException("Could not generate logout request", e);
    }

}

From source file:ch.cyberduck.core.azure.AzureObjectListService.java

@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener)
        throws BackgroundException {
    try {//  ww w  . j  a v  a 2  s  .  c o m
        final CloudBlobContainer container = session.getClient()
                .getContainerReference(containerService.getContainer(directory).getName());
        final AttributedList<Path> children = new AttributedList<Path>();
        ResultContinuation token = null;
        ResultSegment<ListBlobItem> result;
        String prefix = StringUtils.EMPTY;
        if (!containerService.isContainer(directory)) {
            prefix = containerService.getKey(directory);
            if (!prefix.endsWith(String.valueOf(Path.DELIMITER))) {
                prefix += Path.DELIMITER;
            }
        }
        do {
            final BlobRequestOptions options = new BlobRequestOptions();
            result = container.listBlobsSegmented(prefix, false, EnumSet.noneOf(BlobListingDetails.class),
                    PreferencesFactory.get().getInteger("azure.listing.chunksize"), token, options, context);
            for (ListBlobItem object : result.getResults()) {
                if (new Path(object.getUri().getPath(), EnumSet.of(Path.Type.directory)).equals(directory)) {
                    continue;
                }
                final PathAttributes attributes = new PathAttributes();
                if (object instanceof CloudBlob) {
                    final CloudBlob blob = (CloudBlob) object;
                    attributes.setSize(blob.getProperties().getLength());
                    attributes.setModificationDate(blob.getProperties().getLastModified().getTime());
                    attributes.setETag(blob.getProperties().getEtag());
                    if (StringUtils.isNotBlank(blob.getProperties().getContentMD5())) {
                        attributes.setChecksum(Checksum.parse(Hex
                                .encodeHexString(Base64.decodeBase64(blob.getProperties().getContentMD5()))));
                    }
                }
                // A directory is designated by a delimiter character.
                final EnumSet<AbstractPath.Type> types = object instanceof CloudBlobDirectory
                        ? EnumSet.of(Path.Type.directory, Path.Type.placeholder)
                        : EnumSet.of(Path.Type.file);
                final Path child = new Path(directory, PathNormalizer.name(object.getUri().getPath()), types,
                        attributes);
                children.add(child);
            }
            listener.chunk(directory, children);
            token = result.getContinuationToken();
        } while (result.getHasMoreResults());
        return children;
    } catch (StorageException e) {
        throw new AzureExceptionMappingService().map("Listing directory {0} failed", e, directory);
    } catch (URISyntaxException e) {
        throw new NotfoundException(e.getMessage(), e);
    }
}

From source file:com.google.u2f.key.impl.U2FKeyReferenceImpl.java

@Override
public AuthenticateResponse authenticate(AuthenticateRequest authenticateRequest) throws U2FException {
    Log.info(">> authenticate");

    byte control = authenticateRequest.getControl();
    byte[] applicationSha256 = authenticateRequest.getApplicationSha256();
    byte[] challengeSha256 = authenticateRequest.getChallengeSha256();
    byte[] keyHandle = authenticateRequest.getKeyHandle();

    Log.info(" -- Inputs --");
    Log.info("  control: " + control);
    Log.info("  applicationSha256: " + Hex.encodeHexString(applicationSha256));
    Log.info("  challengeSha256: " + Hex.encodeHexString(challengeSha256));
    Log.info("  keyHandle: " + Hex.encodeHexString(keyHandle));

    KeyPair keyPair = dataStore.getKeyPair(keyHandle);
    int counter = dataStore.incrementCounter();
    byte userPresence = userPresenceVerifier.verifyUserPresence();
    byte[] signedData = RawMessageCodec.encodeAuthenticateSignedBytes(applicationSha256, userPresence, counter,
            challengeSha256);// w w w .ja v  a2s. c  o m

    Log.info("Signing bytes " + Hex.encodeHexString(signedData));

    byte[] signature = crypto.sign(signedData, keyPair.getPrivate());

    Log.info(" -- Outputs --");
    Log.info("  userPresence: " + userPresence);
    Log.info("  counter: " + counter);
    Log.info("  signature: " + Hex.encodeHexString(signature));

    Log.info("<< authenticate");

    return new AuthenticateResponse(userPresence, counter, signature);
}

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

@Override
public InputStream toBeSigned(Document document, SignatureParameters parameters) throws IOException {
    try {/*from   ww w  .  j a v  a 2s.c o m*/
        PAdESProfileEPES padesProfile = new PAdESProfileEPES();

        PDFSignatureService pdfSignatureService = new ITextPDFSignatureService();
        byte[] messageDigest = pdfSignatureService.digest(document.openStream(), parameters);

        LOG.fine("Calculated digest on byterange " + Hex.encodeHexString(messageDigest));

        PreComputedContentSigner contentSigner = new PreComputedContentSigner(
                SignatureAlgorithm.RSA.getJavaSignatureAlgorithm(parameters.getDigestAlgorithm()));

        DigestCalculatorProvider digestCalculatorProvider = new BcDigestCalculatorProvider();
        CMSSignedDataGenerator generator = padesProfile.createCMSSignedDataGenerator(contentSigner,
                digestCalculatorProvider, parameters, messageDigest);

        CMSProcessableByteArray content = new CMSProcessableByteArray(
                pdfSignatureService.digest(document.openStream(), parameters));

        generator.generate(content, false);

        return new ByteArrayInputStream(contentSigner.getByteOutputStream().toByteArray());
    } catch (CMSException e) {
        throw new IOException(e);
    } catch (DocumentException e) {
        throw new IOException(e);
    }

}

From source file:com.kuzumeji.platform.standard.SecurityService.java

/**
 * RSA???/*w  w w  . j ava  2s  . c  o m*/
 * <dl>
 * <dt>?
 * <dd>RSA???
 * </dl>
 * @param name RSA???
 * @param keyPair RSA?
 */
public void saveKeyPair(final String name, final KeyPair keyPair) {
    try {
        final Properties property = new PropertyService(PROPERTY_NAME).getProperty();
        final RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        property.setProperty(String.format(KEY_PUBLIC_ENCODED, name),
                Hex.encodeHexString(publicKey.getEncoded()));
        final RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        property.setProperty(String.format(KEY_PRIVATE_ENCODED, name),
                Hex.encodeHexString(privateKey.getEncoded()));
        try (FileOutputStream stream = new FileOutputStream(
                Thread.currentThread().getContextClassLoader().getResource(PROPERTY_NAME).getPath());) {
            property.store(stream, "RSAPublicKey and RSAPrivateKey");
        }
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.thoughtworks.go.plugin.infra.commons.PluginsZip.java

public void create() {
    checkFilesAccessibility(bundledPlugins, externalPlugins);
    reset();//from  w  ww  .  j a v  a2 s.com

    MessageDigest md5Digest = DigestUtils.getMd5Digest();
    try (ZipOutputStream zos = new ZipOutputStream(
            new DigestOutputStream(new BufferedOutputStream(new FileOutputStream(destZipFile)), md5Digest))) {
        for (GoPluginDescriptor agentPlugins : agentPlugins()) {
            String zipEntryPrefix = "external/";

            if (agentPlugins.isBundledPlugin()) {
                zipEntryPrefix = "bundled/";
            }

            zos.putNextEntry(
                    new ZipEntry(zipEntryPrefix + new File(agentPlugins.pluginFileLocation()).getName()));
            Files.copy(new File(agentPlugins.pluginFileLocation()).toPath(), zos);
            zos.closeEntry();
        }
    } catch (Exception e) {
        LOG.error("Could not create zip of plugins for agent to download.", e);
    }

    md5DigestOfPlugins = Hex.encodeHexString(md5Digest.digest());
}

From source file:com.streamsets.lib.security.http.PasswordHasher.java

public String[] getRandomValueAndHash() {
    byte[] random = new byte[64];
    SECURE_RANDOM.nextBytes(random);//from   ww w  .  j  av  a 2s  . c o m
    String value = Hex.encodeHexString(random);
    String hash = getPasswordHash(value, value);
    return new String[] { value, hash };
}

From source file:android.apn.androidpn.server.xmpp.auth.AuthManager.java

private static String createDigest(String token, String password) {
    synchronized (DIGEST_LOCK) {
        digest.update(token.getBytes());
        return Hex.encodeHexString(digest.digest(password.getBytes()));
    }//w ww .  j  a  va 2 s  .c om
}