Search in sources :

Example 1 with TransformParameterSpec

use of javax.xml.crypto.dsig.spec.TransformParameterSpec in project cas by apereo.

the class AbstractSamlObjectBuilder method signSamlElement.

/**
 * Sign SAML element.
 *
 * @param element the element
 * @param privKey the priv key
 * @param pubKey  the pub key
 * @return the element
 */
private static org.jdom.Element signSamlElement(final org.jdom.Element element, final PrivateKey privKey, final PublicKey pubKey) {
    try {
        final String providerName = System.getProperty("jsr105Provider", SIGNATURE_FACTORY_PROVIDER_CLASS);
        final Class<?> clazz = Class.forName(providerName);
        final XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance("DOM", (Provider) clazz.getDeclaredConstructor().newInstance());
        final List<Transform> envelopedTransform = CollectionUtils.wrap(sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
        final Reference ref = sigFactory.newReference(StringUtils.EMPTY, sigFactory.newDigestMethod(DigestMethod.SHA1, null), envelopedTransform, null, null);
        // Create the SignatureMethod based on the type of key
        final SignatureMethod signatureMethod;
        final String algorithm = pubKey.getAlgorithm();
        switch(algorithm) {
            case "DSA":
                signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null);
                break;
            case "RSA":
                signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
                break;
            default:
                throw new IllegalArgumentException("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, CollectionUtils.wrap(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(CollectionUtils.wrap(keyValuePair));
        // Convert the JDOM document to w3c (Java XML signature API requires w3c representation)
        final Element w3cElement = toDom(element);
        // Create a DOMSignContext and specify the DSA/RSA PrivateKey and
        // location of the resulting XMLSignature's parent element
        final DOMSignContext dsc = new DOMSignContext(privKey, w3cElement);
        final Node xmlSigInsertionPoint = getXmlSignatureInsertLocation(w3cElement);
        dsc.setNextSibling(xmlSigInsertionPoint);
        // Marshal, generate (and sign) the enveloped signature
        final XMLSignature signature = sigFactory.newXMLSignature(signedInfo, keyInfo);
        signature.sign(dsc);
        return toJdom(w3cElement);
    } catch (final Exception e) {
        throw new IllegalArgumentException("Error signing SAML element: " + e.getMessage(), e);
    }
}
Also used : XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) KeyValue(javax.xml.crypto.dsig.keyinfo.KeyValue) Reference(javax.xml.crypto.dsig.Reference) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) CanonicalizationMethod(javax.xml.crypto.dsig.CanonicalizationMethod) SignedInfo(javax.xml.crypto.dsig.SignedInfo) KeyInfoFactory(javax.xml.crypto.dsig.keyinfo.KeyInfoFactory) KeyInfo(javax.xml.crypto.dsig.keyinfo.KeyInfo) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) XMLSignature(javax.xml.crypto.dsig.XMLSignature) TransformParameterSpec(javax.xml.crypto.dsig.spec.TransformParameterSpec) SignatureMethod(javax.xml.crypto.dsig.SignatureMethod) Transform(javax.xml.crypto.dsig.Transform)

Example 2 with TransformParameterSpec

use of javax.xml.crypto.dsig.spec.TransformParameterSpec in project santuario-java by apache.

the class TransformTest method testisFeatureSupported.

