javax.xml.crypto.dsig.Reference Java Examples

The following examples show how to use javax.xml.crypto.dsig.Reference. 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: 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 #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: DigSigUtil.java    From juddi with Apache License 2.0 6 votes vote down vote up
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;
}
 
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: WSSecHeaderGeneratorWss4jImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void sign(AbstractWsSecurityHandler.SignedParts... parts) throws TechnicalConnectorException {
   try {
      if (this.cred instanceof SAMLHolderOfKeyToken && StringUtils.isNotEmpty(this.assertionId)) {
         this.sign.setSignatureAlgorithm("http://www.w3.org/2000/09/xmldsig#rsa-sha1");
         this.sign.setKeyIdentifierType(12);
         this.sign.setCustomTokenValueType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID");
         this.sign.setCustomTokenId(this.assertionId);
      } else {
         this.sign.setKeyIdentifierType(1);
      }

      Crypto crypto = new WSSecurityCrypto(this.cred.getPrivateKey(), this.cred.getCertificate());
      this.sign.prepare(this.soapPart, crypto, this.wsSecHeader);
      if (!(this.cred instanceof SAMLHolderOfKeyToken) || !StringUtils.isNotEmpty(this.assertionId)) {
         this.sign.appendBSTElementToHeader(this.wsSecHeader);
      }

      List<Reference> referenceList = this.sign.addReferencesToSign(this.generateReferencesToSign(parts), this.wsSecHeader);
      if (!referenceList.isEmpty()) {
         this.sign.computeSignature(referenceList, false, (Element)null);
      }

   } catch (WSSecurityException var4) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.HANDLER_ERROR, new Object[]{"unable to insert security header.", var4});
   }
}
 
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: WSSecHeaderGeneratorWss4jImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void sign(AbstractWsSecurityHandler.SignedParts... parts) throws TechnicalConnectorException {
   try {
      if (StringUtils.isNotEmpty(this.assertionId)) {
         this.sign.setSignatureAlgorithm("http://www.w3.org/2000/09/xmldsig#rsa-sha1");
         this.sign.setKeyIdentifierType(12);
         this.sign.setCustomTokenValueType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID");
         this.sign.setCustomTokenId(this.assertionId);
      } else {
         this.sign.setKeyIdentifierType(1);
      }

      Crypto crypto = new WSSecurityCrypto(this.cred.getPrivateKey(), this.cred.getCertificate());
      this.sign.prepare(this.soapPart, crypto, this.wsSecHeader);
      if (StringUtils.isEmpty(this.assertionId)) {
         this.sign.appendBSTElementToHeader(this.wsSecHeader);
      }

      List<Reference> referenceList = this.sign.addReferencesToSign(this.generateReferencesToSign(parts), this.wsSecHeader);
      if (!referenceList.isEmpty()) {
         this.sign.computeSignature(referenceList, false, (Element)null);
      }

   } catch (WSSecurityException var4) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.HANDLER_ERROR, new Object[]{"unable to insert security header.", var4});
   }
}
 
Example #10
Source File: WSSecHeaderGeneratorWss4jImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void sign(AbstractWsSecurityHandler.SignedParts... parts) throws TechnicalConnectorException {
   try {
      if (StringUtils.isNotEmpty(this.assertionId)) {
         this.sign.setSignatureAlgorithm("http://www.w3.org/2000/09/xmldsig#rsa-sha1");
         this.sign.setKeyIdentifierType(12);
         this.sign.setCustomTokenValueType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID");
         this.sign.setCustomTokenId(this.assertionId);
      } else {
         this.sign.setKeyIdentifierType(1);
      }

      Crypto crypto = new WSSecurityCrypto(this.cred.getPrivateKey(), this.cred.getCertificate());
      this.sign.prepare(this.soapPart, crypto, this.wsSecHeader);
      if (StringUtils.isEmpty(this.assertionId)) {
         this.sign.appendBSTElementToHeader(this.wsSecHeader);
      }

      List<Reference> referenceList = this.sign.addReferencesToSign(this.generateReferencesToSign(parts), this.wsSecHeader);
      if (!referenceList.isEmpty()) {
         this.sign.computeSignature(referenceList, false, (Element)null);
      }

   } catch (WSSecurityException var4) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.HANDLER_ERROR, new Object[]{"unable to insert security header.", var4});
   }
}
 
