javax.xml.crypto.dsig.XMLSignatureException Java Examples

The following examples show how to use javax.xml.crypto.dsig.XMLSignatureException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DigitalSignatures.java    From org.hl7.fhir.core with Apache License 2.0 8 votes vote down vote up
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException, FHIRException {
  // http://docs.oracle.com/javase/7/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html
  //
  byte[] inputXml = "<Envelope xmlns=\"urn:envelope\">\r\n</Envelope>\r\n".getBytes();
  // load the document that's going to be signed
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
  dbf.setNamespaceAware(true);
  DocumentBuilder builder = dbf.newDocumentBuilder();  
  Document doc = builder.parse(new ByteArrayInputStream(inputXml)); 
  
  // create a key pair
  KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
  kpg.initialize(512);
  KeyPair kp = kpg.generateKeyPair(); 
  
  // sign the document
  DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement()); 
  XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); 
 
  Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null);
  SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));
  
  KeyInfoFactory kif = fac.getKeyInfoFactory(); 
  KeyValue kv = kif.newKeyValue(kp.getPublic());
  KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
  XMLSignature signature = fac.newXMLSignature(si, ki); 
  signature.sign(dsc);
  
  OutputStream os = System.out;
  new XmlGenerator().generate(doc.getDocumentElement(), os);
}
 
Example #2
Source File: DigitalSignatures.java    From org.hl7.fhir.core with Apache License 2.0 7 votes vote down vote up
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException, FHIRException, org.hl7.fhir.exceptions.FHIRException {
  // http://docs.oracle.com/javase/7/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html
  //
  byte[] inputXml = "<Envelope xmlns=\"urn:envelope\">\r\n</Envelope>\r\n".getBytes();
  // load the document that's going to be signed
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
  dbf.setNamespaceAware(true);
  DocumentBuilder builder = dbf.newDocumentBuilder();  
  Document doc = builder.parse(new ByteArrayInputStream(inputXml)); 
  
  // create a key pair
  KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
  kpg.initialize(512);
  KeyPair kp = kpg.generateKeyPair(); 
  
  // sign the document
  DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement()); 
  XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); 
 
  Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null);
  SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));
  
  KeyInfoFactory kif = fac.getKeyInfoFactory(); 
  KeyValue kv = kif.newKeyValue(kp.getPublic());
  KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
  XMLSignature signature = fac.newXMLSignature(si, ki); 
  signature.sign(dsc);
  
  OutputStream os = System.out;
  new XmlGenerator().generate(doc.getDocumentElement(), os);
}
 
Example #3
Source File: RequestValidator.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
public Result validate ( final Document doc ) throws Exception
{
    final NodeList nl = doc.getElementsByTagNameNS ( XMLSignature.XMLNS, "Signature" ); //$NON-NLS-1$

    if ( nl.getLength () == 0 )
    {
        return new Result ( StatusCodes.VALIDATE_NO_SIGNATURE_DATA, "No signature data found" );
    }

    final DOMValidateContext dvc = new DOMValidateContext ( this.keySelector, nl.item ( 0 ) );

    final XMLSignature signature = this.factory.unmarshalXMLSignature ( dvc );

    try
    {
        final boolean result = signature.validate ( dvc );

        return new Result ( result, signature );
    }
    catch ( final XMLSignatureException e )
    {
        logger.debug ( "Failed to perform validation", e );
        return Result.INVALID;
    }
}
 
Example #4
Source File: TmchXmlSignature.java    From nomulus with Apache License 2.0 6 votes vote down vote up
private static String explainValidationProblem(
    DOMValidateContext context, XMLSignature signature)
        throws XMLSignatureException {
  @SuppressWarnings("unchecked")  // Safe by specification.
  List<Reference> references = signature.getSignedInfo().getReferences();
  StringBuilder builder = new StringBuilder();
  builder.append("Signature failed core validation\n");
  boolean sv = signature.getSignatureValue().validate(context);
  builder.append(String.format("Signature validation status: %s\n", sv));
  for (Reference ref : references) {
    builder.append("references[");
    builder.append(ref.getURI());
    builder.append("] validity status: ");
    builder.append(ref.validate(context));
    builder.append("\n");
  }
  return builder.toString();
}
 
Example #5
Source File: SAML2Signature.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Sign an Document at the root
 *
 * @param keyPair Key Pair
 *
 * @return
 *
 * @throws ParserConfigurationException
 * @throws XMLSignatureException
 * @throws MarshalException
 * @throws GeneralSecurityException
 */
