Java Code Examples for javax.xml.crypto.dsig.XMLSignatureFactory#getInstance()

The following examples show how to use javax.xml.crypto.dsig.XMLSignatureFactory#getInstance() . 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: XML.java    From restcommander with Apache License 2.0 6 votes vote down vote up
/**
 * Check the xmldsig signature of the XML document.
 * @param document the document to test
 * @param publicKey the public key corresponding to the key pair the document was signed with
 * @return true if a correct signature is present, false otherwise
 */
public static boolean validSignature(Document document, Key publicKey) {
    Node signatureNode =  document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature").item(0);
    KeySelector keySelector = KeySelector.singletonKeySelector(publicKey);

    try {
        String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance());
        DOMValidateContext valContext = new DOMValidateContext(keySelector, signatureNode);

        XMLSignature signature = fac.unmarshalXMLSignature(valContext);
        return signature.validate(valContext);
    } catch (Exception e) {
        Logger.warn("Error validating an XML signature.", e);
        return false;
    }
}
 
Example 4
Source File: XMLSignatureUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static XMLSignatureFactory getXMLSignatureFactory() {
    XMLSignatureFactory xsf = null;

    try {
        xsf = XMLSignatureFactory.getInstance("DOM", "ApacheXMLDSig");
    } catch (NoSuchProviderException ex) {
        try {
            xsf = XMLSignatureFactory.getInstance("DOM");
        } catch (Exception err) {
            throw new RuntimeException(logger.couldNotCreateInstance("DOM", err));
        }
    }
    return xsf;
}
 
Example 5
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 6
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 7
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 8
Source File: XMLDSigVerifier.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
XMLSignature getValidXMLSignature(InputStream fileStream)
        throws ParserConfigurationException,
        IOException,
        SAXException,
        MarshalException,
        XMLSignatureException,
        DOMException
{
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    dbFactory.setNamespaceAware(true);
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document xml = dBuilder.parse(fileStream);
    xml.getDocumentElement().normalize();

    // Find Signature element
    NodeList nl = xml.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0)
    {
        throw new DOMException(DOMException.INDEX_SIZE_ERR, "Missing elements");
    }

    // Create a DOM XMLSignatureFactory that will be used to unmarshal the
    // document containing the XMLSignature
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

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

    // unmarshal the XMLSignature
    XMLSignature signature = fac.unmarshalXMLSignature(valContext);

    boolean validSig = signature.validate(valContext);
    if(!validSig)
    {
        throw new XMLSignatureException("Invalid XML signature");
    }
    return signature;
}
 
Example 9
Source File: ErrorHandlerPermissions.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
    Document doc = dbf.newDocumentBuilder().parse(new File(SIGNATURE));
    NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS,
            "Signature");
    if (nl.getLength() == 0) {
        throw new RuntimeException("Couldn't find 'Signature' element");
    }
    Element element = (Element) nl.item(0);

    byte[] keyBytes = Base64.getDecoder().decode(validationKey);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey key = kf.generatePublic(spec);
    KeySelector ks = KeySelector.singletonKeySelector(key);

    DOMValidateContext vc = new DOMValidateContext(ks, element);

    // disable secure validation mode
    vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

    // set a dummy dereferencer to be able to get content by references
    vc.setURIDereferencer(dereferencer);

    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    XMLSignature signature = factory.unmarshalXMLSignature(vc);

    // run validation
    signature.validate(vc);
}
 
Example 10
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 11
Source File: RequestSigner.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public RequestSigner ( final Configuration configuration ) throws Exception
{
    this.fac = XMLSignatureFactory.getInstance ( "DOM" );
    this.md = this.fac.newDigestMethod ( configuration.getDigestMethod (), null );
    this.kif = this.fac.getKeyInfoFactory ();

    this.t = this.fac.newTransform ( Transform.ENVELOPED, (TransformParameterSpec)null );
    this.ref = this.fac.newReference ( "", this.md, Collections.singletonList ( this.t ), null, null );
    this.cm = this.fac.newCanonicalizationMethod ( CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec)null );
}
 
Example 12
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 13
Source File: ErrorHandlerPermissions.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
    Document doc = dbf.newDocumentBuilder().parse(new File(SIGNATURE));
    NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS,
            "Signature");
    if (nl.getLength() == 0) {
        throw new RuntimeException("Couldn't find 'Signature' element");
    }
    Element element = (Element) nl.item(0);

    byte[] keyBytes = Base64.getDecoder().decode(validationKey);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey key = kf.generatePublic(spec);
    KeySelector ks = KeySelector.singletonKeySelector(key);

    DOMValidateContext vc = new DOMValidateContext(ks, element);

    // disable secure validation mode
    vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

    // set a dummy dereferencer to be able to get content by references
    vc.setURIDereferencer(dereferencer);

    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    XMLSignature signature = factory.unmarshalXMLSignature(vc);

    // run validation
    signature.validate(vc);
}
 