Example #11
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 #12
Source File: WSSecHeaderGeneratorWss4jImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void sign(AbstractWsSecurityHandler.SignedParts... parts) throws TechnicalConnectorException {
   try {
      if (this.cred instanceof SAMLHolderOfKeyToken && StringUtils.isNotEmpty(this.assertionId)) {
         this.sign.setSignatureAlgorithm("http://www.w3.org/2000/09/xmldsig#rsa-sha1");
         this.sign.setKeyIdentifierType(12);
         this.sign.setCustomTokenValueType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID");
         this.sign.setCustomTokenId(this.assertionId);
      } else {
         this.sign.setKeyIdentifierType(1);
      }

      Crypto crypto = new WSSecurityCrypto(this.cred.getPrivateKey(), this.cred.getCertificate());
      this.sign.prepare(this.soapPart, crypto, this.wsSecHeader);
      if (!(this.cred instanceof SAMLHolderOfKeyToken) || !StringUtils.isNotEmpty(this.assertionId)) {
         this.sign.appendBSTElementToHeader(this.wsSecHeader);
      }

      List<Reference> referenceList = this.sign.addReferencesToSign(this.generateReferencesToSign(parts), this.wsSecHeader);
      if (!referenceList.isEmpty()) {
         this.sign.computeSignature(referenceList, false, (Element)null);
      }

   } catch (WSSecurityException var4) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.HANDLER_ERROR, new Object[]{"unable to insert security header.", var4});
   }
}
 
Example #13
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 #14
Source File: WSSecHeaderGeneratorWss4jImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void sign(AbstractWsSecurityHandler.SignedParts... parts) throws TechnicalConnectorException {
   try {
      if (this.cred instanceof SAMLHolderOfKeyToken && StringUtils.isNotEmpty(this.assertionId)) {
         this.sign.setSignatureAlgorithm("http://www.w3.org/2000/09/xmldsig#rsa-sha1");
         this.sign.setKeyIdentifierType(12);
         this.sign.setCustomTokenValueType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID");
         this.sign.setCustomTokenId(this.assertionId);
      } else {
         this.sign.setKeyIdentifierType(1);
      }

      Crypto crypto = new WSSecurityCrypto(this.cred.getPrivateKey(), this.cred.getCertificate());
      this.sign.prepare(this.soapPart, crypto, this.wsSecHeader);
      if (!(this.cred instanceof SAMLHolderOfKeyToken) || !StringUtils.isNotEmpty(this.assertionId)) {
         this.sign.appendBSTElementToHeader(this.wsSecHeader);
      }

      List<Reference> referenceList = this.sign.addReferencesToSign(this.generateReferencesToSign(parts), this.wsSecHeader);
      if (!referenceList.isEmpty()) {
         this.sign.computeSignature(referenceList, false, (Element)null);
      }

   } catch (WSSecurityException var4) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.HANDLER_ERROR, new Object[]{"unable to insert security header.", var4});
   }
}
 
Example #15
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 #16
Source File: XmlSignature.java    From cstc with GNU General Public License v3.0 5 votes vote down vote up
protected void createSignature(Document document) throws Exception {
  String signMethod = (String)signatureMethod.getSelectedItem();
  PrivateKeyEntry keyEntry = this.selectedEntry;

  if( this.multiSignature )
    this.validateIdAttributes(document);
  ArrayList<Reference> references = this.getReferences();
  SignedInfo signatureInfo = signatureFac.newSignedInfo(signatureFac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec)null), signatureFac.newSignatureMethod(signatureMethods.get(signMethod), null), references);
  KeyInfo keyInfo = this.getKeyInfo();
  XMLSignature signature = signatureFac.newXMLSignature(signatureInfo, keyInfo);

  DOMSignContext dsc = new DOMSignContext (keyEntry.getPrivateKey(), document.getDocumentElement()); 
  signature.sign(dsc);
}
 
Example #17
Source File: XML.java    From restcommander with Apache License 2.0 5 votes vote down vote up
/**
 * Sign the XML document using xmldsig.
 * @param document the document to sign; it will be modified by the method.
 * @param publicKey the public key from the key pair to sign the document.
 * @param privateKey the private key from the key pair to sign the document.
 * @return the signed document for chaining.
 */