public Document sign(Document doc, String referenceID, String keyName, KeyPair keyPair, String canonicalizationMethodType) throws ParserConfigurationException,
        GeneralSecurityException, MarshalException, XMLSignatureException {
    String referenceURI = "#" + referenceID;

    configureIdAttribute(doc);

    if (sibling != null) {
        SignatureUtilTransferObject dto = new SignatureUtilTransferObject();
        dto.setDocumentToBeSigned(doc);
        dto.setKeyName(keyName);
        dto.setKeyPair(keyPair);
        dto.setDigestMethod(digestMethod);
        dto.setSignatureMethod(signatureMethod);
        dto.setReferenceURI(referenceURI);
        dto.setNextSibling(sibling);

        if (x509Certificate != null) {
            dto.setX509Certificate(x509Certificate);
        }

        return XMLSignatureUtil.sign(dto, canonicalizationMethodType);
    }
    return XMLSignatureUtil.sign(doc, keyName, keyPair, digestMethod, signatureMethod, referenceURI, canonicalizationMethodType);
}
 
Example #6
Source File: STSServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void signRequest(Element requestElement, PrivateKey privateKey, Object keyInfoValue) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, KeyException {
   DOMSignContext domSignContext = new DOMSignContext(privateKey, requestElement, requestElement.getFirstChild());
   String requestId = requestElement.getAttribute("RequestID");
   requestElement.setIdAttribute("RequestID", true);
   List<Transform> transforms = new LinkedList();
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature", (TransformParameterSpec)null));
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null));
   Reference reference = xmlSignatureFactory.newReference("#" + requestId, xmlSignatureFactory.newDigestMethod("http://www.w3.org/2000/09/xmldsig#sha1", (DigestMethodParameterSpec)null), transforms, (String)null, (String)null);
   CanonicalizationMethod canonicalizationMethod = xmlSignatureFactory.newCanonicalizationMethod("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null);
   SignatureMethod signatureMethod = xmlSignatureFactory.newSignatureMethod("http://www.w3.org/2000/09/xmldsig#rsa-sha1", (SignatureMethodParameterSpec)null);
   SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference));
   KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
   KeyInfo keyInfo = null;
   if (keyInfoValue instanceof PublicKey) {
      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newKeyValue((PublicKey)keyInfoValue)));
   } else {
      if (!(keyInfoValue instanceof X509Certificate)) {
         throw new IllegalArgumentException("Unsupported keyinfo type [" + keyInfoValue.getClass() + "]");
      }

      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newX509Data(Collections.singletonList(keyInfoValue))));
   }

   XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);
   xmlSignature.sign(domSignContext);
}
 
Example #7
Source File: STSServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void signRequest(Element requestElement, PrivateKey privateKey, Object keyInfoValue) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, KeyException {
   DOMSignContext domSignContext = new DOMSignContext(privateKey, requestElement, requestElement.getFirstChild());
   String requestId = requestElement.getAttribute("RequestID");
   requestElement.setIdAttribute("RequestID", true);
   List<Transform> transforms = new LinkedList();
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature", (TransformParameterSpec)null));
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null));
   Reference reference = xmlSignatureFactory.newReference("#" + requestId, xmlSignatureFactory.newDigestMethod("http://www.w3.org/2000/09/xmldsig#sha1", (DigestMethodParameterSpec)null), transforms, (String)null, (String)null);
   CanonicalizationMethod canonicalizationMethod = xmlSignatureFactory.newCanonicalizationMethod("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null);
   SignatureMethod signatureMethod = xmlSignatureFactory.newSignatureMethod("http://www.w3.org/2000/09/xmldsig#rsa-sha1", (SignatureMethodParameterSpec)null);
   SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference));
   KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
   KeyInfo keyInfo = null;
   if (keyInfoValue instanceof PublicKey) {
      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newKeyValue((PublicKey)keyInfoValue)));
   } else {
      if (!(keyInfoValue instanceof X509Certificate)) {
         throw new IllegalArgumentException("Unsupported keyinfo type [" + keyInfoValue.getClass() + "]");
      }

      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newX509Data(Collections.singletonList(keyInfoValue))));
   }

   XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);
   xmlSignature.sign(domSignContext);
}
 