@org.junit.Test
public void testisFeatureSupported() throws Exception {
    Transform tm;
    for (int i = 0; i < TRANSFORM_ALGOS.length; i++) {
        String algo = TRANSFORM_ALGOS[i];
        TransformParameterSpec params = null;
        if (algo.equals(Transform.XPATH)) {
            params = new XPathFilterParameterSpec("xPath");
        } else if (algo.equals(Transform.XPATH2)) {
            params = new XPathFilter2ParameterSpec(Collections.singletonList(new XPathType("xPath2", XPathType.Filter.INTERSECT)));
        } else if (algo.equals(Transform.XSLT)) {
            params = new XSLTTransformParameterSpec(new XSLTStructure());
        }
        tm = factory.newTransform(algo, params);
        try {
            tm.isFeatureSupported(null);
            fail(TRANSFORM_ALGOS[i] + ": Should raise a NPE for null feature");
        } catch (NullPointerException npe) {
        }
        assertTrue(!tm.isFeatureSupported("not supported"));
    }
}
Also used : XPathType(javax.xml.crypto.dsig.spec.XPathType) XSLTTransformParameterSpec(javax.xml.crypto.dsig.spec.XSLTTransformParameterSpec) XPathFilterParameterSpec(javax.xml.crypto.dsig.spec.XPathFilterParameterSpec) XSLTTransformParameterSpec(javax.xml.crypto.dsig.spec.XSLTTransformParameterSpec) TransformParameterSpec(javax.xml.crypto.dsig.spec.TransformParameterSpec) XPathFilter2ParameterSpec(javax.xml.crypto.dsig.spec.XPathFilter2ParameterSpec)

Example 3 with TransformParameterSpec

use of javax.xml.crypto.dsig.spec.TransformParameterSpec in project cxf by apache.

the class MetadataWriter method signMetaInfo.

private static Document signMetaInfo(X509Certificate signingCert, Key signingKey, Document doc, String referenceID) throws Exception {
    final String signatureMethod;
    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 = Arrays.asList(XML_SIGNATURE_FACTORY.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null), 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 = Arrays.asList(signingCert.getSubjectX500Principal().getName(), 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;
}
Also used : Reference(javax.xml.crypto.dsig.Reference) X509Data(javax.xml.crypto.dsig.keyinfo.X509Data) SignedInfo(javax.xml.crypto.dsig.SignedInfo) KeyInfoFactory(javax.xml.crypto.dsig.keyinfo.KeyInfoFactory) KeyInfo(javax.xml.crypto.dsig.keyinfo.KeyInfo) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) XMLSignature(javax.xml.crypto.dsig.XMLSignature) TransformParameterSpec(javax.xml.crypto.dsig.spec.TransformParameterSpec) Transform(javax.xml.crypto.dsig.Transform) C14NMethodParameterSpec(javax.xml.crypto.dsig.spec.C14NMethodParameterSpec)

Example 4 with TransformParameterSpec

use of javax.xml.crypto.dsig.spec.TransformParameterSpec in project testcases by coheigea.

the class SignatureJSR105EnvelopedTest method testSignatureUsingJSR105.

