List of usage examples for javax.xml.crypto.dsig XMLSignatureFactory newTransform
public abstract Transform newTransform(String algorithm, XMLStructure params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException;
Transform
for the specified algorithm URI and parameters. From source file:Main.java
public static void signEmbeded(Node doc, String uri, PrivateKey privKey, PublicKey pubKey) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, KeyException, MarshalException, XMLSignatureException {//from w ww . j a v a 2 s .c om XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); 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 if ("DSA".equals(privKey.getAlgorithm())) method = SignatureMethod.DSA_SHA1; SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, // Default canonical (C14NMethodParameterSpec) null), fac.newSignatureMethod(method, null), Collections.singletonList(ref)); KeyInfoFactory kif = fac.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(pubKey); // Create a KeyInfo and add the KeyValue to it List<XMLStructure> kidata = new ArrayList<XMLStructure>(); kidata.add(kv); 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(privKey, 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:Main.java
/** * Firma digitalmente usando la forma "enveloped signature" según el * estándar de la W3C (<a//from w ww . jav a2s . c om * 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:no.digipost.api.SdpMeldingSigner.java
public Document sign(final StandardBusinessDocument sbd) { try {/* ww w.java 2 s . co m*/ 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:be.e_contract.mycarenet.xkms.ProofOfPossessionSignatureSOAPHandler.java
private void addSignature(Element parentElement) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException { DOMSignContext domSignContext = new DOMSignContext(this.sessionKey.getPrivate(), parentElement); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM"); Reference reference = xmlSignatureFactory.newReference("#" + this.prototypeKeyBindingId, xmlSignatureFactory.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(xmlSignatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null)), null, null);/* w ww . jav a 2s. c o m*/ SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo( xmlSignatureFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), xmlSignatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference)); XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, null); xmlSignature.sign(domSignContext); }
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);/* 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:no.digipost.signature.client.asice.signature.CreateSignature.java
public CreateSignature() { createXAdESProperties = new CreateXAdESProperties(); transformerFactory = TransformerFactory.newInstance(); try {/* ww w. java2 s . c om*/ XMLSignatureFactory xmlSignatureFactory = getSignatureFactory(); sha256DigestMethod = xmlSignatureFactory.newDigestMethod(DigestMethod.SHA256, null); canonicalizationMethod = xmlSignatureFactory.newCanonicalizationMethod(C14V1, (C14NMethodParameterSpec) null); canonicalXmlTransform = xmlSignatureFactory.newTransform(C14V1, (TransformParameterSpec) null); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) { throw new ConfigurationException("Failed to initialize XML-signing", e); } schema = loadSchema(); }
From source file:no.difi.sdp.client.asice.signature.CreateSignature.java
public CreateSignature() { createXAdESProperties = new CreateXAdESProperties(); transformerFactory = TransformerFactory.newInstance(); try {//from w w w .j a v a 2s. c om XMLSignatureFactory xmlSignatureFactory = getSignatureFactory(); sha256DigestMethod = xmlSignatureFactory.newDigestMethod(DigestMethod.SHA256, null); canonicalizationMethod = xmlSignatureFactory.newCanonicalizationMethod(Constants.C14V1, (C14NMethodParameterSpec) null); canonicalXmlTransform = xmlSignatureFactory.newTransform(Constants.C14V1, (TransformParameterSpec) null); } catch (NoSuchAlgorithmException e) { throw new KonfigurasjonException("Kunne ikke initialisere xml-signering", e); } catch (InvalidAlgorithmParameterException e) { throw new KonfigurasjonException("Kunne ikke initialisere xml-signering", e); } schema = loadSchema(); }
From source file:be.fedict.eid.idp.common.saml2.Saml2Util.java
/** * Sign DOM document//from w w w. jav a2 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:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java
private static Reference createReference(Document document, DigestMethod digestMethod, XMLSignatureFactory sigFac, Integer index) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { String path, fragment;/* w ww. j av a 2 s . c o m*/ if (MimeType.XML.equals(document.getMimeType()) && document.getName() != null && document.getName().contains("#")) { path = document.getName().substring(0, document.getName().indexOf("#")); try { fragment = new URI(document.getName()).getFragment(); } catch (URISyntaxException e) { throw new IllegalArgumentException(e.getMessage()); } } else { path = document.getName(); fragment = null; } List<Transform> transforms; if (MimeType.XML.equals(document.getMimeType())) { transforms = new ArrayList<Transform>(); // Convert a # (fragment) within document name to element-id based Reference if (fragment != null) { // FIXME: this xpath should not be hardcoded String xpath = "ancestor-or-self::*[@ID=" + Utils.xPathLiteral(fragment) + "]"; transforms .add(sigFac.newTransform(Transforms.TRANSFORM_XPATH, new XPathFilterParameterSpec(xpath))); } // Canonicalize transforms.add(sigFac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null)); } else { transforms = null; } return sigFac.newReference(path, digestMethod, transforms, null, index != null ? "ref-" + index : null); }
From source file:com.vmware.identity.saml.impl.TokenAuthorityImpl.java
/** * Creates a list of transform part of Reference section in Signature * * @return//from w w w.j a v a 2s .c o m * @throws NoSuchAlgorithmException * @throws InvalidAlgorithmParameterException */ private List<Transform> createTransforms() { XMLSignatureFactory factory = XMLSignatureFactory.getInstance(); List<Transform> transforms = new ArrayList<Transform>(2); List<String> prefixList = new ArrayList<String>(2); prefixList.add(XMLConstants.XSD_PREFIX); prefixList.add(XMLConstants.XSI_PREFIX); try { transforms.add(factory.newTransform(CanonicalizationMethod.ENVELOPED, (TransformParameterSpec) null)); transforms.add( factory.newTransform(CanonicalizationMethod.EXCLUSIVE, new ExcC14NParameterSpec(prefixList))); } catch (Exception e) { throw new IllegalStateException("Cannot create enveloped or exclusive transform objects.", e); } log.debug("Created transforms: {} and {}", CanonicalizationMethod.ENVELOPED, CanonicalizationMethod.EXCLUSIVE); return transforms; }