Example #8
Source File: STSServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void signRequest(Element requestElement, PrivateKey privateKey, Object keyInfoValue) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, KeyException {
   DOMSignContext domSignContext = new DOMSignContext(privateKey, requestElement, requestElement.getFirstChild());
   String requestId = requestElement.getAttribute("RequestID");
   requestElement.setIdAttribute("RequestID", true);
   List<Transform> transforms = new LinkedList();
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature", (TransformParameterSpec)null));
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null));
   Reference reference = xmlSignatureFactory.newReference("#" + requestId, xmlSignatureFactory.newDigestMethod("http://www.w3.org/2000/09/xmldsig#sha1", (DigestMethodParameterSpec)null), transforms, (String)null, (String)null);
   CanonicalizationMethod canonicalizationMethod = xmlSignatureFactory.newCanonicalizationMethod("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null);
   SignatureMethod signatureMethod = xmlSignatureFactory.newSignatureMethod("http://www.w3.org/2000/09/xmldsig#rsa-sha1", (SignatureMethodParameterSpec)null);
   SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference));
   KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
   KeyInfo keyInfo = null;
   if (keyInfoValue instanceof PublicKey) {
      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newKeyValue((PublicKey)keyInfoValue)));
   } else {
      if (!(keyInfoValue instanceof X509Certificate)) {
         throw new IllegalArgumentException("Unsupported keyinfo type [" + keyInfoValue.getClass() + "]");
      }

      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newX509Data(Collections.singletonList(keyInfoValue))));
   }

   XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);
   xmlSignature.sign(domSignContext);
}
 
Example #9
Source File: STSServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void signRequest(Element requestElement, PrivateKey privateKey, Object keyInfoValue) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, KeyException {
   DOMSignContext domSignContext = new DOMSignContext(privateKey, requestElement, requestElement.getFirstChild());
   String requestId = requestElement.getAttribute("RequestID");
   requestElement.setIdAttribute("RequestID", true);
   List<Transform> transforms = new LinkedList();
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature", (TransformParameterSpec)null));
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null));
   Reference reference = xmlSignatureFactory.newReference("#" + requestId, xmlSignatureFactory.newDigestMethod("http://www.w3.org/2000/09/xmldsig#sha1", (DigestMethodParameterSpec)null), transforms, (String)null, (String)null);
   CanonicalizationMethod canonicalizationMethod = xmlSignatureFactory.newCanonicalizationMethod("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null);
   SignatureMethod signatureMethod = xmlSignatureFactory.newSignatureMethod("http://www.w3.org/2000/09/xmldsig#rsa-sha1", (SignatureMethodParameterSpec)null);
   SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference));
   KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
   KeyInfo keyInfo = null;
   if (keyInfoValue instanceof PublicKey) {
      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newKeyValue((PublicKey)keyInfoValue)));
   } else {
      if (!(keyInfoValue instanceof X509Certificate)) {
         throw new IllegalArgumentException("Unsupported keyinfo type [" + keyInfoValue.getClass() + "]");
      }

      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newX509Data(Collections.singletonList(keyInfoValue))));
   }

   XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);
   xmlSignature.sign(domSignContext);
}
 
Example #10
Source File: STSServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void signRequest(Element requestElement, PrivateKey privateKey, Object keyInfoValue) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, KeyException {
   DOMSignContext domSignContext = new DOMSignContext(privateKey, requestElement, requestElement.getFirstChild());
   String requestId = requestElement.getAttribute("RequestID");
   requestElement.setIdAttribute("RequestID", true);
   List<Transform> transforms = new LinkedList();
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature", (TransformParameterSpec)null));
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null));
   Reference reference = xmlSignatureFactory.newReference("#" + requestId, xmlSignatureFactory.newDigestMethod("http://www.w3.org/2000/09/xmldsig#sha1", (DigestMethodParameterSpec)null), transforms, (String)null, (String)null);
   CanonicalizationMethod canonicalizationMethod = xmlSignatureFactory.newCanonicalizationMethod("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null);
   SignatureMethod signatureMethod = xmlSignatureFactory.newSignatureMethod("http://www.w3.org/2000/09/xmldsig#rsa-sha1", (SignatureMethodParameterSpec)null);
   SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference));
   KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
   KeyInfo keyInfo = null;
   if (keyInfoValue instanceof PublicKey) {
      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newKeyValue((PublicKey)keyInfoValue)));
   } else {
      if (!(keyInfoValue instanceof X509Certificate)) {
         throw new IllegalArgumentException("Unsupported keyinfo type [" + keyInfoValue.getClass() + "]");
      }

      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newX509Data(Collections.singletonList(keyInfoValue))));
   }

   XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);
   xmlSignature.sign(domSignContext);
}
 
