private void addDigestInfosAsReferences(List<DigestInfo> digestInfos, XMLSignatureFactory signatureFactory, List<Reference> references) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MalformedURLException { if (null == digestInfos) { return; } for (DigestInfo digestInfo : digestInfos) { byte[] documentDigestValue = digestInfo.digestValue; DigestMethod digestMethod = signatureFactory.newDigestMethod(getXmlDigestAlgo(digestInfo.digestAlgo), null); String uri = FilenameUtils.getName(new File(digestInfo.description).toURI().toURL().getFile()); Reference reference = signatureFactory.newReference(uri, digestMethod, null, null, null, documentDigestValue); references.add(reference); } }
/** * Verification via the default JSR105 implementation triggers some * canonicalization errors. * * @param odfUrl * @param signatureNode * @throws MarshalException * @throws XMLSignatureException */ private boolean verifySignature(URL odfUrl, Node signatureNode) throws MarshalException, XMLSignatureException { // work-around for Java 7 Element signedPropertiesElement = (Element) ((Element) signatureNode) .getElementsByTagNameNS(XAdESXLSignatureFacet.XADES_NAMESPACE, "SignedProperties").item(0); if (null != signedPropertiesElement) { signedPropertiesElement.setIdAttribute("Id", true); } DOMValidateContext domValidateContext = new DOMValidateContext(new KeyInfoKeySelector(), signatureNode); ODFURIDereferencer dereferencer = new ODFURIDereferencer(odfUrl); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); LOG.debug("java version: " + System.getProperty("java.version")); /* * Requires Java 6u10 because of a bug. See also: * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6696582 */ XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validity = xmlSignature.validate(domValidateContext); return validity; }
@SuppressWarnings("unchecked") public static XMLSignatureFactory getInstance() { if (instance == null) { registerTransform(); Provider p = new XMLDSigRI() { { final Map map = new HashMap(); // map.put("XMLSignatureFactory.DOM", DOMXMLSignatureFactory.class.getName()); map.put("TransformService." + STRTransform.implementedTransformURI, DOMSTRTransform.class.getName()); map.put("Alg.Alias.TransformService.STRTRANSFORM", STRTransform.implementedTransformURI); map.put("TransformService." + STRTransform.implementedTransformURI + " MechanismType", "DOM"); putAll(map); } }; try { instance = XMLSignatureFactory.getInstance("DOM", p); } catch (Exception e) { throw new RuntimeException(e); } } return instance; }
public Assinador useKeystore(KeyStore keyStore, String keyAlias, String privateKeyPass) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, KeyException { this.privateKey = (PrivateKey) keyStore.getKey(keyAlias, privateKeyPass.toCharArray()); this.cert = (X509Certificate) keyStore.getCertificate(keyAlias); // Retrieve signing key // PrivateKey privateKey = (PrivateKey) keyStore.getKey(KEY_ALIAS, // PRIVATE_KEY_PASS.toCharArray()); // // X509Certificate cert = (X509Certificate) // keyStore.getCertificate(KEY_ALIAS); try { String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI"); sigFactory = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance()); } catch (Throwable e) { throw new RuntimeException( "Error while loading XMLSignatureFactory (using 'jsr105Provider=org.jcp.xml.dsig.internal.dom.XMLDSigRI')", e); } PublicKey publicKey = cert.getPublicKey(); // Create a KeyValue containing the RSA PublicKey this.keyInfoFactory = sigFactory.getKeyInfoFactory(); this.keyValue = keyInfoFactory.newKeyValue(publicKey); return this; }
private SignedInfo initSignedInfo(XMLSignatureFactory fac) throws Exception { Reference ref = initReference(fac); String cm = null; cm = map.getProperty(CANONICALIZATIONMETHOD); String sigmethod = null; sigmethod = map.getProperty(SIGNATURE_METHOD); if (sigmethod == null) { sigmethod = SignatureMethod.RSA_SHA1; } if (cm == null) { cm = CanonicalizationMethod.EXCLUSIVE; } SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod( cm, (C14NMethodParameterSpec) null), fac.newSignatureMethod(sigmethod, null), Collections.singletonList(ref)); return si; }
public boolean isValid() throws Exception { NodeList nodes = xmlDoc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (nodes == null || nodes.getLength() == 0) { throw new Exception("Can't find signature in document."); } if (setIdAttributeExists()) { tagIdAttributes(xmlDoc); } X509Certificate cert = samlSettings.getCertificate(); DOMValidateContext ctx = new DOMValidateContext(cert.getPublicKey(), nodes.item(0)); XMLSignatureFactory sigF = XMLSignatureFactory.getInstance("DOM"); XMLSignature xmlSignature = sigF.unmarshalXMLSignature(ctx); return xmlSignature.validate(ctx); }
public XmlSignatureHandler() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { this.builderFactory = DocumentBuilderFactory.newInstance(); this.builderFactory.setNamespaceAware(true); this.transformerFactory = TransformerFactory.newInstance(); this.signatureFactory = XMLSignatureFactory.getInstance("DOM"); this.digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null); this.transformList = new ArrayList<Transform>(2); this.transformList.add( signatureFactory.newTransform( Transform.ENVELOPED, (TransformParameterSpec) null)); this.transformList.add( signatureFactory.newTransform( "http://www.w3.org/TR/2001/REC-xml-c14n-20010315", (TransformParameterSpec) null)); this.canonicalizationMethod = this.signatureFactory.newCanonicalizationMethod( CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null); this.signatureMethod = this.signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); this.keyInfoFactory = this.signatureFactory.getKeyInfoFactory(); }
/** * Sign SAML element. * * @param element the element * @param privKey the priv key * @param pubKey the pub key * @return the element */ private static org.jdom.Element signSamlElement(final org.jdom.Element element, final PrivateKey privKey, final PublicKey pubKey) { try { final String providerName = System.getProperty("jsr105Provider", SIGNATURE_FACTORY_PROVIDER_CLASS); final XMLSignatureFactory sigFactory = XMLSignatureFactory .getInstance("DOM", (Provider) Class.forName(providerName).newInstance()); final List<Transform> envelopedTransform = Collections.singletonList(sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); final Reference ref = sigFactory.newReference(StringUtils.EMPTY, sigFactory .newDigestMethod(DigestMethod.SHA1, null), envelopedTransform, null, null); // Create the SignatureMethod based on the type of key final SignatureMethod signatureMethod; final String algorithm = pubKey.getAlgorithm(); switch (algorithm) { case "DSA": signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null); break; case "RSA": signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); break; default: throw new RuntimeException("Error signing SAML element: Unsupported type of key"); } final CanonicalizationMethod canonicalizationMethod = sigFactory .newCanonicalizationMethod( CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null); // Create the SignedInfo final SignedInfo signedInfo = sigFactory.newSignedInfo( canonicalizationMethod, signatureMethod, Collections.singletonList(ref)); // Create a KeyValue containing the DSA or RSA PublicKey final KeyInfoFactory keyInfoFactory = sigFactory.getKeyInfoFactory(); final KeyValue keyValuePair = keyInfoFactory.newKeyValue(pubKey); // Create a KeyInfo and add the KeyValue to it final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyValuePair)); // Convert the JDOM document to w3c (Java XML signature API requires w3c representation) final Element w3cElement = toDom(element); // Create a DOMSignContext and specify the DSA/RSA PrivateKey and // location of the resulting XMLSignature's parent element final DOMSignContext dsc = new DOMSignContext(privKey, w3cElement); final Node xmlSigInsertionPoint = getXmlSignatureInsertLocation(w3cElement); dsc.setNextSibling(xmlSigInsertionPoint); // Marshal, generate (and sign) the enveloped signature final XMLSignature signature = sigFactory.newXMLSignature(signedInfo, keyInfo); signature.sign(dsc); return toJdom(w3cElement); } catch (final Exception e) { throw new RuntimeException("Error signing SAML element: " + e.getMessage(), e); } }
public RequestSigner ( final Configuration configuration ) throws Exception { this.fac = XMLSignatureFactory.getInstance ( "DOM" ); this.md = this.fac.newDigestMethod ( configuration.getDigestMethod (), null ); this.kif = this.fac.getKeyInfoFactory (); this.t = this.fac.newTransform ( Transform.ENVELOPED, (TransformParameterSpec)null ); this.ref = this.fac.newReference ( "", this.md, Collections.singletonList ( this.t ), null, null ); this.cm = this.fac.newCanonicalizationMethod ( CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec)null ); }
public static boolean verifySignature(Document doc , X509Certificate cert) { try{ if (doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature").getLength() == 0) throw new Exception("Cannot find Signature element"); DOMValidateContext valContext = new DOMValidateContext(cert.getPublicKey(), doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature").item(0)); XMLSignature signature = XMLSignatureFactory.getInstance("DOM").unmarshalXMLSignature(valContext); return signature.validate(valContext); }catch(Exception e){e.printStackTrace();} return false; }
public Document sign(FileInputStream fileStream, KeyPair keyPair) throws ParserConfigurationException, SAXException, IOException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(fileStream); DOMSignContext signContext = new DOMSignContext(keyPair.getPrivate(), document.getDocumentElement()); XMLSignatureFactory signFactory = XMLSignatureFactory .getInstance("DOM"); Reference ref = signFactory.newReference("", signFactory .newDigestMethod(digestMethod, null), Collections .singletonList(signFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); SignedInfo si = signFactory.newSignedInfo(signFactory .newCanonicalizationMethod( CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), signFactory .newSignatureMethod(signatureMethod, null), Collections .singletonList(ref)); KeyInfoFactory kif = signFactory.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(keyPair.getPublic()); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); XMLSignature signature = signFactory.newXMLSignature(si, ki); signature.sign(signContext); return document; }
private boolean validate(final DOMValidateContext validationContext) throws DigitalSignatureValidationException { try { // if (getLogger().isDebugLoggingEnabled()) { // enableReferenceCaching(validationContext); // } XMLSignatureFactory factory = XMLSignatureFactory .getInstance(XML_MECHANISM_TYPE); XMLSignature signature = factory .unmarshalXMLSignature(validationContext); boolean validationResult = signature.validate(validationContext); validationResult = workaroundOpenamBug(signature, validationContext, validationResult); // if (getLogger().isDebugLoggingEnabled()) { // debugLogReferences(signature, validationContext); // } return validationResult; } catch (XMLSignatureException | MarshalException exception) { throw new DigitalSignatureValidationException( "Error occurred during digital signature validation process", DigitalSignatureValidationException.ReasonEnum.EXCEPTION_OCCURRED, exception); } }
private static List<Class<?>> getDeprivilegedClasses() { List<Class<?>> classes = new ArrayList<Class<?>>(); // Test from java.xml.crypto/javax/xml/crypto/dsig package classes.add(XMLSignatureFactory.class); // Test from java.xml.crypto/javax/xml/crypto package classes.add(KeySelectorException.class); // Test From java.security.jgss/javax/security/auth/kerberos package classes.add(KeyTab.class); // Test from jdk.security.jgss/com/sun/security/jgss package classes.add(AuthorizationDataEntry.class); // Test from jdk.security.auth/com/sun/security/auth/callback package classes.add(TextCallbackHandler.class); return classes; }
public static void main(String[] args) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(false); dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); Document doc = dbf.newDocumentBuilder().parse(new File(SIGNATURE)); NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (nl.getLength() == 0) { throw new RuntimeException("Couldn't find 'Signature' element"); } Element element = (Element) nl.item(0); byte[] keyBytes = Base64.getDecoder().decode(validationKey); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey key = kf.generatePublic(spec); KeySelector ks = KeySelector.singletonKeySelector(key); DOMValidateContext vc = new DOMValidateContext(ks, element); // disable secure validation mode vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE); // set a dummy dereferencer to be able to get content by references vc.setURIDereferencer(dereferencer); XMLSignatureFactory factory = XMLSignatureFactory.getInstance(); XMLSignature signature = factory.unmarshalXMLSignature(vc); // run validation signature.validate(vc); }
public static void main(String[] args) { try { XMLSignatureFactory sf = XMLSignatureFactory.getInstance( "DOM", "SomeProviderThatDoesNotExist"); } catch(NoSuchProviderException e) { // this is expected } }
/** * Utility function to validate XML Signature to do a self check * @param signed request * @return */ private boolean validateXmlDSig(String signed, X509Certificate cert){ try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder builder = dbf.newDocumentBuilder(); Document doc = builder.parse(new ByteArrayInputStream(signed.getBytes("utf-8"))); NodeList signatureNodeList = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); NodeList bodyNodeList = doc.getElementsByTagNameNS("http://schemas.xmlsoap.org/soap/envelope/", "Body"); if (signatureNodeList.getLength() == 0) { throw new Exception("Cannot find Signature element"); } DOMValidateContext valContext = new DOMValidateContext(cert.getPublicKey(), signatureNodeList.item(0)); valContext.setIdAttributeNS((Element)bodyNodeList.item(0),"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd","Id"); XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM"); XMLSignature signature = factory.unmarshalXMLSignature(valContext); boolean coreValidity = signature.validate(valContext); /* //detailed validation - use when solving validity problems boolean sv = signature.getSignatureValue().validate(valContext); Iterator<Reference> i = signature.getSignedInfo().getReferences().iterator(); for (int j=0; i.hasNext(); j++) { boolean refValid = ( i.next()).validate(valContext); } */ return coreValidity; } catch (Exception e){ throw new IllegalArgumentException("validation failes", e); } }
public HMACSignatureAlgorithmTest() throws Exception { // // If the BouncyCastle provider is not installed, then try to load it // via reflection. // if (Security.getProvider("BC") == null) { Constructor<?> cons = null; try { Class<?> c = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider"); cons = c.getConstructor(new Class[] {}); } catch (Exception e) { //ignore } if (cons != null) { Provider provider = (Provider)cons.newInstance(); Security.insertProviderAt(provider, 2); bcInstalled = true; } } db = XMLUtils.createDocumentBuilder(false); // create common objects fac = XMLSignatureFactory.getInstance("DOM", new org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI()); withoutComments = fac.newCanonicalizationMethod (CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null); // Digest Methods sha1 = fac.newDigestMethod(DigestMethod.SHA1, null); hmacSha1 = fac.newSignatureMethod("http://www.w3.org/2000/09/xmldsig#hmac-sha1", null); hmacSha224 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#hmac-sha224", null); hmacSha256 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", null); hmacSha384 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#hmac-sha384", null); hmacSha512 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#hmac-sha512", null); ripemd160 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160", null); sks = new KeySelectors.SecretKeySelector("testkey".getBytes("ASCII")); }
OfflineDereferencer() throws Exception { String fs = System.getProperty("file.separator"); String base = System.getProperty("basedir") == null ? "./" : System.getProperty("basedir"); w3cRec = base + fs + "src/test/resources" + fs + "org" + fs + "w3c" + fs + "www" + fs + "TR" + fs + "2000"; defaultDereferencer = XMLSignatureFactory.getInstance().getURIDereferencer(); }
public LocalHttpCacheURIDereferencer() { XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM", new org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI()); ud = xmlSignatureFactory.getURIDereferencer(); String base = BASEDIR == null ? "./": BASEDIR; File dir = new File(base + FS + "src/test/resources" + FS + "javax" + FS + "xml" + FS + "crypto" + FS + "dsig"); uriMap = new HashMap<String, File>(); uriMap.put("http://www.w3.org/TR/xml-stylesheet", new File(dir, "xml-stylesheet")); uriMap.put("http://www.w3.org/Signature/2002/04/xml-stylesheet.b64", new File(dir, "xml-stylesheet.b64")); uriMap.put("http://www.ietf.org/rfc/rfc3161.txt", new File(dir, "rfc3161.txt")); }
public void dsig() throws Exception { XMLSignatureFactory fac = XMLSignatureFactory.getInstance ("DOM", new org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI()); long start = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { fac.newCanonicalizationMethod (CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); } long end = System.currentTimeMillis(); long elapsed = end - start; if (log.isDebugEnabled()) { log.debug("Elapsed: " + elapsed); log.debug("dsig succeeded"); } }
public boolean isValida(final InputStream xmlStream) throws Exception { final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); final Document document = dbf.newDocumentBuilder().parse(xmlStream); final NodeList nodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (nodeList.getLength() == 0) { throw new IllegalStateException("N\u00e3o foi encontrada a assinatura do XML."); } final String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI"); final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance()); final DOMValidateContext validateContext = new DOMValidateContext(new X509KeySelector(), nodeList.item(0)); for (final String tag : AssinaturaDigital.ELEMENTOS_ASSINAVEIS) { final NodeList elements = document.getElementsByTagName(tag); if (elements.getLength() > 0) { validateContext.setIdAttributeNS((Element) elements.item(0), null, "Id"); } } return signatureFactory.unmarshalXMLSignature(validateContext).validate(validateContext); }
public String assinarDocumento(final String conteudoXml) throws Exception { final KeyStore keyStore = KeyStore.getInstance("PKCS12"); try (InputStream certificadoStream = new ByteArrayInputStream(this.config.getCertificado())) { keyStore.load(certificadoStream, this.config.getCertificadoSenha().toCharArray()); } final KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(keyStore.aliases().nextElement(), new KeyStore.PasswordProtection(this.config.getCertificadoSenha().toCharArray())); final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM"); final List<Transform> transforms = new ArrayList<>(2); transforms.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); transforms.add(signatureFactory.newTransform(AssinaturaDigital.C14N_TRANSFORM_METHOD, (TransformParameterSpec) null)); final KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory(); final X509Data x509Data = keyInfoFactory.newX509Data(Collections.singletonList((X509Certificate) keyEntry.getCertificate())); final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data)); final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); try (StringReader stringReader = new StringReader(conteudoXml)) { final Document document = documentBuilderFactory.newDocumentBuilder().parse(new InputSource(stringReader)); for (final String elementoAssinavel : AssinaturaDigital.ELEMENTOS_ASSINAVEIS) { final NodeList elements = document.getElementsByTagName(elementoAssinavel); for (int i = 0; i < elements.getLength(); i++) { final Element element = (Element) elements.item(i); final String id = element.getAttribute("Id"); element.setIdAttribute("Id", true); final Reference reference = signatureFactory.newReference("#" + id, signatureFactory.newDigestMethod(DigestMethod.SHA1, null), transforms, null, null); final SignedInfo signedInfo = signatureFactory.newSignedInfo(signatureFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference)); final XMLSignature signature = signatureFactory.newXMLSignature(signedInfo, keyInfo); signature.sign(new DOMSignContext(keyEntry.getPrivateKey(), element.getParentNode())); } } return this.converteDocumentParaXml(document); } }
/** * Verifies that signed mark data contains a valid signature. * * <p>This method DOES NOT check if the SMD ID is revoked. It's only concerned with the * cryptographic stuff. * * @throws GeneralSecurityException for unsupported protocols, certs not signed by the TMCH, * incorrect keys, and for invalid, old, not-yet-valid or revoked certificates. * @throws IOException * @throws MarshalException * @throws ParserConfigurationException * @throws SAXException */ public void verify(byte[] smdXml) throws GeneralSecurityException, IOException, MarshalException, ParserConfigurationException, SAXException, XMLSignatureException { checkArgument(smdXml.length > 0); Document doc = parseSmdDocument(new ByteArrayInputStream(smdXml)); NodeList signatureNodes = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (signatureNodes.getLength() != 1) { throw new XMLSignatureException("Expected exactly one <ds:Signature> element."); } XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM"); KeyValueKeySelector selector = new KeyValueKeySelector(tmchCertificateAuthority); DOMValidateContext context = new DOMValidateContext(selector, signatureNodes.item(0)); XMLSignature signature = factory.unmarshalXMLSignature(context); boolean isValid; try { isValid = signature.validate(context); } catch (XMLSignatureException e) { throwIfInstanceOf(getRootCause(e), GeneralSecurityException.class); throw e; } if (!isValid) { throw new XMLSignatureException(explainValidationProblem(context, signature)); } }
protected Reference createReference(XMLSignatureFactory fac, String uri, String type, SignatureType sigType, String id, Message message) throws InvalidAlgorithmParameterException, XmlSignatureException { try { List<Transform> transforms = getTransforms(fac, sigType, message); Reference ref = fac.newReference(uri, fac.newDigestMethod(getDigestAlgorithmUri(), null), transforms, type, id); return ref; } catch (NoSuchAlgorithmException e) { throw new XmlSignatureException("Wrong algorithm specified in the configuration.", e); } }
protected Reference createKeyInfoReference(XMLSignatureFactory fac, String keyInfoId, String digestAlgorithm) throws Exception { //NOPMD if (keyInfoId == null) { return null; } if (getConfiguration().getAddKeyInfoReference() == null) { return null; } if (!getConfiguration().getAddKeyInfoReference()) { return null; } LOG.debug("Creating reference to key info element with Id: {}", keyInfoId); List<Transform> transforms = new ArrayList<Transform>(1); Transform transform = fac.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null); transforms.add(transform); return fac.newReference("#" + keyInfoId, fac.newDigestMethod(digestAlgorithm, null), transforms, null, null); }
public Data dereference(URIReference uriReference, XMLCryptoContext context) throws URIReferenceException { if (uriReference == null) { throw new NullPointerException("Parameter 'uriReference' cannot be null."); } if (context == null) { throw new NullPointerException("Parameter 'context' can notbe null."); } if (!(uriReference instanceof DOMURIReference && context instanceof DOMCryptoContext)) { throw new IllegalArgumentException(String.format("This %s implementation supports the DOM XML mechanism only.", URIDereferencer.class.getName())); } String uriString = uriReference.getURI(); if (uriString == null) { throw new URIReferenceException("Cannot resolve a URI of value 'null'."); } if (uriString != null && ((uriString.length() != 0 && uriString.charAt(0) == '#') || uriString.isEmpty())) { // same document uri XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); return fac.getURIDereferencer().dereference(uriReference, context); } throw new URIReferenceException(String.format("URI reference %s not supported", uriString)); }
public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null); List<Transform> transforms = new LinkedList<Transform>(); Map<String, String> xpathNamespaceMap = new HashMap<String, String>(); xpathNamespaceMap.put("ds", "http://www.w3.org/2000/09/xmldsig#"); // XPath v1 - slow... // Transform envelopedTransform = signatureFactory.newTransform( // CanonicalizationMethod.XPATH, new XPathFilterParameterSpec( // "not(ancestor-or-self::ds:Signature)", // xpathNamespaceMap)); // XPath v2 - fast... List<XPathType> types = new ArrayList<XPathType>(1); types.add(new XPathType("/descendant::*[name()='ds:Signature']", XPathType.Filter.SUBTRACT, xpathNamespaceMap)); Transform envelopedTransform = signatureFactory.newTransform(CanonicalizationMethod.XPATH2, new XPathFilter2ParameterSpec(types)); transforms.add(envelopedTransform); Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null); transforms.add(exclusiveTransform); Reference reference = signatureFactory.newReference("", digestMethod, transforms, null, this.dsReferenceId); references.add(reference); }
public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null); List<Transform> transforms = new LinkedList<Transform>(); Transform envelopedTransform = signatureFactory.newTransform(CanonicalizationMethod.ENVELOPED, (TransformParameterSpec) null); transforms.add(envelopedTransform); Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null); transforms.add(exclusiveTransform); Reference reference = signatureFactory.newReference("", digestMethod, transforms, null, null); references.add(reference); }
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); 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); }
private static X509Certificate getVerifiedSignatureSigner(URL odfUrl, Node signatureNode) throws MarshalException, XMLSignatureException { if (null == odfUrl) { throw new IllegalArgumentException("odfUrl is null"); } KeyInfoKeySelector keySelector = new KeyInfoKeySelector(); DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureNode); ODFURIDereferencer dereferencer = new ODFURIDereferencer(odfUrl); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); LOG.debug("java version: " + System.getProperty("java.version")); /* * Requires Java 6u10 because of a bug. See also: * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6696582 */ XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validity = xmlSignature.validate(domValidateContext); if (false == validity) { LOG.debug("invalid signature"); return null; } // TODO: check what has been signed. X509Certificate signer = keySelector.getCertificate(); if (null == signer) { throw new IllegalStateException("signer X509 certificate is null"); } LOG.debug("signer: " + signer.getSubjectX500Principal()); return signer; }
private ODFURIDereferencer(URL odfUrl, byte[] odfData) { if (null == odfUrl && null == odfData) { throw new IllegalArgumentException("odfUrl and odfData are null"); } if (null != odfUrl && null != odfData) { throw new IllegalArgumentException("odfUrl and odfData are both not null"); } this.odfUrl = odfUrl; this.odfData = odfData; XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); this.baseUriDereferener = xmlSignatureFactory.getURIDereferencer(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); try { this.documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new RuntimeException("parser config error: " + e.getMessage(), e); } EntityResolver entityResolver = new ODFEntityResolver(); this.documentBuilder.setEntityResolver(entityResolver); }
public List<X509Certificate> getSigners(URL url) throws IOException, ParserConfigurationException, SAXException, TransformerException, MarshalException, XMLSignatureException, JAXBException { List<X509Certificate> signers = new LinkedList<X509Certificate>(); List<String> signatureResourceNames = getSignatureResourceNames(url); for (String signatureResourceName : signatureResourceNames) { LOG.debug("signature resource name: " + signatureResourceName); Document signatureDocument = loadDocument(url, signatureResourceName); if (null == signatureDocument) { LOG.warn("signature resource not found: " + signatureResourceName); continue; } NodeList signatureNodeList = signatureDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (0 == signatureNodeList.getLength()) { LOG.debug("no signature elements present"); continue; } Node signatureNode = signatureNodeList.item(0); OPCKeySelector keySelector = new OPCKeySelector(url, signatureResourceName); DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureNode); domValidateContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE); OOXMLURIDereferencer dereferencer = new OOXMLURIDereferencer(url); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validity = xmlSignature.validate(domValidateContext); if (false == validity) { LOG.debug("not a valid signature"); continue; } // TODO: check what has been signed. X509Certificate signer = keySelector.getCertificate(); signers.add(signer); } return signers; }
protected ASiCURIDereferencer(byte[] data, File tmpFile) { this.data = data; this.tmpFile = tmpFile; XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); this.baseUriDereferener = xmlSignatureFactory.getURIDereferencer(); }
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"); addManifestObject(signatureFactory, document, signatureId, references, objects); addSignatureInfo(signatureFactory, document, signatureId, references, objects); }
private void addManifestObject(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<Reference> references, List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { Manifest manifest = constructManifest(signatureFactory, document); String objectId = "idPackageObject"; // really has to be this value. List<XMLStructure> objectContent = new LinkedList<XMLStructure>(); objectContent.add(manifest); addSignatureTime(signatureFactory, document, signatureId, objectContent); objects.add(signatureFactory.newXMLObject(objectContent, objectId, null, null)); DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null); Reference reference = signatureFactory.newReference("#" + objectId, digestMethod, null, "http://www.w3.org/2000/09/xmldsig#Object", null); references.add(reference); }
private Manifest constructManifest(XMLSignatureFactory signatureFactory, Document document) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { List<Reference> manifestReferences = new LinkedList<Reference>(); try { addManifestReferences(signatureFactory, document, manifestReferences); } catch (Exception e) { throw new RuntimeException("error: " + e.getMessage(), e); } return signatureFactory.newManifest(manifestReferences); }
private void addSignatureTime(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<XMLStructure> objectContent) { /* * SignatureTime */ Element signatureTimeElement = document.createElementNS(OOXML_DIGSIG_NS, "mdssi:SignatureTime"); signatureTimeElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:mdssi", OOXML_DIGSIG_NS); Element formatElement = document.createElementNS(OOXML_DIGSIG_NS, "mdssi:Format"); formatElement.setTextContent("YYYY-MM-DDThh:mm:ssTZD"); signatureTimeElement.appendChild(formatElement); Element valueElement = document.createElementNS(OOXML_DIGSIG_NS, "mdssi:Value"); Date now = this.clock.getTime(); DateTime dateTime = new DateTime(now.getTime(), DateTimeZone.UTC); DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis(); String nowStr = fmt.print(dateTime); LOG.debug("now: " + nowStr); valueElement.setTextContent(nowStr); signatureTimeElement.appendChild(valueElement); List<XMLStructure> signatureTimeContent = new LinkedList<XMLStructure>(); signatureTimeContent.add(new DOMStructure(signatureTimeElement)); SignatureProperty signatureTimeSignatureProperty = signatureFactory.newSignatureProperty(signatureTimeContent, "#" + signatureId, "idSignatureTime"); List<SignatureProperty> signaturePropertyContent = new LinkedList<SignatureProperty>(); signaturePropertyContent.add(signatureTimeSignatureProperty); SignatureProperties signatureProperties = signatureFactory.newSignatureProperties(signaturePropertyContent, "id-signature-time-" + UUID.randomUUID().toString()); objectContent.add(signatureProperties); }
private void addSignatureInfo(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<Reference> references, List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { List<XMLStructure> objectContent = new LinkedList<XMLStructure>(); Element signatureInfoElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureInfoV1"); signatureInfoElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", OFFICE_DIGSIG_NS); Element manifestHashAlgorithmElement = document.createElementNS(OFFICE_DIGSIG_NS, "ManifestHashAlgorithm"); manifestHashAlgorithmElement.setTextContent("http://www.w3.org/2000/09/xmldsig#sha1"); signatureInfoElement.appendChild(manifestHashAlgorithmElement); List<XMLStructure> signatureInfoContent = new LinkedList<XMLStructure>(); signatureInfoContent.add(new DOMStructure(signatureInfoElement)); SignatureProperty signatureInfoSignatureProperty = signatureFactory.newSignatureProperty(signatureInfoContent, "#" + signatureId, "idOfficeV1Details"); List<SignatureProperty> signaturePropertyContent = new LinkedList<SignatureProperty>(); signaturePropertyContent.add(signatureInfoSignatureProperty); SignatureProperties signatureProperties = signatureFactory.newSignatureProperties(signaturePropertyContent, null); objectContent.add(signatureProperties); String objectId = "idOfficeObject"; objects.add(signatureFactory.newXMLObject(objectContent, objectId, null, null)); DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null); Reference reference = signatureFactory.newReference("#" + objectId, digestMethod, null, "http://www.w3.org/2000/09/xmldsig#Object", null); references.add(reference); }
protected OOXMLURIDereferencer(byte[] ooxmlDocument, URL ooxmlUrl) { if (null == ooxmlUrl && null == ooxmlDocument) { throw new IllegalArgumentException("need some reference to the OOXML document"); } this.ooxmlUrl = ooxmlUrl; this.ooxmlDocument = ooxmlDocument; XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); this.baseUriDereferencer = xmlSignatureFactory.getURIDereferencer(); }