// Sign + Verify an XML Document using the JSR-105 API
@org.junit.Test
public void testSignatureUsingJSR105() throws Exception {
    // Read in plaintext document
    InputStream sourceDocument = this.getClass().getClassLoader().getResourceAsStream("plaintext.xml");
    DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
    Document document = builder.parse(sourceDocument);
    // Set up the Key
    KeyStore keyStore = KeyStore.getInstance("jks");
    keyStore.load(this.getClass().getClassLoader().getResource("clientstore.jks").openStream(), "cspass".toCharArray());
    Key key = keyStore.getKey("myclientkey", "ckpass".toCharArray());
    X509Certificate cert = (X509Certificate) keyStore.getCertificate("myclientkey");
    String signatureId = "_" + UUID.randomUUID().toString();
    String signaturePropertyId = "_" + UUID.randomUUID().toString();
    // Sign using DOM
    XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");
    CanonicalizationMethod c14nMethod = signatureFactory.newCanonicalizationMethod("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec) null);
    KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory();
    X509Data x509Data = keyInfoFactory.newX509Data(Collections.singletonList(cert));
    javax.xml.crypto.dsig.keyinfo.KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data));
    SignatureMethod signatureMethod = signatureFactory.newSignatureMethod("http://www.w3.org/2000/09/xmldsig#rsa-sha1", null);
    Transform transform = signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
    DigestMethod digestMethod = signatureFactory.newDigestMethod("http://www.w3.org/2000/09/xmldsig#sha1", null);
    Reference reference = signatureFactory.newReference("", digestMethod, Collections.singletonList(transform), null, null);
    Transform objectTransform = signatureFactory.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", (TransformParameterSpec) null);
    Reference objectReference = signatureFactory.newReference("#" + signaturePropertyId, digestMethod, Collections.singletonList(objectTransform), "http://www.w3.org/2000/09/xmldsig#SignatureProperties", null);
    List<Reference> references = new ArrayList<>();
    references.add(reference);
    references.add(objectReference);
    SignedInfo signedInfo = signatureFactory.newSignedInfo(c14nMethod, signatureMethod, references);
    // Add a SignatureProperty containing a Timestamp
    Element timestamp = document.createElementNS(null, "Timestamp");
    timestamp.setTextContent(new Date().toString());
    XMLStructure content = new DOMStructure(timestamp);
    SignatureProperty signatureProperty = signatureFactory.newSignatureProperty(Collections.singletonList(content), "#" + signatureId, signaturePropertyId);
    SignatureProperties signatureProperties = signatureFactory.newSignatureProperties(Collections.singletonList(signatureProperty), null);
    XMLObject object = signatureFactory.newXMLObject(Collections.singletonList(signatureProperties), null, null, null);
    XMLSignature sig = signatureFactory.newXMLSignature(signedInfo, keyInfo, Collections.singletonList(object), signatureId, null);
    XMLSignContext signContext = new DOMSignContext(key, document.getDocumentElement());
    sig.sign(signContext);
    // XMLUtils.outputDOM(document, System.out);
    // Verify using JSR-105
    // Find the Signature Element
    Element sigElement = SignatureUtils.getSignatureElement(document);
    Assert.assertNotNull(sigElement);
    XMLValidateContext context = new DOMValidateContext(cert.getPublicKey(), sigElement);
    context.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
    context.setProperty("org.apache.jcp.xml.dsig.secureValidation", Boolean.TRUE);
    context.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.TRUE);
    signatureFactory = XMLSignatureFactory.getInstance("DOM");
    XMLSignature xmlSignature = signatureFactory.unmarshalXMLSignature(context);
    // Check the Signature value
    Assert.assertTrue(xmlSignature.validate(context));
    // First find the Timestamp
    SignatureProperty timestampSignatureProperty = getTimestampSignatureProperty(xmlSignature);
    assertNotNull(timestampSignatureProperty);
    // Check that what was signed is what we expected to be signed.
    boolean foundEnvelopedSig = false;
    boolean foundSignedTimestamp = false;
    for (Object refObject : signedInfo.getReferences()) {
        Reference ref = (Reference) refObject;
        if ("".equals(ref.getURI())) {
            List<Transform> transforms = (List<Transform>) ref.getTransforms();
            if (transforms != null && transforms.stream().anyMatch(t -> t.getAlgorithm().equals(Transform.ENVELOPED))) {
                foundEnvelopedSig = true;
            }
        } else if ("http://www.w3.org/2000/09/xmldsig#SignatureProperties".equals(ref.getType()) && ref.getURI().equals("#" + timestampSignatureProperty.getId())) {
            // Found matching SignatureProperties Object
            // Now validate Timestamp
            validateTimestamp(signatureProperty, cert);
            foundSignedTimestamp = true;
        }
    }
    assertEquals(sigElement.getParentNode(), document.getDocumentElement());
    assertTrue(foundEnvelopedSig);
    assertTrue(foundSignedTimestamp);
}
Also used : X509Certificate(java.security.cert.X509Certificate) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) CanonicalizationMethod(javax.xml.crypto.dsig.CanonicalizationMethod) SignatureMethod(javax.xml.crypto.dsig.SignatureMethod) Date(java.util.Date) SignatureProperty(javax.xml.crypto.dsig.SignatureProperty) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) Transform(javax.xml.crypto.dsig.Transform) XMLValidateContext(javax.xml.crypto.dsig.XMLValidateContext) CertificateExpiredException(java.security.cert.CertificateExpiredException) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) X509Data(javax.xml.crypto.dsig.keyinfo.X509Data) XMLObject(javax.xml.crypto.dsig.XMLObject) XMLStructure(javax.xml.crypto.XMLStructure) DOMStructure(javax.xml.crypto.dom.DOMStructure) Iterator(java.util.Iterator) C14NMethodParameterSpec(javax.xml.crypto.dsig.spec.C14NMethodParameterSpec) XMLSignContext(javax.xml.crypto.dsig.XMLSignContext) KeyStore(java.security.KeyStore) UUID(java.util.UUID) XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) Key(java.security.Key) List(java.util.List) Element(org.w3c.dom.Element) SignedInfo(javax.xml.crypto.dsig.SignedInfo) Reference(javax.xml.crypto.dsig.Reference) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) DocumentBuilder(javax.xml.parsers.DocumentBuilder) DigestMethod(javax.xml.crypto.dsig.DigestMethod) KeyInfoFactory(javax.xml.crypto.dsig.keyinfo.KeyInfoFactory) TransformParameterSpec(javax.xml.crypto.dsig.spec.TransformParameterSpec) XMLUtils(org.apache.xml.security.utils.XMLUtils) SignatureProperties(javax.xml.crypto.dsig.SignatureProperties) Assert(org.junit.Assert) Collections(java.util.Collections) Init(org.apache.xml.security.Init) InputStream(java.io.InputStream) XMLSignature(javax.xml.crypto.dsig.XMLSignature) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) DigestMethod(javax.xml.crypto.dsig.DigestMethod) XMLStructure(javax.xml.crypto.XMLStructure) Document(org.w3c.dom.Document) SignatureProperty(javax.xml.crypto.dsig.SignatureProperty) X509Data(javax.xml.crypto.dsig.keyinfo.X509Data) KeyInfoFactory(javax.xml.crypto.dsig.keyinfo.KeyInfoFactory) XMLSignature(javax.xml.crypto.dsig.XMLSignature) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) DOMStructure(javax.xml.crypto.dom.DOMStructure) XMLSignContext(javax.xml.crypto.dsig.XMLSignContext) ArrayList(java.util.ArrayList) List(java.util.List) XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) XMLValidateContext(javax.xml.crypto.dsig.XMLValidateContext) InputStream(java.io.InputStream) Reference(javax.xml.crypto.dsig.Reference) CanonicalizationMethod(javax.xml.crypto.dsig.CanonicalizationMethod) XMLObject(javax.xml.crypto.dsig.XMLObject) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) SignedInfo(javax.xml.crypto.dsig.SignedInfo) DocumentBuilder(javax.xml.parsers.DocumentBuilder) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) SignatureProperties(javax.xml.crypto.dsig.SignatureProperties) SignatureMethod(javax.xml.crypto.dsig.SignatureMethod) XMLObject(javax.xml.crypto.dsig.XMLObject) Transform(javax.xml.crypto.dsig.Transform) Key(java.security.Key)

