List of usage examples for javax.xml.crypto.dsig.keyinfo KeyInfoFactory newX509Data
public abstract X509Data newX509Data(List<?> content);
X509Data containing the specified list of X.509 content. From source file:com.bcmcgroup.flare.xmldsig.Xmldsig.java
/** * Method used to create an enveloped digital signature for an element of a TAXII document. * * @param element the element to be signed * @param keyEntry the PrivateKeyEntry//from w w w .j a va 2 s .c om * @param cbIndex the index of the Content_Block if we're signing a Content_Block, otherwise set to -1 if we're signing the root element * @return the status of the operation * * Usage Example: * String pks = config.getProperty("pathToPublisherKeyStore"); * String pksPw = FLAREclientUtil.decrypt(config.getProperty("publisherKeyStorePassword")); * String keyName = config.getProperty("publisherKeyName"); * String keyPW = FLAREclientUtil.decrypt(config.getProperty("publisherKeyPassword")); * PrivateKeyEntry keyEntry = FLAREclientUtil.getKeyEntry(pks, pksPw, keyName, keyPW); * List<Integer> statusList = Xmldsig.sign(rootElement, keyEntry, -1); */ private static boolean sign(Element element, PrivateKeyEntry keyEntry, int cbIndex) { element.normalize(); boolean status = false; //Create XML Signature Factory XMLSignatureFactory xmlSigFactory = XMLSignatureFactory.getInstance("DOM"); PublicKey publicKey = ClientUtil.getPublicKey(keyEntry); PrivateKey privateKey = keyEntry.getPrivateKey(); DOMSignContext dsc = new DOMSignContext(privateKey, element); dsc.setDefaultNamespacePrefix("ds"); dsc.setURIDereferencer(new MyURIDereferencer(element)); SignedInfo si = null; DigestMethod dm = null; SignatureMethod sm = null; KeyInfo ki = null; X509Data xd; List<Serializable> x509Content = new ArrayList<>(); try { String algorithm = publicKey.getAlgorithm(); X509Certificate cert = (X509Certificate) keyEntry.getCertificate(); x509Content.add(cert.getSubjectX500Principal().getName()); x509Content.add(cert); String algorithmName = cert.getSigAlgName(); if (algorithm.toUpperCase().contains("RSA")) { if (algorithmName.toUpperCase().contains("SHA1")) { dm = xmlSigFactory.newDigestMethod(DigestMethod.SHA1, null); sm = xmlSigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); } else if (algorithmName.toUpperCase().contains("SHA2")) { dm = xmlSigFactory.newDigestMethod(DigestMethod.SHA256, null); sm = xmlSigFactory.newSignatureMethod(RSA_SHA256_URI, null); } else { logger.error("Error in digital signature application. " + algorithmName + " is not supported."); } CanonicalizationMethod cm; if (cbIndex != -1) { cm = xmlSigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null); String refUri = "#xpointer(//*[local-name()='Content_Block'][" + cbIndex + "]/*[local-name()='Content'][1]/*)"; List<Reference> references = Collections.singletonList(xmlSigFactory.newReference(refUri, dm)); si = xmlSigFactory.newSignedInfo(cm, sm, references); } else { List<Transform> transforms = new ArrayList<>(2); transforms.add(xmlSigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); transforms.add(xmlSigFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null)); cm = xmlSigFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); String refUri = "#xpointer(/*)"; List<Reference> references = Collections .singletonList(xmlSigFactory.newReference(refUri, dm, transforms, null, null)); si = xmlSigFactory.newSignedInfo(cm, sm, references); } KeyInfoFactory kif = xmlSigFactory.getKeyInfoFactory(); xd = kif.newX509Data(x509Content); ki = kif.newKeyInfo(Collections.singletonList(xd)); } else { logger.error("Error in digital signature application. " + algorithmName + " is not supported."); } } catch (NoSuchAlgorithmException ex) { logger.error("NoSuchAlgorithm Exception when attempting to digitally sign a document."); } catch (InvalidAlgorithmParameterException ex) { logger.error("InvalidAlgorithmParameter Exception when attempting to digitally sign a document."); } // Create a new XML Signature XMLSignature signature = xmlSigFactory.newXMLSignature(si, ki); try { // Sign the document signature.sign(dsc); status = true; } catch (MarshalException ex) { logger.error("MarshalException when attempting to digitally sign a document."); } catch (XMLSignatureException ex) { logger.error("XMLSignature Exception when attempting to digitally sign a document."); } catch (Exception e) { logger.error("General exception when attempting to digitally sign a document."); } return status; }
From source file:Main.java
/** * Firma digitalmente usando la forma "enveloped signature" según el * estándar de la W3C (<a/*from w w w .java2 s . com*/ * href="http://www.w3.org/TR/xmldsig-core/">http://www.w3.org/TR/xmldsig-core/</a>). * <p> * * Este método además incorpora la información del * certificado a la sección <KeyInfo> opcional del * estándar, según lo exige SII. * <p> * * @param doc * El documento a firmar * @param uri * La referencia dentro del documento que debe ser firmada * @param pKey * La llave privada para firmar * @param cert * El certificado digital correspondiente a la llave privada * @throws NoSuchAlgorithmException * Si el algoritmo de firma de la llave no está soportado * (Actualmente soportado RSA+SHA1, DSA+SHA1 y HMAC+SHA1). * @throws InvalidAlgorithmParameterException * Si los algoritmos de canonización (parte del * estándar XML Signature) no son soportados (actaulmente * se usa el por defecto) * @throws KeyException * Si hay problemas al incluir la llave pública en el * <KeyValue>. * @throws MarshalException * @throws XMLSignatureException * * @see javax.xml.crypto.dsig.XMLSignature#sign(javax.xml.crypto.dsig.XMLSignContext) */ public static void signEmbeded(Node doc, String uri, PrivateKey pKey, X509Certificate cert) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException { // Create a DOM XMLSignatureFactory that will be used to generate the // enveloped signature XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); // Create a Reference to the enveloped document (in this case we are // signing the whole document, so a URI of "" signifies that) and // also specify the SHA1 digest algorithm and the ENVELOPED Transform. Reference ref = fac.newReference(uri, fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); // Create the SignedInfo String method = SignatureMethod.RSA_SHA1; // default by SII if ("DSA".equals(cert.getPublicKey().getAlgorithm())) method = SignatureMethod.DSA_SHA1; else if ("HMAC".equals(cert.getPublicKey().getAlgorithm())) method = SignatureMethod.HMAC_SHA1; SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, // Default canonical and // default by SII (C14NMethodParameterSpec) null), fac.newSignatureMethod(method, null), Collections.singletonList(ref)); KeyInfoFactory kif = fac.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(cert.getPublicKey()); // Create a KeyInfo and add the KeyValue to it List<XMLStructure> kidata = new ArrayList<XMLStructure>(); kidata.add(kv); kidata.add(kif.newX509Data(Collections.singletonList(cert))); KeyInfo ki = kif.newKeyInfo(kidata); // Create a DOMSignContext and specify the PrivateKey and // location of the resulting XMLSignature's parent element DOMSignContext dsc = new DOMSignContext(pKey, doc); // Create the XMLSignature (but don't sign it yet) XMLSignature signature = fac.newXMLSignature(si, ki); // Marshal, generate (and sign) the enveloped signature signature.sign(dsc); }
From source file:com.fujitsu.dc.common.auth.token.TransCellAccessToken.java
/** * X509??./*from ww w. j av a 2 s.c om*/ * @param privateKeyFileName ??? * @param certificateFileName ?? * @param rootCertificateFileNames ?? * @throws IOException IOException * @throws NoSuchAlgorithmException NoSuchAlgorithmException * @throws InvalidKeySpecException InvalidKeySpecException * @throws CertificateException CertificateException */ public static void configureX509(String privateKeyFileName, String certificateFileName, String[] rootCertificateFileNames) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException { xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM"); // Read RootCA Certificate x509RootCertificateFileNames = new ArrayList<String>(); if (rootCertificateFileNames != null) { for (String fileName : rootCertificateFileNames) { x509RootCertificateFileNames.add(fileName); } } // Read Private Key InputStream is = null; if (privateKeyFileName == null) { is = TransCellAccessToken.class.getClassLoader() .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_KEY_PATH); } else { is = new FileInputStream(privateKeyFileName); } PEMReader privateKeyPemReader = new PEMReader(is); byte[] privateKeyDerBytes = privateKeyPemReader.getDerBytes(); PKCS1EncodedKeySpec keySpecRSAPrivateKey = new PKCS1EncodedKeySpec(privateKeyDerBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); privKey = keyFactory.generatePrivate(keySpecRSAPrivateKey.getKeySpec()); // Read Certificate if (certificateFileName == null) { is = TransCellAccessToken.class.getClassLoader() .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_CRT_PATH); } else { is = new FileInputStream(certificateFileName); } PEMReader serverCertificatePemReader; serverCertificatePemReader = new PEMReader(is); byte[] serverCertificateBytesCert = serverCertificatePemReader.getDerBytes(); CertificateFactory cf = CertificateFactory.getInstance(X509KeySelector.X509KEY_TYPE); x509Certificate = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(serverCertificateBytesCert)); // Create the KeyInfo containing the X509Data KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory(); List x509Content = new ArrayList(); x509Content.add(x509Certificate.getSubjectX500Principal().getName()); x509Content.add(x509Certificate); X509Data xd = keyInfoFactory.newX509Data(x509Content); keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(xd)); // http://java.sun.com/developer/technicalArticles/xml/dig_signature_api/ }
From source file:io.personium.common.auth.token.TransCellAccessToken.java
/** * X509??./*w w w .ja v a 2 s.c o m*/ * @param privateKeyFileName ??? * @param certificateFileName ?? * @param rootCertificateFileNames ?? * @throws IOException IOException * @throws NoSuchAlgorithmException NoSuchAlgorithmException * @throws InvalidKeySpecException InvalidKeySpecException * @throws CertificateException CertificateException * @throws InvalidNameException InvalidNameException */ public static void configureX509(String privateKeyFileName, String certificateFileName, String[] rootCertificateFileNames) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException, InvalidNameException { xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM"); // Read RootCA Certificate x509RootCertificateFileNames = new ArrayList<String>(); if (rootCertificateFileNames != null) { for (String fileName : rootCertificateFileNames) { x509RootCertificateFileNames.add(fileName); } } // Read Private Key InputStream is = null; if (privateKeyFileName == null) { is = TransCellAccessToken.class.getClassLoader() .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_KEY_PATH); } else { is = new FileInputStream(privateKeyFileName); } PEMReader privateKeyPemReader = new PEMReader(is); byte[] privateKeyDerBytes = privateKeyPemReader.getDerBytes(); PKCS1EncodedKeySpec keySpecRSAPrivateKey = new PKCS1EncodedKeySpec(privateKeyDerBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); privKey = keyFactory.generatePrivate(keySpecRSAPrivateKey.getKeySpec()); // Read Certificate if (certificateFileName == null) { is = TransCellAccessToken.class.getClassLoader() .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_CRT_PATH); } else { is = new FileInputStream(certificateFileName); } PEMReader serverCertificatePemReader; serverCertificatePemReader = new PEMReader(is); byte[] serverCertificateBytesCert = serverCertificatePemReader.getDerBytes(); CertificateFactory cf = CertificateFactory.getInstance(X509KeySelector.X509KEY_TYPE); x509Certificate = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(serverCertificateBytesCert)); // Create the KeyInfo containing the X509Data KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory(); List x509Content = new ArrayList(); x509Content.add(x509Certificate.getSubjectX500Principal().getName()); x509Content.add(x509Certificate); X509Data xd = keyInfoFactory.newX509Data(x509Content); keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(xd)); // Get FQDN from Certificate and set FQDN to PersoniumCoreUtils String dn = x509Certificate.getSubjectX500Principal().getName(); LdapName ln = new LdapName(dn); for (Rdn rdn : ln.getRdns()) { if (rdn.getType().equalsIgnoreCase("CN")) { PersoniumCoreUtils.setFQDN(rdn.getValue().toString()); break; } } // http://java.sun.com/developer/technicalArticles/xml/dig_signature_api/ }
From source file:no.digipost.api.SdpMeldingSigner.java
public Document sign(final StandardBusinessDocument sbd) { try {/*w w w .j a va 2s. c om*/ PrivateKey privateKey = keystoreInfo.getPrivateKey(); X509Certificate certificate = keystoreInfo.getCertificate(); DOMResult result = new DOMResult(); Marshalling.marshal(marshaller, sbd, result); Document doc = (Document) result.getNode(); Marshalling.trimNamespaces(doc); XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA256, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); SignedInfo si = fac.newSignedInfo( fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(Constants.RSA_SHA256, null), Collections.singletonList(ref)); KeyInfoFactory kif = fac.getKeyInfoFactory(); X509Data xd = kif.newX509Data(Collections.singletonList(certificate)); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd)); XMLSignature signature = fac.newXMLSignature(si, ki); Node digitalPostNode = doc.getDocumentElement().getFirstChild().getNextSibling(); Node avsenderNode = digitalPostNode.getFirstChild(); DOMSignContext dsc = new DOMSignContext(privateKey, digitalPostNode, avsenderNode); signature.sign(dsc); doc.normalizeDocument(); return doc; } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnrecoverableKeyException e) { throw new RuntimeException(e); } catch (XMLSignatureException e) { throw new RuntimeException(e); } catch (InvalidAlgorithmParameterException e) { throw new RuntimeException(e); } catch (KeyStoreException e) { throw new RuntimeException(e); } catch (MarshalException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:no.difi.sdp.client.asice.signature.CreateSignature.java
private KeyInfo keyInfo(final XMLSignatureFactory xmlSignatureFactory, final Certificate[] sertifikater) { KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory(); X509Data x509Data = keyInfoFactory.newX509Data(asList(sertifikater)); return keyInfoFactory.newKeyInfo(singletonList(x509Data)); }
From source file:be.e_contract.mycarenet.xkms2.KeyBindingAuthenticationSignatureSOAPHandler.java
private void addSignature(Element parentElement) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException { DOMSignContext domSignContext = new DOMSignContext(this.authnPrivateKey, parentElement); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM"); Reference reference = xmlSignatureFactory.newReference(this.referenceUri, xmlSignatureFactory.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(xmlSignatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null)), null, null);/*from w w w. ja va2s . c o m*/ SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo( xmlSignatureFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), xmlSignatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference)); KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory(); KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections .singletonList(keyInfoFactory.newX509Data(Collections.singletonList(this.authnCertificate)))); XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo); xmlSignature.sign(domSignContext); }
From source file:be.fedict.eid.idp.common.saml2.Saml2Util.java
/** * Sign DOM document/*from ww w .j a va 2 s . c o m*/ * * @param documentElement * document to be signed * @param nextSibling * next sibling in document, dsig is added before this one * @param identity * Identity to sign with * @throws NoSuchAlgorithmException * signing algorithm not found * @throws InvalidAlgorithmParameterException * invalid signing algo param * @throws MarshalException * error marshalling signature * @throws XMLSignatureException * error during signing */ public static void signDocument(Element documentElement, Node nextSibling, KeyStore.PrivateKeyEntry identity) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException { // get document ID String documentId = documentElement.getAttribute("ID"); LOG.debug("document ID=" + documentId); // fix for recent versions of Apache xmlsec. documentElement.setIdAttribute("ID", true); XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM"); XMLSignContext signContext = new DOMSignContext(identity.getPrivateKey(), documentElement, nextSibling); signContext.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, "ds"); javax.xml.crypto.dsig.DigestMethod digestMethod = signatureFactory .newDigestMethod(javax.xml.crypto.dsig.DigestMethod.SHA1, null); List<javax.xml.crypto.dsig.Transform> transforms = new LinkedList<javax.xml.crypto.dsig.Transform>(); transforms.add(signatureFactory.newTransform(javax.xml.crypto.dsig.Transform.ENVELOPED, (TransformParameterSpec) null)); javax.xml.crypto.dsig.Transform exclusiveTransform = signatureFactory .newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null); transforms.add(exclusiveTransform); Reference reference = signatureFactory.newReference("#" + documentId, digestMethod, transforms, null, null); SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); CanonicalizationMethod canonicalizationMethod = signatureFactory .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference)); List<Object> keyInfoContent = new LinkedList<Object>(); KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance(); List<Object> x509DataObjects = new LinkedList<Object>(); for (X509Certificate certificate : Saml2Util.getCertificateChain(identity)) { x509DataObjects.add(certificate); } javax.xml.crypto.dsig.keyinfo.X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects); keyInfoContent.add(x509Data); javax.xml.crypto.dsig.keyinfo.KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent); javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, keyInfo); xmlSignature.sign(signContext); }
From source file:es.gob.afirma.signers.ooxml.be.fedict.eid.applet.service.signer.AbstractXmlSignatureService.java
@SuppressWarnings("unchecked") private byte[] getSignedXML(final String digestAlgo, final List<DigestInfo> digestInfos, final List<X509Certificate> signingCertificateChain, final PrivateKey signingKey) throws ParserConfigurationException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, javax.xml.crypto.dsig.XMLSignatureException, TransformerException, IOException, SAXException {//from w w w . j a va 2s. c om // DOM Document construction. Document document = getEnvelopingDocument(); if (null == document) { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); document = documentBuilderFactory.newDocumentBuilder().newDocument(); } final XMLSignContext xmlSignContext = new DOMSignContext(signingKey, document); final URIDereferencer uriDereferencer = getURIDereferencer(); if (null != uriDereferencer) { xmlSignContext.setURIDereferencer(uriDereferencer); } final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", //$NON-NLS-1$ new org.jcp.xml.dsig.internal.dom.XMLDSigRI()); // Add ds:References that come from signing client local files. final List<Reference> references = new LinkedList<Reference>(); addDigestInfosAsReferences(digestInfos, signatureFactory, references); // Invoke the signature facets. final String signatureId = "xmldsig-" + UUID.randomUUID().toString(); //$NON-NLS-1$ final List<XMLObject> objects = new LinkedList<XMLObject>(); for (final SignatureFacet signatureFacet : this.signatureFacets) { signatureFacet.preSign(signatureFactory, document, signatureId, signingCertificateChain, references, objects); } // ds:SignedInfo final SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(getSignatureMethod(digestAlgo), null); final SignedInfo signedInfo = signatureFactory.newSignedInfo(signatureFactory.newCanonicalizationMethod( getCanonicalizationMethod(), (C14NMethodParameterSpec) null), signatureMethod, references); // Creamos el KeyInfo final KeyInfoFactory kif = signatureFactory.getKeyInfoFactory(); final List<Object> x509Content = new ArrayList<Object>(); x509Content.add(signingCertificateChain.get(0)); final List<Object> content = new ArrayList<Object>(); try { content.add(kif.newKeyValue(signingCertificateChain.get(0).getPublicKey())); } catch (final Exception e) { Logger.getLogger("es.gob.afirma") //$NON-NLS-1$ .severe("Error creando el KeyInfo, la informacion puede resultar incompleta: " + e); //$NON-NLS-1$ } content.add(kif.newX509Data(x509Content)); // JSR105 ds:Signature creation final String signatureValueId = signatureId + "-signature-value"; //$NON-NLS-1$ final javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, kif.newKeyInfo(content), // KeyInfo objects, signatureId, signatureValueId); // ds:Signature Marshalling. final DOMXMLSignature domXmlSignature = (DOMXMLSignature) xmlSignature; Node documentNode = document.getDocumentElement(); if (null == documentNode) { documentNode = document; // In case of an empty DOM document. } final String dsPrefix = null; domXmlSignature.marshal(documentNode, dsPrefix, (DOMCryptoContext) xmlSignContext); // Completion of undigested ds:References in the ds:Manifests. for (final XMLObject object : objects) { final List<XMLStructure> objectContentList = object.getContent(); for (final XMLStructure objectContent : objectContentList) { if (!(objectContent instanceof Manifest)) { continue; } final Manifest manifest = (Manifest) objectContent; final List<Reference> manifestReferences = manifest.getReferences(); for (final Reference manifestReference : manifestReferences) { if (null != manifestReference.getDigestValue()) { continue; } final DOMReference manifestDOMReference = (DOMReference) manifestReference; manifestDOMReference.digest(xmlSignContext); } } } // Completion of undigested ds:References. final List<Reference> signedInfoReferences = signedInfo.getReferences(); for (final Reference signedInfoReference : signedInfoReferences) { final DOMReference domReference = (DOMReference) signedInfoReference; if (null != domReference.getDigestValue()) { // ds:Reference with external digest value continue; } domReference.digest(xmlSignContext); } // Calculation of signature final DOMSignedInfo domSignedInfo = (DOMSignedInfo) signedInfo; final ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); domSignedInfo.canonicalize(xmlSignContext, dataStream); final byte[] octets = dataStream.toByteArray(); final Signature sig = Signature.getInstance(digestAlgo.replace("-", "") + "withRSA"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ final byte[] sigBytes; try { sig.initSign(signingKey); sig.update(octets); sigBytes = sig.sign(); } catch (final Exception e) { throw new javax.xml.crypto.dsig.XMLSignatureException( "Error en la firma PKCS#1 ('" + digestAlgo + "withRSA): " + e); //$NON-NLS-1$ //$NON-NLS-2$ } // Sacamos el pre-XML a un OutputStream final ByteArrayOutputStream baos = new ByteArrayOutputStream(); writeDocument(document, baos); // Ya tenemos el XML, con la firma vacia y el SignatureValue, cada uno // por su lado... return postSign(baos.toByteArray(), signingCertificateChain, signatureId, sigBytes); }
From source file:com.vmware.identity.saml.impl.TokenAuthorityImpl.java
/** * Create KeyInfo section representation. * * @return KeyInfo/* www . j ava 2 s . c o m*/ */ private KeyInfo createKeyInfo(SignInfo signInfo) { List<? extends Certificate> stsCertificates = signInfo.getCertificationPath().getCertificates(); XMLSignatureFactory factory = XMLSignatureFactory.getInstance(); KeyInfoFactory keyInfoFactory = factory.getKeyInfoFactory(); X509Data certificatesData = keyInfoFactory.newX509Data(stsCertificates); log.debug("Created KeyInfo section from certificates: {}", stsCertificates); return keyInfoFactory.newKeyInfo(Collections.singletonList(certificatesData)); }