public static Document sign(Document document, RSAPublicKey publicKey, RSAPrivateKey privateKey) {
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
    KeyInfoFactory keyInfoFactory = fac.getKeyInfoFactory();

    try {
        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));
        DOMSignContext dsc = new DOMSignContext(privateKey, document.getDocumentElement());
        KeyValue keyValue = keyInfoFactory.newKeyValue(publicKey);
        KeyInfo ki = keyInfoFactory.newKeyInfo(Collections.singletonList(keyValue));
        XMLSignature signature = fac.newXMLSignature(si, ki);
        signature.sign(dsc);
    } catch (Exception e) {
        Logger.warn("Error while signing an XML document.", e);
    }

    return document;
}
 
Example #18
Source File: XmlSignatureApplet.java    From juddi with Apache License 2.0 5 votes vote down vote up
private SignedInfo initSignedInfo(XMLSignatureFactory fac) throws Exception {
    Reference ref = initReference(fac);
    SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
            (C14NMethodParameterSpec) null),
            fac.newSignatureMethod(SignatureMethod.RSA_SHA1,
            null),
            Collections.singletonList(ref));
    return si;
}
 
Example #19
Source File: XmlSignatureApplet.java    From juddi with Apache License 2.0 5 votes vote down vote up
private Reference initReference(XMLSignatureFactory fac) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    List transformers = new ArrayList();
    transformers.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));

    //  String dm = map.getProperty(SIGNATURE_OPTION_DIGEST_METHOD);
    //if (dm == null) {
    String dm = DigestMethod.SHA1;
    //}
    Reference ref = fac.newReference("", fac.newDigestMethod(dm, null), transformers, null, null);
    return ref;
}
 
Example #20
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 #21
Source File: DigSigUtil.java    From juddi with Apache License 2.0 5 votes vote down vote up
private Reference initReference(XMLSignatureFactory fac) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
        List transformers = new ArrayList();
        transformers.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));

        String dm = map.getProperty(SIGNATURE_OPTION_DIGEST_METHOD);
        if (dm == null) {
                dm = DigestMethod.SHA1;
        }
        Reference ref = fac.newReference("", fac.newDigestMethod(dm, null), transformers, null, null);
        return ref;
}
 
Example #22
Source File: XMLHelpers.java    From SAMLRaider with MIT License 5 votes vote down vote up
/**
 * Validates if the first XML Signature of the given document is valid
 * Only used for test purposes
 *
 * @param document
 *            Document with signature to validate
 * @return true if valid, else false
 */
public boolean validateSignature(Document document) throws Exception {

	setIDAttribute(document);
	XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

	// Find Signature element.
	NodeList nl = document.getElementsByTagNameNS(javax.xml.crypto.dsig.XMLSignature.XMLNS, "Signature");
	if (nl.getLength() == 0) {
		throw new Exception("Cannot find Signature element");
	}

	// Create a DOMValidateContext and specify a KeySelector
	// and document context.
	DOMValidateContext valContext = new DOMValidateContext(new X509KeySelector(), nl.item(0));

	// Unmarshal the XMLSignature
	javax.xml.crypto.dsig.XMLSignature signature = fac.unmarshalXMLSignature(valContext);

	// Validate the XMLSignature.
	boolean coreValidity = signature.validate(valContext);

	// Check core validation status.
	if (coreValidity == false) {
		boolean sv = signature.getSignatureValue().validate(valContext);
		if (sv == false) {
			if(Flags.DEBUG){
				// Check the validation status of each Reference.
				@SuppressWarnings("rawtypes")
				Iterator i = signature.getSignedInfo().getReferences().iterator();
				for (int j = 0; i.hasNext(); j++) {
					boolean refValid = ((Reference) i.next()).validate(valContext);
					System.out.println("ref[" + j + "] validity status: " + refValid);
				}
			}
		}
	}
	return coreValidity;
}
 