Example 5 with TransformParameterSpec

use of javax.xml.crypto.dsig.spec.TransformParameterSpec in project santuario-java by apache.

the class TransformTest method testConstructor.

@org.junit.Test
public void testConstructor() throws Exception {
    // test newTransform(String algorithm,
    // AlgorithmParameterSpec params)
    // for generating Transform objects
    Transform tm;
    for (int i = 0; i < TRANSFORM_ALGOS.length; i++) {
        String algo = TRANSFORM_ALGOS[i];
        TransformParameterSpec params = null;
        if (algo.equals(Transform.XPATH)) {
            params = new XPathFilterParameterSpec("xPath");
        } else if (algo.equals(Transform.XPATH2)) {
            params = new XPathFilter2ParameterSpec(Collections.singletonList(new XPathType("xPath2", XPathType.Filter.INTERSECT)));
        } else if (algo.equals(Transform.XSLT)) {
            params = new XSLTTransformParameterSpec(new XSLTStructure());
        }
        try {
            tm = factory.newTransform(algo, params);
            assertNotNull(tm);
            assertEquals(tm.getAlgorithm(), algo);
            assertEquals(tm.getParameterSpec(), params);
        } catch (Exception ex) {
            fail(TRANSFORM_ALGOS[i] + ": Unexpected exception " + ex);
        }
        try {
            tm = factory.newTransform(algo, new TestUtils.MyOwnC14nParameterSpec());
            fail(TRANSFORM_ALGOS[i] + ": Should raise an IAPE for invalid parameters");
        } catch (InvalidAlgorithmParameterException iape) {
        } catch (Exception ex) {
            fail(TRANSFORM_ALGOS[i] + ": Should raise a IAPE instead of " + ex);
        }
    }
    try {
        tm = factory.newTransform(null, (TransformParameterSpec) null);
        fail("Should raise a NPE for null algo");
    } catch (NullPointerException npe) {
    } catch (Exception ex) {
        fail("Should raise a NPE instead of " + ex);
    }
    try {
        tm = factory.newTransform("non-existent", (TransformParameterSpec) null);
        fail("Should raise an NSAE for non-existent algos");
    } catch (NoSuchAlgorithmException nsae) {
    } catch (Exception ex) {
        fail("Should raise an NSAE instead of " + ex);
    }
}
Also used : XPathType(javax.xml.crypto.dsig.spec.XPathType) XSLTTransformParameterSpec(javax.xml.crypto.dsig.spec.XSLTTransformParameterSpec) XPathFilterParameterSpec(javax.xml.crypto.dsig.spec.XPathFilterParameterSpec) XSLTTransformParameterSpec(javax.xml.crypto.dsig.spec.XSLTTransformParameterSpec) TransformParameterSpec(javax.xml.crypto.dsig.spec.TransformParameterSpec) XPathFilter2ParameterSpec(javax.xml.crypto.dsig.spec.XPathFilter2ParameterSpec)

