List of usage examples for javax.xml.crypto.dsig XMLSignatureFactory newSignedInfo
public abstract SignedInfo newSignedInfo(CanonicalizationMethod cm, SignatureMethod sm, List<? extends Reference> references);
SignedInfo
with the specified canonicalization and signature methods, and list of one or more references. From source file:Main.java
public static void main(String[] args) throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA"); kpg.initialize(1024, new SecureRandom()); KeyPair dsaKeyPair = kpg.generateKeyPair(); XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance(); Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null)); SignedInfo signedInfo = sigFactory.newSignedInfo( sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref)); KeyInfoFactory kif = sigFactory.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(dsaKeyPair.getPublic()); KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv)); XMLSignature xmlSig = sigFactory.newXMLSignature(signedInfo, keyInfo); }
From source file:MainClass.java
public static void main(String[] args) throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA"); kpg.initialize(1024, new SecureRandom()); KeyPair dsaKeyPair = kpg.generateKeyPair(); XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance(); Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null)); SignedInfo signedInfo = sigFactory.newSignedInfo( sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref)); KeyInfoFactory kif = sigFactory.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(dsaKeyPair.getPublic()); KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv)); XMLSignature xmlSig = sigFactory.newXMLSignature(signedInfo, keyInfo); }
From source file:Signing.java
public static void main(String[] args) throws Exception { SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPHeader soapHeader = soapEnvelope.getHeader(); SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12")); SOAPBody soapBody = soapEnvelope.getBody(); soapBody.addAttribute(/*from w w w . ja v a 2 s.c o m*/ soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"), "Body"); Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com"); SOAPBodyElement gltp = soapBody.addBodyElement(bodyName); Source source = soapPart.getContent(); Node root = null; if (source instanceof DOMSource) { root = ((DOMSource) source).getNode(); } else if (source instanceof SAXSource) { InputSource inSource = ((SAXSource) source).getInputSource(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = null; db = dbf.newDocumentBuilder(); Document doc = db.parse(inSource); root = (Node) doc.getDocumentElement(); } dumpDocument(root); KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA"); kpg.initialize(1024, new SecureRandom()); KeyPair keypair = kpg.generateKeyPair(); XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance(); Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null)); SignedInfo signedInfo = sigFactory.newSignedInfo( sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref)); KeyInfoFactory kif = sigFactory.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(keypair.getPublic()); KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv)); XMLSignature sig = sigFactory.newXMLSignature(signedInfo, keyInfo); System.out.println("Signing the message..."); PrivateKey privateKey = keypair.getPrivate(); Element envelope = getFirstChildElement(root); Element header = getFirstChildElement(envelope); DOMSignContext sigContext = new DOMSignContext(privateKey, header); sigContext.putNamespacePrefix(XMLSignature.XMLNS, "ds"); sigContext.setIdAttributeNS(getNextSiblingElement(header), "http://schemas.xmlsoap.org/soap/security/2000-12", "id"); sig.sign(sigContext); dumpDocument(root); System.out.println("Validate the signature..."); Element sigElement = getFirstChildElement(header); DOMValidateContext valContext = new DOMValidateContext(keypair.getPublic(), sigElement); valContext.setIdAttributeNS(getNextSiblingElement(header), "http://schemas.xmlsoap.org/soap/security/2000-12", "id"); boolean valid = sig.validate(valContext); System.out.println("Signature valid? " + valid); }
From source file:Main.java
public static void signEmbeded(Node doc, String uri, PrivateKey privKey, PublicKey pubKey) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, KeyException, MarshalException, XMLSignatureException {//from ww w. ja va 2 s. c o m 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 ww w . j a va 2 s .co m*/ * 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 {// w ww . j a va 2s . 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);//from w w w .ja va 2 s. c om 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. j a v a 2 s .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.difi.sdp.client.asice.signature.CreateSignature.java
public Signature createSignature(final Noekkelpar noekkelpar, final List<AsicEAttachable> attachedFiles) throws XmlValideringException { XMLSignatureFactory xmlSignatureFactory = getSignatureFactory(); SignatureMethod signatureMethod = getSignatureMethod(xmlSignatureFactory); // Lag signatur-referanse for alle filer List<Reference> references = references(xmlSignatureFactory, attachedFiles); // Lag signatur-referanse for XaDES properties references.add(xmlSignatureFactory.newReference("#SignedProperties", sha256DigestMethod, singletonList(canonicalXmlTransform), signedPropertiesType, null)); // Generer XAdES-dokument som skal signeres, informasjon om nkkel brukt til signering og informasjon om hva som er signert Document document = createXAdESProperties.createPropertiesToSign(attachedFiles, noekkelpar.getSertifikat()); KeyInfo keyInfo = keyInfo(xmlSignatureFactory, noekkelpar.getCertificateChain()); SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, references);//w ww. ja v a 2 s . c om // Definer signatur over XAdES-dokument XMLObject xmlObject = xmlSignatureFactory .newXMLObject(singletonList(new DOMStructure(document.getDocumentElement())), null, null, null); XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo, singletonList(xmlObject), "Signature", null); try { xmlSignature.sign(new DOMSignContext(noekkelpar.getPrivateKey(), document)); } catch (MarshalException e) { throw new XmlKonfigurasjonException("Klarte ikke lese ASiC-E XML for signering", e); } catch (XMLSignatureException e) { throw new XmlKonfigurasjonException("Klarte ikke signere ASiC-E element.", e); } // Pakk Signatur inn i XAdES-konvolutt wrapSignatureInXADeSEnvelope(document); ByteArrayOutputStream outputStream; try { outputStream = new ByteArrayOutputStream(); Transformer transformer = transformerFactory.newTransformer(); schema.newValidator().validate(new DOMSource(document)); transformer.transform(new DOMSource(document), new StreamResult(outputStream)); } catch (TransformerException e) { throw new KonfigurasjonException("Klarte ikke serialisere XML", e); } catch (SAXException e) { throw new XmlValideringException( "Kunne ikke validere generert signatures.xml. Sjekk at input er gyldig og at det ikke er ugyldige tegn i filnavn o.l.", KLIENT, e); } catch (IOException e) { throw new RuntimeIOException(e); } return new Signature(outputStream.toByteArray()); }
From source file:no.digipost.signature.client.asice.signature.CreateSignature.java
public Signature createSignature(final List<ASiCEAttachable> attachedFiles, final KeyStoreConfig keyStoreConfig) { XMLSignatureFactory xmlSignatureFactory = getSignatureFactory(); SignatureMethod signatureMethod = getSignatureMethod(xmlSignatureFactory); // Create signature references for all files List<Reference> references = references(xmlSignatureFactory, attachedFiles); // Create signature reference for XAdES properties references.add(xmlSignatureFactory.newReference("#SignedProperties", sha256DigestMethod, singletonList(canonicalXmlTransform), signedPropertiesType, null)); // Generate XAdES document to sign, information about the key used for signing and information about what's signed Document document = createXAdESProperties.createPropertiesToSign(attachedFiles, keyStoreConfig.getCertificate()); KeyInfo keyInfo = keyInfo(xmlSignatureFactory, keyStoreConfig.getCertificateChain()); SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, references);/*from w w w.j a v a 2 s .c o m*/ // Define signature over XAdES document XMLObject xmlObject = xmlSignatureFactory .newXMLObject(singletonList(new DOMStructure(document.getDocumentElement())), null, null, null); XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo, singletonList(xmlObject), "Signature", null); try { xmlSignature.sign(new DOMSignContext(keyStoreConfig.getPrivateKey(), document)); } catch (MarshalException e) { throw new XmlConfigurationException("failed to read ASiC-E XML for signing", e); } catch (XMLSignatureException e) { throw new XmlConfigurationException("Failed to sign ASiC-E element.", e); } wrapSignatureInXADeSEnvelope(document); ByteArrayOutputStream outputStream; try { outputStream = new ByteArrayOutputStream(); Transformer transformer = transformerFactory.newTransformer(); schema.newValidator().validate(new DOMSource(document)); transformer.transform(new DOMSource(document), new StreamResult(outputStream)); } catch (TransformerException e) { throw new ConfigurationException("Unable to serialize XML.", e); } catch (SAXException e) { throw new XmlValidationException( "Failed to validate generated signature.xml. Verify that the input is valid and that there are no illegal symbols in file names etc.", e); } catch (IOException e) { throw new RuntimeIOException(e); } return new Signature(outputStream.toByteArray()); }