Example 14
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 15
Source File: ErrorHandlerPermissions.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
    Document doc = dbf.newDocumentBuilder().parse(new File(SIGNATURE));
    NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS,
            "Signature");
    if (nl.getLength() == 0) {
        throw new RuntimeException("Couldn't find 'Signature' element");
    }
    Element element = (Element) nl.item(0);

    byte[] keyBytes = Base64.getDecoder().decode(validationKey);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey key = kf.generatePublic(spec);
    KeySelector ks = KeySelector.singletonKeySelector(key);

    DOMValidateContext vc = new DOMValidateContext(ks, element);

    // disable secure validation mode
    vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

    // set a dummy dereferencer to be able to get content by references
    vc.setURIDereferencer(dereferencer);

    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    XMLSignature signature = factory.unmarshalXMLSignature(vc);

    // run validation
    signature.validate(vc);
}
 
Example 16
Source File: RequestValidator.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public RequestValidator ( final KeySelector keySelector )
{
    this.factory = XMLSignatureFactory.getInstance ( "DOM" ); //$NON-NLS-1$
    this.keySelector = keySelector;
}
 
Example 17
Source File: TckSigningUtil.java    From juddi with Apache License 2.0 4 votes vote down vote up
private static XMLSignatureFactory initXMLSigFactory() {
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance();
    return fac;
}
 
Example 18
Source File: SamlUtils.java    From cas4.0.x-server-wechat with Apache License 2.0 4 votes vote down vote up
private static Element signSamlElement(final Element element, final PrivateKey privKey,
        final PublicKey pubKey) {
    try {
        final String providerName = System.getProperty("jsr105Provider",
                JSR_105_PROVIDER);
        final XMLSignatureFactory sigFactory = XMLSignatureFactory
                .getInstance("DOM", (Provider) Class.forName(providerName)
                        .newInstance());

        final List envelopedTransform = Collections
                .singletonList(sigFactory.newTransform(Transform.ENVELOPED,
                        (TransformParameterSpec) null));

        final Reference ref = sigFactory.newReference("", sigFactory
                .newDigestMethod(DigestMethod.SHA1, null), envelopedTransform,
                null, null);

        // Create the SignatureMethod based on the type of key
        SignatureMethod signatureMethod;
        if (pubKey instanceof DSAPublicKey) {
            signatureMethod = sigFactory.newSignatureMethod(
                    SignatureMethod.DSA_SHA1, null);
        } else if (pubKey instanceof RSAPublicKey) {
            signatureMethod = sigFactory.newSignatureMethod(
                    SignatureMethod.RSA_SHA1, null);
        } else {
            throw new RuntimeException(
                    "Error signing SAML element: Unsupported type of key");
        }

        final CanonicalizationMethod canonicalizationMethod = sigFactory
                .newCanonicalizationMethod(
                        CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                        (C14NMethodParameterSpec) null);

        // Create the SignedInfo
        final SignedInfo signedInfo = sigFactory.newSignedInfo(
                canonicalizationMethod, signatureMethod, Collections
                .singletonList(ref));

        // Create a KeyValue containing the DSA or RSA PublicKey
        final KeyInfoFactory keyInfoFactory = sigFactory
                .getKeyInfoFactory();
        final KeyValue keyValuePair = keyInfoFactory.newKeyValue(pubKey);

        // Create a KeyInfo and add the KeyValue to it
        final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections
                .singletonList(keyValuePair));
        // Convert the JDOM document to w3c (Java XML signature API requires
        // w3c
        // representation)
        org.w3c.dom.Element w3cElement = toDom(element);

        // Create a DOMSignContext and specify the DSA/RSA PrivateKey and
        // location of the resulting XMLSignature's parent element
        DOMSignContext dsc = new DOMSignContext(privKey, w3cElement);

        org.w3c.dom.Node xmlSigInsertionPoint = getXmlSignatureInsertLocation(w3cElement);
        dsc.setNextSibling(xmlSigInsertionPoint);

        // Marshal, generate (and sign) the enveloped signature
        XMLSignature signature = sigFactory.newXMLSignature(signedInfo,
                keyInfo);
        signature.sign(dsc);

        return toJdom(w3cElement);

    } catch (final Exception e) {
        throw new RuntimeException("Error signing SAML element: "
                + e.getMessage(), e);
    }
}
 
Example 19
Source File: DigSigUtil.java    From juddi with Apache License 2.0 4 votes vote down vote up
private XMLSignatureFactory initXMLSigFactory() {
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance();
        return fac;
}
 
Example 20
Source File: XmlSignatureApplet.java    From juddi with Apache License 2.0 4 votes vote down vote up
private XMLSignatureFactory initXMLSigFactory() {
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance();
    return fac;
}