Example #23
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 #24
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 #25
Source File: SoapMultiSignature.java    From cstc with GNU General Public License v3.0 5 votes vote down vote up
protected byte[] perform(byte[] input) throws Exception {

      String signMethod = (String)signatureMethod.getSelectedItem();
      PrivateKeyEntry keyEntry = this.selectedEntry;

      XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
      ArrayList<Reference> references = getReferences(fac);
      SignedInfo signatureInfo = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec)null), fac.newSignatureMethod(signatureMethods.get(signMethod), null), references);
      KeyInfo keyInfo = this.getKeyInfo(fac, keyEntry);
      XMLSignature signature = fac.newXMLSignature(signatureInfo, keyInfo);

      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setNamespaceAware(true);
      Document doc = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(input));
      try {
        validateIdAttributes(doc);
      } catch( Exception e ) {
        throw new IllegalArgumentException("Provided Id identifier seems to be invalid.");
      }
      DOMSignContext dsc = new DOMSignContext (keyEntry.getPrivateKey(), doc.getDocumentElement()); 
      signature.sign(dsc);

      DOMSource source = new DOMSource(doc);
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      StreamResult result = new StreamResult(bos);
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      transformer.transform(source, result);
      return bos.toByteArray();
	}
 
Example #26
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 #27
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 Exception {
    // 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(); 
    PublicKey pub = getPublicKey("C:\\work\\fhirserver\\tests\\signatures\\public_key.der");
    PrivateKey priv = getPrivateKey("C:\\work\\fhirserver\\tests\\signatures\\private_key.der");
    
    // sign the document
    DOMSignContext dsc = new DOMSignContext(priv, 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(pub);
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
    XMLSignature signature = fac.newXMLSignature(si, ki); 
    signature.sign(dsc);
    
    OutputStream os = new FileOutputStream("c:\\temp\\java-digsig.xml");
    new XmlGenerator().generate(doc.getDocumentElement(), os);
  }
 
Example #28
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 Exception {
    // 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(); 
    PublicKey pub = getPublicKey("C:\\work\\fhirserver\\tests\\signatures\\public_key.der");
    PrivateKey priv = getPrivateKey("C:\\work\\fhirserver\\tests\\signatures\\private_key.der");
    
    // sign the document
    DOMSignContext dsc = new DOMSignContext(priv, 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(pub);
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
    XMLSignature signature = fac.newXMLSignature(si, ki); 
    signature.sign(dsc);
    
    OutputStream os = new FileOutputStream("c:\\temp\\java-digsig.xml");
    new XmlGenerator().generate(doc.getDocumentElement(), os);
  }
 
Example #29
Source File: MetadataWriter.java    From cxf with Apache License 2.0 4 votes vote down vote up
private static Document signMetaInfo(X509Certificate signingCert, Key signingKey,
                                     Document doc, String referenceID
) throws Exception {
    String signatureMethod = null;
    if ("SHA1withDSA".equals(signingCert.getSigAlgName())) {
        signatureMethod = SignatureMethod.DSA_SHA1;
    } else if ("SHA1withRSA".equals(signingCert.getSigAlgName())) {
        signatureMethod = SignatureMethod.RSA_SHA1;
    } else if ("SHA256withRSA".equals(signingCert.getSigAlgName())) {
        signatureMethod = SignatureMethod.RSA_SHA1;
    } else {
        LOG.error("Unsupported signature method: " + signingCert.getSigAlgName());
        throw new RuntimeException("Unsupported signature method: " + signingCert.getSigAlgName());
    }

    List<Transform> transformList = new ArrayList<>();
    transformList.add(XML_SIGNATURE_FACTORY.newTransform(Transform.ENVELOPED, (TransformParameterSpec)null));
    transformList.add(XML_SIGNATURE_FACTORY.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
                                                                      (C14NMethodParameterSpec)null));

    // Create a Reference to the enveloped document (in this case,
    // you are signing the whole document, so a URI of "" signifies
    // that, and also specify the SHA1 digest algorithm and
    // the ENVELOPED Transform.
    Reference ref =
        XML_SIGNATURE_FACTORY.newReference("#" + referenceID,
                                           XML_SIGNATURE_FACTORY.newDigestMethod(DigestMethod.SHA1, null),
                                           transformList,
                                           null, null);

    // Create the SignedInfo.
    SignedInfo si =
        XML_SIGNATURE_FACTORY.newSignedInfo(
            XML_SIGNATURE_FACTORY.newCanonicalizationMethod(
                CanonicalizationMethod.EXCLUSIVE,
                (C14NMethodParameterSpec)null),
                XML_SIGNATURE_FACTORY.newSignatureMethod(signatureMethod, null),
                 Collections.singletonList(ref));

    // Create the KeyInfo containing the X509Data.
    KeyInfoFactory kif = XML_SIGNATURE_FACTORY.getKeyInfoFactory();
    List<Object> x509Content = new ArrayList<>();
    x509Content.add(signingCert.getSubjectX500Principal().getName());
    x509Content.add(signingCert);
    X509Data xd = kif.newX509Data(x509Content);
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));

    // Create a DOMSignContext and specify the RSA PrivateKey and
    // location of the resulting XMLSignature's parent element.
    //DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement());
    DOMSignContext dsc = new DOMSignContext(signingKey, doc.getDocumentElement());
    dsc.setIdAttributeNS(doc.getDocumentElement(), null, "ID");
    dsc.setNextSibling(doc.getDocumentElement().getFirstChild());

    // Create the XMLSignature, but don't sign it yet.
    XMLSignature signature = XML_SIGNATURE_FACTORY.newXMLSignature(si, ki);

    // Marshal, generate, and sign the enveloped signature.
    signature.sign(dsc);

    // Output the resulting document.
    return doc;
}
 