Example #11
Source File: XMLSignatureUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Sign the root element
 *
 * @param doc
 * @param digestMethod
 * @param signatureMethod
 * @param referenceURI
 *
 * @return
 *
 * @throws GeneralSecurityException
 * @throws XMLSignatureException
 * @throws MarshalException
 * @since 2.5.0
 */
public static Document sign(Document doc, String keyName, KeyPair keyPair, String digestMethod, String signatureMethod, String referenceURI,
                            X509Certificate x509Certificate, String canonicalizationMethodType)
        throws GeneralSecurityException, MarshalException, XMLSignatureException {
    if (logger.isTraceEnabled()) {
        logger.trace("Document to be signed=" + DocumentUtil.asString(doc));
    }
    PrivateKey signingKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    DOMSignContext dsc = new DOMSignContext(signingKey, doc.getDocumentElement());

    signImpl(dsc, digestMethod, signatureMethod, referenceURI, keyName, publicKey, x509Certificate, canonicalizationMethodType);

    return doc;
}
 
Example #12
Source File: XMLSignatureUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private static boolean validateUsingKeySelector(Node signatureNode, KeySelector validationKeySelector) throws XMLSignatureException, MarshalException {
    DOMValidateContext valContext = new DOMValidateContext(validationKeySelector, signatureNode);
    XMLSignature signature = fac.unmarshalXMLSignature(valContext);
    boolean coreValidity = signature.validate(valContext);
    
    if (! coreValidity) {
        if (logger.isTraceEnabled()) {
            boolean sv = signature.getSignatureValue().validate(valContext);
            logger.trace("Signature validation status: " + sv);

            List<Reference> references = signature.getSignedInfo().getReferences();
            for (Reference ref : references) {
                logger.trace("[Ref id=" + ref.getId() + ":uri=" + ref.getURI() + "]validity status:" + ref.validate(valContext));
            }
        }
    }

    return coreValidity;
}
 
Example #13
Source File: MSExcelOOXMLSignUtil.java    From hadoopoffice with Apache License 2.0 5 votes vote down vote up
/** 
 * Signs the Excel OOXML file and writes it to the final outputstream
 * 
 * @param privateKey private Key for signing
 * @param x509List List of certificates for signing. First item must be the private key for signing.
 * @param password optional password for encryption, if used
 * @param hashAlgorithm hash algorithm to be used
 * 
 * @throws MarshalException 
 * @throws XMLSignatureException 
 * @throws IOException 
 * @throws FormatNotUnderstoodException 
 */
public void sign(Key privateKey, List<X509Certificate> x509List, String password, HashAlgorithm hashAlgorithm) throws XMLSignatureException, MarshalException, IOException, FormatNotUnderstoodException {
	if (this.tempSignFileOS!=null) { // close it we sign only a closed temporary file
		this.tempSignFileOS.close();
	}
	SignatureConfig sc = new SignatureConfig();
       sc.addSignatureFacet(new OOXMLSignatureFacet());
       sc.addSignatureFacet(new KeyInfoSignatureFacet());
       sc.addSignatureFacet(new XAdESSignatureFacet());
       sc.addSignatureFacet(new Office2010SignatureFacet());
	sc.setKey((PrivateKey)privateKey);
	sc.setSigningCertificateChain(x509List);
	sc.setDigestAlgo(hashAlgorithm);
	FileInputStream tempSignFileIS = null;
	try {
		
		InputStream tmpFileInputStream = new FileInputStream(this.tempSignFile);
		if (password==null) {
			this.signUnencryptedOpcPackage(tmpFileInputStream, sc);
		} else {
			this.signEncryptedPackage(tmpFileInputStream, sc, password);
		}
		
	} catch (InvalidFormatException | IOException e) {
		LOG.error(e);
	} finally {
		if (this.finalOutputStream!=null) {
			this.finalOutputStream.close();
		}
		if (tempSignFileIS!=null) {
			tempSignFileIS.close();
		}
	}
}
 
