Search in sources :

Example 6 with C14NMethodParameterSpec

use of javax.xml.crypto.dsig.spec.C14NMethodParameterSpec in project OpenAttestation by OpenAttestation.

the class SAMLSignature method signSAMLObject.

/**
     * Adds an enveloped signature to the given element. Then moves the
     * signature element so that it is in the correct position according to the
     * SAML assertion and protocol schema: it must immediately follow any Issuer
     * and precede everything else.
     */
public void signSAMLObject(Element target) throws GeneralSecurityException, XMLSignatureException, MarshalException {
    Reference ref = factory.newReference("#" + target.getAttribute("ID"), factory.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(factory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null);
    SignedInfo signedInfo = factory.newSignedInfo(factory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), factory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));
    XMLSignature signature = factory.newXMLSignature(signedInfo, keyInfo);
    DOMSignContext signContext = new DOMSignContext(keyPair.getPrivate(), target);
    signature.sign(signContext);
    // For the result to be schema-valid, we have to move the signature
    // element from its place at the end of the child list to live
    // between Issuer and Subject elements.  So, deep breath, and:
    Node signatureElement = target.getLastChild();
    boolean foundIssuer = false;
    Node elementAfterIssuer = null;
    NodeList children = target.getChildNodes();
    for (int c = 0; c < children.getLength(); ++c) {
        Node child = children.item(c);
        if (foundIssuer) {
            elementAfterIssuer = child;
            break;
        }
        if (child.getNodeType() == Node.ELEMENT_NODE && child.getLocalName().equals("Issuer")) {
            foundIssuer = true;
        }
    }
    // Place after the Issuer, or as first element if no Issuer:
    if (!foundIssuer || elementAfterIssuer != null) {
        target.removeChild(signatureElement);
        target.insertBefore(signatureElement, foundIssuer ? elementAfterIssuer : target.getFirstChild());
    }
}
Also used : Reference(javax.xml.crypto.dsig.Reference) XMLSignature(javax.xml.crypto.dsig.XMLSignature) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) SignedInfo(javax.xml.crypto.dsig.SignedInfo) C14NMethodParameterSpec(javax.xml.crypto.dsig.spec.C14NMethodParameterSpec)

Example 7 with C14NMethodParameterSpec

use of javax.xml.crypto.dsig.spec.C14NMethodParameterSpec 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)

Aggregations

C14NMethodParameterSpec (javax.xml.crypto.dsig.spec.C14NMethodParameterSpec)7 DOMSignContext (javax.xml.crypto.dsig.dom.DOMSignContext)5 Reference (javax.xml.crypto.dsig.Reference)4 SignedInfo (javax.xml.crypto.dsig.SignedInfo)4 XMLSignature (javax.xml.crypto.dsig.XMLSignature)3 Transform (javax.xml.crypto.dsig.Transform)2 XMLSignatureFactory (javax.xml.crypto.dsig.XMLSignatureFactory)2 DOMValidateContext (javax.xml.crypto.dsig.dom.DOMValidateContext)2 KeyInfo (javax.xml.crypto.dsig.keyinfo.KeyInfo)2 KeyInfoFactory (javax.xml.crypto.dsig.keyinfo.KeyInfoFactory)2 X509Data (javax.xml.crypto.dsig.keyinfo.X509Data)2 TransformParameterSpec (javax.xml.crypto.dsig.spec.TransformParameterSpec)2 Document (org.w3c.dom.Document)2 InputStream (java.io.InputStream)1 Key (java.security.Key)1 KeyStore (java.security.KeyStore)1 CertificateExpiredException (java.security.cert.CertificateExpiredException)1 CertificateNotYetValidException (java.security.cert.CertificateNotYetValidException)1 X509Certificate (java.security.cert.X509Certificate)1 AlgorithmParameterSpec (java.security.spec.AlgorithmParameterSpec)1