List of usage examples for javax.xml.crypto.dsig XMLSignatureFactory newReference
public abstract Reference newReference(String uri, DigestMethod dm);
Reference
with the specified URI and digest method. 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 ww 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: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 ww.j a va2s. c o m*/ * @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:be.fedict.eid.applet.service.signer.odf.OpenOfficeSignatureFacet.java
public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { LOG.debug("pre sign"); Element dateElement = document.createElementNS("", "dc:date"); dateElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:dc", "http://purl.org/dc/elements/1.1/"); DateTime dateTime = new DateTime(DateTimeZone.UTC); DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis(); String now = fmt.print(dateTime); now = now.substring(0, now.indexOf("Z")); LOG.debug("now: " + now); dateElement.setTextContent(now);/*from ww w . ja va 2s . c om*/ String signaturePropertyId = "sign-prop-" + UUID.randomUUID().toString(); List<XMLStructure> signaturePropertyContent = new LinkedList<XMLStructure>(); signaturePropertyContent.add(new DOMStructure(dateElement)); SignatureProperty signatureProperty = signatureFactory.newSignatureProperty(signaturePropertyContent, "#" + signatureId, signaturePropertyId); List<XMLStructure> objectContent = new LinkedList<XMLStructure>(); List<SignatureProperty> signaturePropertiesContent = new LinkedList<SignatureProperty>(); signaturePropertiesContent.add(signatureProperty); SignatureProperties signatureProperties = signatureFactory .newSignatureProperties(signaturePropertiesContent, null); objectContent.add(signatureProperties); objects.add(signatureFactory.newXMLObject(objectContent, null, null, null)); DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null); Reference reference = signatureFactory.newReference("#" + signaturePropertyId, digestMethod); references.add(reference); }
From source file:be.fedict.eid.applet.service.signer.ooxml.OOXMLSignatureFacet.java
private void addManifestReferences(XMLSignatureFactory signatureFactory, Document document, List<Reference> manifestReferences) throws IOException, JAXBException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { CTTypes contentTypes = getContentTypes(); List<String> relsEntryNames = getRelsEntryNames(); DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null); Set<String> digestedPartNames = new HashSet<String>(); for (String relsEntryName : relsEntryNames) { CTRelationships relationships = getRelationships(relsEntryName); List<CTRelationship> relationshipList = relationships.getRelationship(); RelationshipTransformParameterSpec parameterSpec = new RelationshipTransformParameterSpec(); for (CTRelationship relationship : relationshipList) { String relationshipType = relationship.getType(); STTargetMode targetMode = relationship.getTargetMode(); if (null != targetMode) { LOG.debug("TargetMode: " + targetMode.name()); if (targetMode == STTargetMode.EXTERNAL) { /*/*from ww w .j ava 2 s . c om*/ * ECMA-376 Part 2 - 3rd edition * * 13.2.4.16 Manifest Element * * "The producer shall not create a Manifest element that references any data outside of the package." */ continue; } } if (false == OOXMLSignatureFacet.isSignedRelationship(relationshipType)) { continue; } String baseUri = "/" + relsEntryName.substring(0, relsEntryName.indexOf("_rels/")); String relationshipTarget = relationship.getTarget(); String partName = FilenameUtils .separatorsToUnix(FilenameUtils.normalize(baseUri + relationshipTarget)); LOG.debug("part name: " + partName); String relationshipId = relationship.getId(); parameterSpec.addRelationshipReference(relationshipId); String contentType = getContentType(contentTypes, partName); if (relationshipType.endsWith("customXml")) { if (false == contentType.equals("inkml+xml") && false == contentType.equals("text/xml")) { LOG.debug("skipping customXml with content type: " + contentType); continue; } } if (false == digestedPartNames.contains(partName)) { /* * We only digest a part once. */ Reference reference = signatureFactory.newReference(partName + "?ContentType=" + contentType, digestMethod); manifestReferences.add(reference); digestedPartNames.add(partName); } } if (false == parameterSpec.getSourceIds().isEmpty()) { List<Transform> transforms = new LinkedList<Transform>(); transforms.add( signatureFactory.newTransform(RelationshipTransformService.TRANSFORM_URI, parameterSpec)); transforms.add(signatureFactory.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null)); Reference reference = signatureFactory.newReference( "/" + relsEntryName + "?ContentType=application/vnd.openxmlformats-package.relationships+xml", digestMethod, transforms, null, null); manifestReferences.add(reference); } } }
From source file:org.roda.common.certification.ODFSignatureUtils.java
private static void digitalSign(XMLSignatureFactory factory, List<Reference> referenceList, DigestMethod digestMethod, X509Certificate certificate, Document docSignatures, Element rootSignatures, Key key) throws MarshalException, XMLSignatureException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { String signatureId = UUID.randomUUID().toString(); String signaturePropertyId = UUID.randomUUID().toString(); CanonicalizationMethod canMethod = factory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null); SignatureMethod signMethod = factory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); Reference signaturePropertyReference = factory.newReference("#" + signaturePropertyId, digestMethod); referenceList.add(signaturePropertyReference); SignedInfo si = factory.newSignedInfo(canMethod, signMethod, referenceList); KeyInfo ki = getKeyInfo(factory, certificate); List<XMLObject> objectList = getXMLObjectList(factory, docSignatures, signatureId, signaturePropertyId); XMLSignature signature = factory.newXMLSignature(si, ki, objectList, signatureId, null); DOMSignContext signContext = new DOMSignContext(key, rootSignatures); signature.sign(signContext);//from w ww. j av a 2 s.c o m }
From source file:org.roda.core.plugins.plugins.characterization.ODFSignatureUtils.java
private static void digitalSign(XMLSignatureFactory factory, List<Reference> referenceList, DigestMethod digestMethod, X509Certificate certificate, Document docSignatures, Element rootSignatures, Key key) throws MarshalException, XMLSignatureException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { String signatureId = IdUtils.createUUID(); String signaturePropertyId = IdUtils.createUUID(); CanonicalizationMethod canMethod = factory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null); SignatureMethod signMethod = factory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); Reference signaturePropertyReference = factory.newReference("#" + signaturePropertyId, digestMethod); referenceList.add(signaturePropertyReference); SignedInfo si = factory.newSignedInfo(canMethod, signMethod, referenceList); KeyInfo ki = getKeyInfo(factory, certificate); List<XMLObject> objectList = getXMLObjectList(factory, docSignatures, signatureId, signaturePropertyId); XMLSignature signature = factory.newXMLSignature(si, ki, objectList, signatureId, null); DOMSignContext signContext = new DOMSignContext(key, rootSignatures); signature.sign(signContext);/* w w w . ja v a 2 s . c om*/ }
From source file:org.warlock.itk.distributionenvelope.Payload.java
/** * Sign the payloadBody as-is. Note that this is going to be encrypted anyway * so we avoid any incompatibilities due to canonicalisation, and we don't * care if the payloadBody is text, compressed and so on. Re-writes payloadBody * with a serialised XML Digital Signature "Signature" element containing an * enveloping signature, or throws an exception to signal failure. * /* w w w.ja v a2s .c om*/ * @param pk * @param cert * @throws Exception */ private void signPayload(PrivateKey pk, X509Certificate cert) throws Exception { if ((pk == null) || (cert == null)) { throw new Exception("Null signing material"); } cert.checkValidity(); XMLSignatureFactory xsf = XMLSignatureFactory.getInstance("DOM"); Reference ref = null; String objectRef = "uuid" + UUID.randomUUID().toString(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document doc = null; DOMStructure payloadContent = null; if (compressed || base64 || !mimeType.contains("xml")) { ref = xsf.newReference("#" + objectRef, xsf.newDigestMethod(DigestMethod.SHA1, null)); doc = dbf.newDocumentBuilder().newDocument(); payloadContent = new DOMStructure(doc.createTextNode(payloadBody)); } else { Transform t = xsf.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", (TransformParameterSpec) null); ref = xsf.newReference("#" + objectRef, xsf.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(t), null, null); doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(payloadBody))); payloadContent = new DOMStructure(doc.getDocumentElement()); } XMLObject payloadObject = xsf.newXMLObject(Collections.singletonList(payloadContent), objectRef, null, null); SignedInfo si = xsf.newSignedInfo( xsf.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), xsf.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref)); KeyInfoFactory kif = xsf.getKeyInfoFactory(); ArrayList<Object> x509content = new ArrayList<Object>(); x509content.add(cert); X509Data xd = kif.newX509Data(x509content); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd)); XMLSignature signature = xsf.newXMLSignature(si, ki, Collections.singletonList(payloadObject), null, null); DOMSignContext dsc = new DOMSignContext(pk, doc); signature.sign(dsc); StringWriter sw = new StringWriter(); StreamResult sr = new StreamResult(sw); Transformer tx = TransformerFactory.newInstance().newTransformer(); tx.transform(new DOMSource(doc), sr); if (sw.toString().indexOf("<?xml ") == 0) { payloadBody = sw.toString().substring(sw.toString().indexOf("?>") + "?>".length()); } else { payloadBody = sw.toString(); } }
From source file:test.be.fedict.eid.dss.DigitalSignatureServiceTest.java
private void signDocument(Document document) throws IOException, PKCS11Exception, InterruptedException, NoSuchFieldException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableEntryException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, CardException { Messages messages = new Messages(Locale.getDefault()); PcscEid pcscEid = new PcscEid(new TestView(), messages); if (false == pcscEid.isEidPresent()) { LOG.debug("insert eID..."); pcscEid.waitForEidPresent();//from w w w.j av a 2 s . c o m } // PrivateKeyEntry privateKeyEntry = pcscEid.getPrivateKeyEntry(); PrivateKeyEntry privateKeyEntry = null; // TODO: refactor once Commons eID has been released. XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM"); XMLSignContext signContext = new DOMSignContext(privateKeyEntry.getPrivateKey(), document.getDocumentElement()); signContext.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, "ds"); DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null); Reference reference = signatureFactory.newReference("#id", digestMethod); SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod( CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null); SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference)); KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance(); List<Object> x509DataObjects = new LinkedList<Object>(); X509Certificate signingCertificate = (X509Certificate) privateKeyEntry.getCertificate(); x509DataObjects.add(signingCertificate); X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects); List<Object> keyInfoContent = new LinkedList<Object>(); keyInfoContent.add(x509Data); KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent); javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, keyInfo); xmlSignature.sign(signContext); pcscEid.close(); }