Example #14
Source File: XmlSignatureHelperTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Ignore
@Test
public void signSamlArtifactResolve() throws JDOMException, TransformerException, NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException,
        KeyStoreException, CertificateException {
    Document unsignedDocument = getDocument("artifact-resolve-unsigned.xml");
    Document signedDom = signatureHelper.signSamlAssertion(unsignedDocument);
    Assert.assertNotNull(signedDom);
    boolean foundSignedInfo = false;
    boolean foundSignatureValue = false;
    boolean foundKeyInfo = false;

    // traverse the saml to find the signature element and its child nodes
    NodeList list = signedDom.getChildNodes();
    if (list.item(0).getNodeName().equals("samlp:ArtifactResolve")) {
        NodeList sublist = list.item(0).getChildNodes();
        for (int i = 0; i < sublist.getLength(); i++) {
            if (sublist.item(i).getNodeName().equals("Signature")) {
                NodeList signatureList = sublist.item(i).getChildNodes();
                for (int j = 0; j < signatureList.getLength(); j++) {
                    if (signatureList.item(j).getNodeName().equals("SignedInfo")) {
                        foundSignedInfo = true;
                    } else if (signatureList.item(j).getNodeName().equals("SignatureValue")) {
                        foundSignatureValue = true;
                    } else if (signatureList.item(j).getNodeName().equals("KeyInfo")) {
                        foundKeyInfo = true;
                    }
                }
            }
        }
    }
    Assert.assertTrue("Should be true if Signature contains SignedInfo tag", foundSignedInfo);
    Assert.assertTrue("Should be true if Signature contains SignatureValue tag", foundSignatureValue);
    Assert.assertTrue("Should be true if Signature contains KeyInfo tag", foundKeyInfo);
    Assert.assertTrue(validator.isDocumentTrusted(signedDom, "CN=*.slidev.org,OU=Domain Control Validated,O=*.slidev.org"));
}
 
Example #15
Source File: TrustAddressGeneratorTest.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
public TrustAddressGeneratorTest() throws IOException, MarshalException, ParserConfigurationException, SAXException, XMLSignatureException {
    InputStream input = new FileInputStream("src/test/ts/EntryToken.tsml");
    XMLDSigVerifier sigVerifier = new XMLDSigVerifier();
    XMLSignature signature = sigVerifier.getValidXMLSignature(input);
    InputStream digest = signature.getSignedInfo().getCanonicalizedData();
    this.digest = convertHexToBase64String(Numeric.toHexString(getBytesFromInputStream(digest)));
}
 
Example #16
Source File: MSExcelOOXMLSignUtil.java    From hadoopoffice with Apache License 2.0 5 votes vote down vote up
private void signUnencryptedOpcPackage(InputStream tmpFileInputStream, SignatureConfig sc) throws InvalidFormatException, IOException, XMLSignatureException, MarshalException {
	OPCPackage	pkg = OPCPackage.open(tmpFileInputStream);
	sc.setOpcPackage(pkg);
	// needed to avoid linebreaks for xmlsec
	String originalPropertyValue=null;

		
		SignatureInfo si = new SignatureInfo();
		si.setSignatureConfig(sc);
		si.confirmSignature();
		pkg.save(this.finalOutputStream);
		pkg.close();
}
 
Example #17
Source File: MSExcelOOXMLSignUtil.java    From hadoopoffice with Apache License 2.0 5 votes vote down vote up
private void signEncryptedPackage(InputStream tmpFileInputStream, SignatureConfig sc, String password) throws IOException, InvalidFormatException, FormatNotUnderstoodException, XMLSignatureException, MarshalException {

	POIFSFileSystem poifsTemp = new POIFSFileSystem(tmpFileInputStream);
	EncryptionInfo info = new EncryptionInfo(poifsTemp);
	Decryptor d = Decryptor.getInstance(info);

	try {
		if (!d.verifyPassword(password)) {
			throw new FormatNotUnderstoodException("Error: Cannot decrypt new Excel file (.xlsx) for signing. Invalid password");
		}
		// signing
		OPCPackage pkg = OPCPackage.open(d.getDataStream(poifsTemp));
		sc.setOpcPackage(pkg);
		
		SignatureInfo si = new SignatureInfo();
		si.setSignatureConfig(sc);
		si.confirmSignature();
		// encrypt again
		Encryptor enc = info.getEncryptor();
		enc.confirmPassword(password);
		POIFSFileSystem poifs = new POIFSFileSystem();
		OutputStream os = enc.getDataStream(poifs);
		pkg.save(os);
		pkg.close();
		if (os!=null) {
			os.close();
		}
		poifs.writeFilesystem(this.finalOutputStream);
		if (poifs!=null) {
			poifs.close();
		}
		if (poifsTemp!=null) {
			poifsTemp.close();
		}
	} catch (GeneralSecurityException e) {
		
		LOG.error(e);
		throw new FormatNotUnderstoodException("Error: Cannot decrypt new Excel file (.xlsx)  for signing.");
	} 
}
 