Aggregations

TransformParameterSpec (javax.xml.crypto.dsig.spec.TransformParameterSpec)6 DOMSignContext (javax.xml.crypto.dsig.dom.DOMSignContext)4 Reference (javax.xml.crypto.dsig.Reference)3 SignedInfo (javax.xml.crypto.dsig.SignedInfo)3 Transform (javax.xml.crypto.dsig.Transform)3 XMLSignature (javax.xml.crypto.dsig.XMLSignature)3 KeyInfoFactory (javax.xml.crypto.dsig.keyinfo.KeyInfoFactory)3 CanonicalizationMethod (javax.xml.crypto.dsig.CanonicalizationMethod)2 SignatureMethod (javax.xml.crypto.dsig.SignatureMethod)2 XMLSignatureFactory (javax.xml.crypto.dsig.XMLSignatureFactory)2 KeyInfo (javax.xml.crypto.dsig.keyinfo.KeyInfo)2 X509Data (javax.xml.crypto.dsig.keyinfo.X509Data)2 C14NMethodParameterSpec (javax.xml.crypto.dsig.spec.C14NMethodParameterSpec)2 XPathFilter2ParameterSpec (javax.xml.crypto.dsig.spec.XPathFilter2ParameterSpec)2 XPathFilterParameterSpec (javax.xml.crypto.dsig.spec.XPathFilterParameterSpec)2 XPathType (javax.xml.crypto.dsig.spec.XPathType)2 XSLTTransformParameterSpec (javax.xml.crypto.dsig.spec.XSLTTransformParameterSpec)2 InputStream (java.io.InputStream)1 Key (java.security.Key)1 KeyStore (java.security.KeyStore)1