Example #30
Source File: AbstractBindingBuilder.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void doSymmSignature(AbstractToken policyToken, SecurityToken tok,
                                     List<WSEncryptionPart> sigParts,
                                     boolean isSigProtect)
    throws WSSecurityException {

    WSSecSignature sig = new WSSecSignature(secHeader);
    sig.setIdAllocator(wssConfig.getIdAllocator());
    sig.setCallbackLookup(callbackLookup);
    sig.setAttachmentCallbackHandler(new AttachmentCallbackHandler(message));
    sig.setStoreBytesInAttachment(storeBytesInAttachment);
    sig.setExpandXopInclude(isExpandXopInclude());
    sig.setWsDocInfo(wsDocInfo);

    // If a EncryptedKeyToken is used, set the correct value type to
    // be used in the wsse:Reference in ds:KeyInfo
    if (policyToken instanceof X509Token) {
        if (isRequestor()) {
            // TODO Add support for SAML2 here
            sig.setCustomTokenValueType(
                WSS4JConstants.SOAPMESSAGE_NS11 + "#" + WSS4JConstants.ENC_KEY_VALUE_TYPE
            );
            sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
        } else {
            //the tok has to be an EncryptedKey token
            sig.setEncrKeySha1value(tok.getSHA1());
            sig.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
        }

    } else {
        String tokenType = tok.getTokenType();
        if (WSS4JConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType)
            || WSS4JConstants.SAML_NS.equals(tokenType)) {
            sig.setCustomTokenValueType(WSS4JConstants.WSS_SAML_KI_VALUE_TYPE);
        } else if (WSS4JConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType)
            || WSS4JConstants.SAML2_NS.equals(tokenType)) {
            sig.setCustomTokenValueType(WSS4JConstants.WSS_SAML2_KI_VALUE_TYPE);
        } else if (tokenType != null) {
            sig.setCustomTokenValueType(tokenType);
        } else if (policyToken instanceof UsernameToken) {
            sig.setCustomTokenValueType(WSS4JConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
        } else {
            sig.setCustomTokenValueType(WSS4JConstants.WSS_SAML_KI_VALUE_TYPE);
        }
        sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
    }

    String sigTokId = tok.getWsuId();
    if (sigTokId == null) {
        sigTokId = tok.getId();
    }

    sigTokId = XMLUtils.getIDFromReference(sigTokId);
    sig.setCustomTokenId(sigTokId);
    sig.setSecretKey(tok.getSecret());
    sig.setSignatureAlgorithm(binding.getAlgorithmSuite().getAlgorithmSuiteType().getSymmetricSignature());
    AlgorithmSuiteType algType = binding.getAlgorithmSuite().getAlgorithmSuiteType();
    sig.setDigestAlgo(algType.getDigest());
    sig.setSigCanonicalization(binding.getAlgorithmSuite().getC14n().getValue());
    sig.prepare(getSignatureCrypto());

    sig.getParts().addAll(sigParts);
    List<Reference> referenceList = sig.addReferencesToSign(sigParts);

    //Do signature
    sig.computeSignature(referenceList, false, null);

    if (isSigProtect) {
        WSEncryptionPart part = new WSEncryptionPart(sig.getId(), "Element");
        encryptedTokensList.add(part);
    }

    addSig(sig.getSignatureValue());
}