Example #18
Source File: TmchXmlSignature.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * 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.
 */
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));
  }
}
 
Example #19
Source File: SamlAssertionServiceTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testSandbox() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException,
        TransformerException, MarshalException, XMLSignatureException {
    
    service.setIssuerBase("http://local.slidev.org:8082/simple-idp");
    
    List<String> roles = Arrays.asList("role1", "role2");
    
    Map<String, String> attributes = new HashMap<String, String>();
    Mockito.when(
            samlComposer.componseResponse("destUri", "http://local.slidev.org:8082/simple-idp?",
                    "request_id", "unique_id", attributes, roles)).thenReturn("samlResponse");
    
    Request request = Mockito.mock(AuthRequestService.Request.class);
    Mockito.when(request.getRequestId()).thenReturn("request_id");
    Mockito.when(request.getRealm()).thenReturn(null);
    Mockito.when(request.getDestination()).thenReturn("destUri");
    
    User user = Mockito.mock(User.class);
    Mockito.when(user.getUserId()).thenReturn("unique_id");
    
    service.buildAssertion("unique_id", roles, attributes, request);
    
    Mockito.verify(samlComposer).componseResponse("destUri", "http://local.slidev.org:8082/simple-idp",
            "request_id", "unique_id", attributes, roles);
    
}
 
Example #20
Source File: DigitalSignatures.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException, FHIRException, org.hl7.fhir.exceptions.FHIRException {
  // http://docs.oracle.com/javase/7/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html
  //
  byte[] inputXml = "<Envelope xmlns=\"urn:envelope\">\r\n</Envelope>\r\n".getBytes();
  // load the document that's going to be signed
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
  dbf.setNamespaceAware(true);
  DocumentBuilder builder = dbf.newDocumentBuilder();  
  Document doc = builder.parse(new ByteArrayInputStream(inputXml)); 
  
  // create a key pair
  KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
  kpg.initialize(512);
  KeyPair kp = kpg.generateKeyPair(); 
  
  // sign the document
  DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement()); 
  XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); 
 
  Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null);
  SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));
  
  KeyInfoFactory kif = fac.getKeyInfoFactory(); 
  KeyValue kv = kif.newKeyValue(kp.getPublic());
  KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
  XMLSignature signature = fac.newXMLSignature(si, ki); 
  signature.sign(dsc);
  
  OutputStream os = System.out;
  new XmlGenerator().generate(doc.getDocumentElement(), os);
}
 
Example #21
Source File: XMLSignatureBuilder.java    From development with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #22
Source File: DigitalSignatureValidator.java    From development with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #23
Source File: DigitalSignatureValidator.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * The overall signature validation consists of two steps, one is the
 * validation of the signature itself and the other the validation of the
 * references digest values. Because of a canonicalization bug in openam,
 * which is not yet registered, the second verification cannot be done.
 * 
 * @return true if the signature validation has not failed, even if the
 *         reference validation failed.
 */
boolean workaroundOpenamBug(XMLSignature signature,
        DOMValidateContext validationContext, boolean validationResult)
        throws XMLSignatureException {
    if (!validationResult) {
        if (signature.getSignatureValue().validate(validationContext)) {
            return true;
        }
    }
    return validationResult;
}
 
Example #24
Source File: XMLHelpers.java    From SAMLRaider with MIT License 5 votes vote down vote up
/**
 * Sign assertions in SAML message
 *
 * @param document
 *            Document in assertions should be signed
 * @param signAlgorithm
 *            Signature algorithm in uri form, default if an unknown
 *            algorithm is provided:
 *            http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
 * @param digestAlgorithm
 *            Digest algorithm in uri form, default if an unknown algorithm
 *            is provided: http://www.w3.org/2001/04/xmlenc#sha256
 */
