List of usage examples for org.apache.commons.codec.binary Hex encodeHexString
public static String encodeHexString(byte[] data)
From source file:com.dinochiesa.edgecallouts.AesCryptoCallout.java
private void setOutput(MessageContext msgCtxt, byte[] result) throws Exception { EncodingType outputEncodingWanted = getEncodeResult(msgCtxt); String outputVar = getOutputVar(msgCtxt); if (outputEncodingWanted == EncodingType.BASE64) { msgCtxt.setVariable(varName("output_encoding"), "base64"); msgCtxt.setVariable(outputVar, Base64.encodeBase64String(result)); } else if (outputEncodingWanted == EncodingType.HEX) { msgCtxt.setVariable(varName("output_encoding"), "hex"); msgCtxt.setVariable(outputVar, Hex.encodeHexString(result)); } else {/*from ww w . j a v a 2s . c o m*/ // emit the result as a Java byte array msgCtxt.setVariable(varName("output_encoding"), "none"); msgCtxt.setVariable(outputVar, result); } }
From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java
private static void exportIdPMetadata(Options options, CommandLine cmd, TremoloType tt, KeyStore ks) throws Exception, KeyStoreException, CertificateEncodingException, NoSuchAlgorithmException, UnrecoverableKeyException, SecurityException, MarshallingException, SignatureException { InitializationService.initialize();/* w w w . ja v a 2 s. c om*/ logger.info("Finding IdP..."); String idpName = loadOption(cmd, "idpName", options); ApplicationType idp = null; for (ApplicationType app : tt.getApplications().getApplication()) { if (app.getName().equalsIgnoreCase(idpName)) { idp = app; } } if (idp == null) { throw new Exception("IdP '" + idpName + "' not found"); } logger.info("Loading the base URL"); String baseURL = loadOption(cmd, "urlBase", options); String url = baseURL + idp.getUrls().getUrl().get(0).getUri(); SecureRandom random = new SecureRandom(); byte[] idBytes = new byte[20]; random.nextBytes(idBytes); StringBuffer b = new StringBuffer(); b.append('f').append(Hex.encodeHexString(idBytes)); String id = b.toString(); EntityDescriptorBuilder edb = new EntityDescriptorBuilder(); EntityDescriptor ed = edb.buildObject(); ed.setID(id); ed.setEntityID(url); IDPSSODescriptorBuilder idpssdb = new IDPSSODescriptorBuilder(); IDPSSODescriptor sd = idpssdb.buildObject();//ed.getSPSSODescriptor("urn:oasis:names:tc:SAML:2.0:protocol"); sd.addSupportedProtocol("urn:oasis:names:tc:SAML:2.0:protocol"); ed.getRoleDescriptors().add(sd); HashMap<String, List<String>> params = new HashMap<String, List<String>>(); for (ParamType pt : idp.getUrls().getUrl().get(0).getIdp().getParams()) { List<String> vals = params.get(pt.getName()); if (vals == null) { vals = new ArrayList<String>(); params.put(pt.getName(), vals); } vals.add(pt.getValue()); } sd.setWantAuthnRequestsSigned(params.containsKey("requireSignedAuthn") && params.get("requireSignedAuthn").get(0).equalsIgnoreCase("true")); KeyDescriptorBuilder kdb = new KeyDescriptorBuilder(); if (params.get("encKey") != null && !params.get("encKey").isEmpty() && (ks.getCertificate(params.get("encKey").get(0)) != null)) { KeyDescriptor kd = kdb.buildObject(); kd.setUse(UsageType.ENCRYPTION); KeyInfoBuilder kib = new KeyInfoBuilder(); KeyInfo ki = kib.buildObject(); X509DataBuilder x509b = new X509DataBuilder(); X509Data x509 = x509b.buildObject(); X509CertificateBuilder certb = new X509CertificateBuilder(); org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject(); cert.setValue(Base64.encode(ks.getCertificate(params.get("encKey").get(0)).getEncoded())); x509.getX509Certificates().add(cert); ki.getX509Datas().add(x509); kd.setKeyInfo(ki); sd.getKeyDescriptors().add(kd); } if (params.get("sigKey") != null && !params.get("sigKey").isEmpty() && (ks.getCertificate(params.get("sigKey").get(0)) != null)) { KeyDescriptor kd = kdb.buildObject(); kd.setUse(UsageType.SIGNING); KeyInfoBuilder kib = new KeyInfoBuilder(); KeyInfo ki = kib.buildObject(); X509DataBuilder x509b = new X509DataBuilder(); X509Data x509 = x509b.buildObject(); X509CertificateBuilder certb = new X509CertificateBuilder(); org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject(); cert.setValue(Base64.encode(ks.getCertificate(params.get("sigKey").get(0)).getEncoded())); x509.getX509Certificates().add(cert); ki.getX509Datas().add(x509); kd.setKeyInfo(ki); sd.getKeyDescriptors().add(kd); } HashSet<String> nameids = new HashSet<String>(); for (TrustType trustType : idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust()) { for (ParamType pt : trustType.getParam()) { if (pt.getName().equalsIgnoreCase("nameIdMap")) { String val = pt.getValue().substring(0, pt.getValue().indexOf('=')); if (!nameids.contains(val)) { nameids.add(val); } } } } NameIDFormatBuilder nifb = new NameIDFormatBuilder(); for (String nidf : nameids) { NameIDFormat nif = nifb.buildObject(); nif.setFormat(nidf); sd.getNameIDFormats().add(nif); } SingleSignOnServiceBuilder ssosb = new SingleSignOnServiceBuilder(); SingleSignOnService sso = ssosb.buildObject(); sso.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"); sso.setLocation(url + "/httpPost"); sd.getSingleSignOnServices().add(sso); sso = ssosb.buildObject(); sso.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"); sso.setLocation(url + "/httpRedirect"); sd.getSingleSignOnServices().add(sso); String signingKey = loadOptional(cmd, "signMetadataWithKey", options); if (signingKey != null && ks.getCertificate(signingKey) != null) { BasicX509Credential signingCredential = new BasicX509Credential( (X509Certificate) ks.getCertificate(signingKey), (PrivateKey) ks.getKey(signingKey, tt.getKeyStorePassword().toCharArray())); Signature signature = OpenSAMLUtils.buildSAMLObject(Signature.class); signature.setSigningCredential(signingCredential); signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1); signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); ed.setSignature(signature); try { XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(ed).marshall(ed); } catch (MarshallingException e) { throw new RuntimeException(e); } Signer.signObject(signature); } // Get the Subject marshaller EntityDescriptorMarshaller marshaller = new EntityDescriptorMarshaller(); // Marshall the Subject Element assertionElement = marshaller.marshall(ed); logger.info(net.shibboleth.utilities.java.support.xml.SerializeSupport.nodeToString(assertionElement)); }
From source file:at.creadoo.util.netio.NetIO.java
private String getPasswordHash() throws NoSuchAlgorithmException, UnsupportedEncodingException { return Hex.encodeHexString( (DigestUtils.getMd5Digest().digest((user + pass + hash).getBytes(Constants.DEFAULT_CHARSET)))); }
From source file:de.fosd.jdime.artifact.Artifact.java
/** * Returns a hash of the tree rooted in this {@code Artifact}. * * @return the tree hash/*from www . j av a 2 s. c om*/ */ public String getTreeHash() { if (hashValid) { return hash; } MessageDigest digest = DigestUtils.getSha256Digest(); DigestUtils.updateDigest(digest, hashId()); if (hasChildren()) { children.forEach(c -> DigestUtils.updateDigest(digest, c.getTreeHash())); hash = "1" + Hex.encodeHexString(digest.digest()); } else { hash = "0" + Hex.encodeHexString(digest.digest()); } hashValid = true; return hash; }
From source file:eu.europa.ec.markt.dss.signature.pades.PAdESProfileLTV.java
@Override public Document extendSignatures(Document document, Document originalData, SignatureParameters parameters) throws IOException { try {/*ww w . j av a 2 s . co m*/ final PdfReader reader = new PdfReader(document.openStream()); final ByteArrayOutputStream output = new ByteArrayOutputStream(); final PdfStamper stamper = new PdfStamper(reader, output, '\0', true); LTVSignatureValidationCallback callback = new LTVSignatureValidationCallback(stamper); pdfSignatureService.validateSignatures(document.openStream(), callback); PdfIndirectReference certsRef = stamper.getWriter().getPdfIndirectReference(); stamper.getWriter().addToBody(callback.getCertsArray(), certsRef, false); PdfDictionary dssDictionary = new PdfDictionary(new PdfName("DSS")); PdfDictionary vriDictionary = new PdfDictionary(new PdfName("VRI")); PdfDictionary sigVriDictionary = new PdfDictionary(); integrateCRL(callback, stamper, dssDictionary, sigVriDictionary, sigVriDictionary); integrateOCSP(callback, stamper, dssDictionary, sigVriDictionary, sigVriDictionary); // Add the signature's VRI dictionary, hashing the signature block from the callback method MessageDigest _md = MessageDigest.getInstance(DigestAlgorithm.SHA1.getName()); String hexHash = Hex.encodeHexString(_md.digest(callback.getSignatureBlock())).toUpperCase(); PdfIndirectReference sigVriRef = stamper.getWriter().getPdfIndirectReference(); stamper.getWriter().addToBody(sigVriDictionary, sigVriRef, false); vriDictionary.put(new PdfName(hexHash), sigVriRef); PdfIndirectReference vriRef = stamper.getWriter().getPdfIndirectReference(); stamper.getWriter().addToBody(vriDictionary, vriRef, false); // Add final objects to DSS dictionary dssDictionary.put(new PdfName("VRI"), vriRef); dssDictionary.put(new PdfName("Certs"), certsRef); PdfIndirectReference dssRef = stamper.getWriter().getPdfIndirectReference(); stamper.getWriter().addToBody(dssDictionary, dssRef, false); reader.getCatalog().put(new PdfName("DSS"), dssRef); // /Extensions<</ADBE<</BaseVersion/1.7/ExtensionLevel 5>>>> PdfDeveloperExtension etsiExtension = new PdfDeveloperExtension(PdfName.ADBE, new PdfName("1.7"), 5); stamper.getWriter().addDeveloperExtension(etsiExtension); stamper.getWriter().addToBody(reader.getCatalog(), reader.getCatalog().getIndRef(), false); stamper.close(); output.close(); Document extendedDocument = new InMemoryDocument(output.toByteArray()); ByteArrayOutputStream ltvDoc = new ByteArrayOutputStream(); ITextPDFDocTimeSampService service = new ITextPDFDocTimeSampService(); byte[] digest = service.digest(extendedDocument.openStream(), parameters); TimeStampResponse tsToken = tspSource.getTimeStampResponse(parameters.getDigestAlgorithm(), digest); service.sign(extendedDocument.openStream(), tsToken.getTimeStampToken().getEncoded(), ltvDoc, parameters); return new InMemoryDocument(ltvDoc.toByteArray()); } catch (DocumentException ex) { throw new RuntimeException(ex); } catch (SignatureException e) { throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
From source file:de.elomagic.carafile.client.CaraFileClient.java
/** * Downloads a file into a {@link OutputStream}. * * @param md {@link MetaData} of the file. * @param out The output stream. It's not recommended to use a buffered stream. * @throws IOException Thrown when unable to write file into the output stream or the SHA-1 validation failed. *//*www. j a v a2s .c om*/ public void downloadFile(final MetaData md, final OutputStream out) throws IOException { if (md == null) { throw new IllegalArgumentException("Parameter 'md' must not be null!"); } if (out == null) { throw new IllegalArgumentException("Parameter 'out' must not be null!"); } Map<String, Path> downloadedChunks = new HashMap<>(); Set<String> chunksToDownload = new HashSet<>(); for (ChunkData chunkData : md.getChunks()) { chunksToDownload.add(chunkData.getId()); } try { while (!chunksToDownload.isEmpty()) { PeerChunk pc = peerChunkSelector.getNext(md, chunksToDownload); if (pc == null || pc.getPeerURI() == null) { throw new IOException("No peer found or selected for download"); } Path chunkFile = Files.createTempFile("fs_", ".tmp"); try (OutputStream chunkOut = Files.newOutputStream(chunkFile, StandardOpenOption.APPEND)) { downloadShunk(pc, md, chunkOut); downloadedChunks.put(pc.getChunkId(), chunkFile); chunksToDownload.remove(pc.getChunkId()); chunkOut.flush(); } catch (Exception ex) { Files.deleteIfExists(chunkFile); throw ex; } } MessageDigest messageDigest = DigestUtils.getSha1Digest(); // Write chunk on correct order to file. try (DigestOutputStream dos = new DigestOutputStream(out, messageDigest); BufferedOutputStream bos = new BufferedOutputStream(dos, md.getChunkSize())) { for (ChunkData chunk : md.getChunks()) { Path chunkPath = downloadedChunks.get(chunk.getId()); Files.copy(chunkPath, bos); } } String sha1 = Hex.encodeHexString(messageDigest.digest()); if (!sha1.equalsIgnoreCase(md.getId())) { throw new IOException( "SHA1 validation of file failed. Expected " + md.getId() + " but was " + sha1); } } finally { for (Path path : downloadedChunks.values()) { try { Files.deleteIfExists(path); } catch (IOException ex) { LOG.error("Unable to delete chunk " + path.toString() + "; " + ex.getMessage(), ex); } } } }
From source file:com.aoppp.gatewaysdk.internal.hw.DigestUtils2.java
/** * Calculates the SHA-256 digest and returns the value as a hex string. * <p>// ww w . jav a2 s .c o m * Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0. * </p> * * @param data * Data to digest * @return SHA-256 digest as a hex string * @since 1.4 */ public static String sha256Hex(final byte[] data) { return Hex.encodeHexString(sha256(data)); }
From source file:eu.europa.ec.markt.dss.validation102853.pades.PAdESSignature.java
@Override public String getId() { try {/*from w ww.ja va 2 s . c o m*/ MessageDigest digest = MessageDigest.getInstance("MD5"); if (getSigningTime() != null) { digest.update(Long.toString(getSigningTime().getTime()).getBytes()); } digest.update(getSigningCertificate().getCertToken().getCertificate().getEncoded()); return Hex.encodeHexString(digest.digest()); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.aoppp.gatewaysdk.internal.hw.DigestUtils2.java
/** * Calculates the SHA-256 digest and returns the value as a hex string. * <p>/* ww w.ja va 2 s .c o m*/ * Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0. * </p> * * @param data * Data to digest * @return SHA-256 digest as a hex string * @throws IOException * On error reading from the stream * @since 1.4 */ public static String sha256Hex(final InputStream data) throws IOException { return Hex.encodeHexString(sha256(data)); }
From source file:us.camin.api.Server.java
private String genToken() { Random r = new Random(); int salt = r.nextInt(); MessageDigest crypt;/*ww w . ja v a 2s . co m*/ try { crypt = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { log.warning("Could not find SHA-1 algorithm"); return ""; } crypt.reset(); String token = m_name + salt + m_secret; crypt.update(token.getBytes()); token = m_name + "$" + salt + "$" + Hex.encodeHexString(crypt.digest()); log.info("Generated token " + token + " from " + m_name + salt + m_secret); return token; }