public void signAssertion(Document document, String signAlgorithm, String digestAlgorithm, X509Certificate cert, PrivateKey key)
		throws CertificateException, FileNotFoundException, NoSuchAlgorithmException, InvalidKeySpecException,
		MarshalException, XMLSignatureException, IOException {
	try {
		if(Thread.currentThread().getContextClassLoader() == null){
			Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); 
		}
		setIDAttribute(document);
		XPath xpath = XPathFactory.newInstance().newXPath();
		XPathExpression expr = xpath.compile("//*[local-name()='Assertion']/@ID");
		NodeList nlURIs = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

		String[] sigIDs = new String[nlURIs.getLength()];

		for (int i = 0; i < nlURIs.getLength(); i++) {
			sigIDs[i] = nlURIs.item(i).getNodeValue();
		}

		Init.init();
		for (String id : sigIDs) {
			signElement(document, id, cert, key, signAlgorithm, digestAlgorithm);
		}
	} catch (XPathExpressionException e) {
		e.printStackTrace();
	}
}
 
Example #25
Source File: XMLHelpers.java    From SAMLRaider with MIT License 5 votes vote down vote up
/**
 * Sign whole SAML Message
 *
 * @param document
 *            Document with the response to sign
 * @param signAlgorithm
 *            Signature algorithm in uri form, default if an unknown
 *            algorithm is provided:
 *            http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
 * @param digestAlgorithm
 *            Digest algorithm in uri form, default if an unknown algorithm
 *            is provided: http://www.w3.org/2001/04/xmlenc#sha256
 */
public void signMessage(Document document, String signAlgorithm, String digestAlgorithm, X509Certificate cert, PrivateKey key)
		throws CertificateException, FileNotFoundException, NoSuchAlgorithmException, InvalidKeySpecException,
		MarshalException, XMLSignatureException, IOException {
	try {
		if(Thread.currentThread().getContextClassLoader() == null){
			Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); 
		}
		setIDAttribute(document);
		XPath xpath = XPathFactory.newInstance().newXPath();
		XPathExpression expr = xpath.compile("//*[local-name()='Response']/@ID");
		NodeList nlURIs = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

		String[] sigIDs = new String[nlURIs.getLength()];

		for (int i = 0; i < nlURIs.getLength(); i++) {
			sigIDs[i] = nlURIs.item(i).getNodeValue();
		}

		Init.init();
		for (String id : sigIDs) {
			signElement(document, id, cert, key, signAlgorithm, digestAlgorithm);
		}
	} catch (XPathExpressionException e) {
		e.printStackTrace();
	}
}
 
Example #26
Source File: XmlSignatureHelper.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * Signs the SAML assertion using the specified public and private keys.
 * 
 * @param document
 *            SAML assertion be signed.
 * @param privateKey
 *            Private key used to sign SAML assertion.
 * @param publicKey
 *            Public key used to sign SAML asserion.
 * @return w3c element representation of specified document.
 * @throws NoSuchAlgorithmException
 * @throws InvalidAlgorithmParameterException
 * @throws KeyException
 * @throws MarshalException
 * @throws XMLSignatureException
 */
private Element signSamlAssertion(Document document, PrivateKey privateKey, X509Certificate certificate)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException,
        XMLSignatureException {
    XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");
    List<Transform> envelopedTransform = Collections.singletonList(signatureFactory.newTransform(
            Transform.ENVELOPED, (TransformParameterSpec) null));
    Reference ref = signatureFactory.newReference("", signatureFactory.newDigestMethod(DigestMethod.SHA1, null),
            envelopedTransform, null, null);
    
    SignatureMethod signatureMethod = null;
    if (certificate.getPublicKey() instanceof DSAPublicKey) {
        signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null);
    } else if (certificate.getPublicKey() instanceof RSAPublicKey) {
        signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
    }
    
    CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod(
            CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null);
    
    SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod,
            Collections.singletonList(ref));
    
    KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory();
    X509Data data = keyInfoFactory.newX509Data(Collections.singletonList(certificate));
    KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(data));
    
    Element w3cElement = document.getDocumentElement();
    Node xmlSigInsertionPoint = getXmlSignatureInsertionLocation(w3cElement);
    DOMSignContext dsc = new DOMSignContext(privateKey, w3cElement, xmlSigInsertionPoint);
    
    XMLSignature signature = signatureFactory.newXMLSignature(signedInfo, keyInfo);
    signature.sign(dsc);
    return w3cElement;
}
 
Example #27
Source File: SAML2Signature.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Sign a SAML Document
 *
 * @param samlDocument
 * @param keypair
 *
 * @throws org.keycloak.saml.common.exceptions.ProcessingException
 */
public void signSAMLDocument(Document samlDocument, String keyName, KeyPair keypair, String canonicalizationMethodType) throws ProcessingException {
    // Get the ID from the root
    String id = samlDocument.getDocumentElement().getAttribute(JBossSAMLConstants.ID.get());
    try {
        sign(samlDocument, id, keyName, keypair, canonicalizationMethodType);
    } catch (ParserConfigurationException | GeneralSecurityException | MarshalException | XMLSignatureException e) {
        throw new ProcessingException(logger.signatureError(e));
    }
}
 
Example #28
Source File: XMLSignatureUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Sign the root element
 *
 *
 * @return
 *
 * @throws GeneralSecurityException
 * @throws XMLSignatureException
 * @throws MarshalException
 */
public static Document sign(SignatureUtilTransferObject dto, String canonicalizationMethodType) throws GeneralSecurityException, MarshalException,
        XMLSignatureException {
    Document doc = dto.getDocumentToBeSigned();
    String keyName = dto.getKeyName();
    KeyPair keyPair = dto.getKeyPair();
    Node nextSibling = dto.getNextSibling();
    String digestMethod = dto.getDigestMethod();
    String referenceURI = dto.getReferenceURI();
    String signatureMethod = dto.getSignatureMethod();

    if (logger.isTraceEnabled()) {
        logger.trace("Document to be signed=" + DocumentUtil.asString(doc));
    }

    PrivateKey signingKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    DOMSignContext dsc = new DOMSignContext(signingKey, doc.getDocumentElement(), nextSibling);

    signImpl(dsc, digestMethod, signatureMethod, referenceURI, keyName, publicKey, dto.getX509Certificate(), canonicalizationMethodType);

    if (logger.isTraceEnabled()) {
        logger.trace("Signed document=" + DocumentUtil.asString(doc));
    }

    return doc;
}
 
Example #29
Source File: XMLSignatureUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static void signImpl(DOMSignContext dsc, String digestMethod, String signatureMethod, String referenceURI, String keyName, PublicKey publicKey,
                             X509Certificate x509Certificate, String canonicalizationMethodType)
        throws GeneralSecurityException, MarshalException, XMLSignatureException {
    dsc.setDefaultNamespacePrefix("dsig");

    DigestMethod digestMethodObj = fac.newDigestMethod(digestMethod, null);
    Transform transform1 = fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
    Transform transform2 = fac.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", (TransformParameterSpec) null);

    List<Transform> transformList = new ArrayList<>();
    transformList.add(transform1);
    transformList.add(transform2);

    Reference ref = fac.newReference(referenceURI, digestMethodObj, transformList, null, null);

    CanonicalizationMethod canonicalizationMethod = fac.newCanonicalizationMethod(canonicalizationMethodType,
            (C14NMethodParameterSpec) null);

    List<Reference> referenceList = Collections.singletonList(ref);
    SignatureMethod signatureMethodObj = fac.newSignatureMethod(signatureMethod, null);
    SignedInfo si = fac.newSignedInfo(canonicalizationMethod, signatureMethodObj, referenceList);

    KeyInfo ki;
    if (includeKeyInfoInSignature) {
        ki = createKeyInfo(keyName, publicKey, x509Certificate);
    } else {
        ki = createKeyInfo(keyName, null, null);
    }
    XMLSignature signature = fac.newXMLSignature(si, ki);

    signature.sign(dsc);
}
 
Example #30
Source File: SamlAssertionServiceTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithRealm() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException,
        TransformerException, MarshalException, XMLSignatureException {
    
    service.setIssuerBase("http://local.slidev.org:8082/simple-idp");
    
    List<String> roles = Arrays.asList("role1", "role2");
    
    Map<String, String> attributes = new HashMap<String, String>();
    Mockito.when(
            samlComposer.componseResponse("destUri", "http://local.slidev.org:8082/simple-idp?realm=realm",
                    "request_id", "unique_id", attributes, roles)).thenReturn("samlResponse");
    
    Request request = Mockito.mock(AuthRequestService.Request.class);
    Mockito.when(request.getRequestId()).thenReturn("request_id");
    Mockito.when(request.getRealm()).thenReturn("realm");
    Mockito.when(request.getDestination()).thenReturn("destUri");
    
    User user = Mockito.mock(User.class);
    Mockito.when(user.getUserId()).thenReturn("unique_id");
    
    service.buildAssertion("unique_id", roles, attributes, request);
    
    Mockito.verify(samlComposer).componseResponse("destUri", "http://local.slidev.org:8082/simple-idp?realm=realm",
            "request_id", "unique_id", attributes, roles);
    
}