org.apache.xml.security.utils.Constants Java Examples

The following examples show how to use org.apache.xml.security.utils.Constants. 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: Helper.java    From NCANode with MIT License 6 votes vote down vote up
/**
 * Метод возвращает алгоритм подписи по OID
 *
 * @param oid OID
 * @return Массив с двумя элементами (Первый = Алгоритм подписи, второй = Алгоритм хэширования)
 */
public static String[] getSignMethodByOID(String oid) {

    String ret[] = new String[2];


    if (oid.equals(PKCSObjectIdentifiers.sha1WithRSAEncryption.getId())) {
        ret[0] = Constants.MoreAlgorithmsSpecNS + "rsa-sha1";
        ret[1] = Constants.MoreAlgorithmsSpecNS + "sha1";
    } else if (oid.equals(PKCSObjectIdentifiers.sha256WithRSAEncryption.getId())) {
        ret[0] = Constants.MoreAlgorithmsSpecNS + "rsa-sha256";
        ret[1] = XMLCipherParameters.SHA256;
    } else {
        ret[0] = Constants.MoreAlgorithmsSpecNS + "gost34310-gost34311";
        ret[1] = Constants.MoreAlgorithmsSpecNS + "gost34311";
    }

    return ret;
}
 
Example #2
Source File: XmlSigOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private XMLSignature prepareEnvelopingSignature(Document doc,
                                                String id,
                                                String referenceId,
                                                String sigAlgo,
                                                String digestAlgo) throws Exception {
    Element docEl = doc.getDocumentElement();
    Document newDoc = DOMUtils.createDocument();
    doc.removeChild(docEl);
    newDoc.adoptNode(docEl);
    Element object = newDoc.createElementNS(Constants.SignatureSpecNS, "ds:Object");
    object.appendChild(docEl);
    docEl.setAttributeNS(null, "Id", id);
    docEl.setIdAttributeNS(null, "Id", true);

    XMLSignature sig = new XMLSignature(newDoc, "", sigAlgo);
    newDoc.appendChild(sig.getElement());
    sig.getElement().appendChild(object);

    Transforms transforms = new Transforms(newDoc);
    transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);

    sig.addDocument(referenceId, transforms, digestAlgo);
    return sig;
}
 
Example #3
Source File: MetadataTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testGetMetadata() throws Exception {
    URL busFile = MetadataTest.class.getResource("client.xml");

    String address = "https://localhost:" + PORT + "/sso/metadata";
    WebClient client = WebClient.create(address, busFile.toString());
    client.accept("text/xml");

    Response response = client.get();
    assertEquals(response.getStatus(), 200);
    Document doc = response.readEntity(Document.class);
    assertEquals("EntityDescriptor", doc.getDocumentElement().getLocalName());

    // Now validate the signature
    Element signature =
        (Element)doc.getElementsByTagNameNS(Constants.SignatureSpecNS, "Signature").item(0);
    assertNotNull(signature);
    XMLSignature signatureElem = new XMLSignature(signature, "");
    doc.getDocumentElement().setIdAttributeNS(null, "ID", true);

    X509Certificate signingCert = signatureElem.getKeyInfo().getX509Certificate();
    assertNotNull(signingCert);
    assertTrue(signatureElem.checkSignatureValue(signingCert));
}
 
Example #4
Source File: XadesSignatureFormatExtenderImplTest.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testEnrichSignatureWithA() throws Exception
{
    System.out.println("enrichSignatureWithA");

    Document doc = getDocument("document.verified.c.xl.xml");
    Element signatureNode = (Element)doc.getElementsByTagNameNS(Constants.SignatureSpecNS, "Signature").item(0);

    XadesSignatureFormatExtenderImpl instance = (XadesSignatureFormatExtenderImpl)new XadesFormatExtenderProfile().getFormatExtender();
    XMLSignature sig = new XMLSignature(signatureNode, "");
    Collection<UnsignedSignatureProperty> usp = new ArrayList<UnsignedSignatureProperty>(1);
    usp.add(new ArchiveTimeStampProperty());

    instance.enrichSignature(sig, new UnsignedProperties(usp));

    outputDocument(doc, "document.verified.c.xl.a.xml");
}
 
Example #5
Source File: XadesSignatureFormatExtenderImplTest.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testEnrichSignatureWithT() throws Exception
{
    System.out.println("enrichSignatureWithT");

    Document doc = getDocument("document.signed.bes.xml");
    Element signatureNode = (Element)doc.getElementsByTagNameNS(Constants.SignatureSpecNS, "Signature").item(0);

    XadesSignatureFormatExtenderImpl instance = (XadesSignatureFormatExtenderImpl)new XadesFormatExtenderProfile().getFormatExtender();
    XMLSignature sig = new XMLSignature(signatureNode, "");
    Collection<UnsignedSignatureProperty> usp = new ArrayList<UnsignedSignatureProperty>(1);
    usp.add(new SignatureTimeStampProperty());

    instance.enrichSignature(sig, new UnsignedProperties(usp));

    outputDocument(doc, "document.signed.bes.enriched.t.xml");
}
 
Example #6
Source File: XadesSignatureFormatExtenderImplTest.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testEnrichSignatureWithNestedCounterSig() throws Exception
{
    System.out.println("enrichSignatureWithNestedCounterSig");

    Document doc = getDocument("document.signed.bes.cs.xml");
    NodeList signatures = doc.getElementsByTagNameNS(Constants.SignatureSpecNS, Constants._TAG_SIGNATURE);
    // Existing counter signature is the last
    Element signatureNode = (Element)signatures.item(signatures.getLength() - 1);
            
    XadesSigner signer = new XadesBesSigningProfile(keyingProviderMy).newSigner();
    
    XadesSignatureFormatExtender extender = new XadesFormatExtenderProfile().getFormatExtender();
    XMLSignature sig = new XMLSignature(signatureNode, signatureNode.getOwnerDocument().getBaseURI());
    Collection<UnsignedSignatureProperty> usp = new ArrayList<UnsignedSignatureProperty>(1);
    usp.add(new CounterSignatureProperty(signer));
    
    extender.enrichSignature(sig, new UnsignedProperties(usp));

    outputDocument(doc, "document.signed.bes.cs.cs.xml");
}
 
Example #7
Source File: OtherSignerTests.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testSignAndAppendAsFirstChild() throws Exception
{
    System.out.println("signAndAppendAsFirstChild");

    Document doc = getTestDocument();
    Element root = doc.getDocumentElement();
    XadesSigner signer = new XadesBesSigningProfile(keyingProviderMy).newSigner();

    DataObjectDesc obj1 = new DataObjectReference('#' + root.getAttribute("Id")).withTransform(new EnvelopedSignatureTransform());
    SignedDataObjects dataObjs = new SignedDataObjects(obj1);

    signer.sign(dataObjs, root, SignatureAppendingStrategies.AsFirstChild);

    Element firstChild = (Element) doc.getDocumentElement().getFirstChild();
    assertEquals(Constants._TAG_SIGNATURE, firstChild.getLocalName());
    assertEquals(Constants.SignatureSpecNS, firstChild.getNamespaceURI());
}
 
Example #8
Source File: SignedDataObjectsProcessorTest.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testAddNullReference() throws Exception
{
    System.out.println("addNullReference");

    Document doc = SignatureServicesTestBase.getNewDocument();

    SignedDataObjects dataObjsDescs = new SignedDataObjects()
        .withSignedDataObject(new AnonymousDataObjectReference("data".getBytes()));

    XMLSignature xmlSignature = new XMLSignature(doc, "", XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256);
    xmlSignature.setId("sigId");

    SignedDataObjectsProcessor processor = new SignedDataObjectsProcessor(new TestAlgorithmsProvider(), new AllwaysNullAlgsParamsMarshaller());
    Map<DataObjectDesc, Reference> result = processor.process(dataObjsDescs, xmlSignature);

    assertEquals(1, result.size());
    assertEquals(0, xmlSignature.getObjectLength());
    assertEquals(1, xmlSignature.getSignedInfo().getLength());

    Reference r = xmlSignature.getSignedInfo().item(0);
    assertNull(r.getElement().getAttributeNodeNS(Constants.SignatureSpecNS, "URI"));
}
 
Example #9
Source File: XPathTransformParamsMarshallerTest.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testMarshalXPathParametersWithNamespacePrefixes() throws Exception 
{
    XPathTransform xpath = new XPathTransform("foo:elem1/bar:elem2")
            .withNamespace("foo", "http://test.xades4j/ns1")
            .withNamespace("bar", "http://test.xades4j/ns2");

    List<Node> params = sut.marshalParameters(xpath, doc);
    assertEquals(1, params.size());
    Element paramNode = (Element) params.get(0);

    Map<String, String> namespaces = xpath.getNamespaces();

    for (Map.Entry<String, String> entry : namespaces.entrySet()) {
        String ns = paramNode.getAttributeNS(Constants.NamespaceSpecNS, entry.getKey());
        assertNotNull(ns);
        assertFalse(ns.isEmpty());
        assertEquals(entry.getValue(), ns);
    }
}
 
Example #10
Source File: XPath2FilterTransformParamsMarshallerTest.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testMarshalXPathParametersWithNamespacePrefixes() throws Exception {
    XPath2FilterTransform xpath = XPath2Filter
            .intersect("foo:elem1")
            .union("bar:elem2")
            .withNamespace("foo", "http://test.xades4j/ns1")
            .withNamespace("bar", "http://test.xades4j/ns2");

    List<Node> params = sut.marshalParameters(xpath, doc);
    assertEquals(2, params.size());

    Set<Map.Entry<String, String>> namespaces = xpath.getNamespaces().entrySet();

    for (Node paramNode : params) 
    {
        for (Map.Entry<String, String> entry : namespaces) 
        {
            String ns = ((Element)paramNode).getAttributeNS(Constants.NamespaceSpecNS, entry.getKey());
            assertNotNull(ns);
            assertFalse(ns.isEmpty());
            assertEquals(entry.getValue(), ns);
        }
    }
}
 
Example #11
Source File: RSSecurityUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static X509Certificate loadX509IssuerSerial(Crypto crypto, Element certNode)
    throws Exception {
    Node issuerNameNode =
        certNode.getElementsByTagNameNS(Constants.SignatureSpecNS, "X509IssuerName").item(0);
    Node serialNumberNode =
        certNode.getElementsByTagNameNS(Constants.SignatureSpecNS, "X509SerialNumber").item(0);
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ISSUER_SERIAL);
    cryptoType.setIssuerSerial(issuerNameNode.getTextContent(),
                               new BigInteger(serialNumberNode.getTextContent()));
    return crypto.getX509Certificates(cryptoType)[0];
}
 
Example #12
Source File: AbstractXmlSigInHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Element getActualBody(Element envelopingSigElement) {
    Element objectNode = getNode(envelopingSigElement, Constants.SignatureSpecNS, "Object", 0);
    if (objectNode == null) {
        throwFault("Object envelope is not available", null);
    }
    Element node = DOMUtils.getFirstElement(objectNode);
    if (node == null) {
        throwFault("No signed data is found", null);
    }
    return node;

}
 
Example #13
Source File: SignatureTimeStampVerifier.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected QualifyingProperty addPropSpecificTimeStampInputAndCreateProperty(
        SignatureTimeStampData propData,
        TimeStampDigestInput digestInput,
        QualifyingPropertyVerificationContext ctx) throws CannotAddDataToDigestInputException
{
    Element sigValueElem = DOMHelper.getFirstDescendant(
        ctx.getSignature().getElement(),
        Constants.SignatureSpecNS, Constants._TAG_SIGNATUREVALUE);
    digestInput.addNode(sigValueElem);
    return new SignatureTimeStampProperty();
}
 
Example #14
Source File: SignerBES.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Element createElementForAlgorithm(Algorithm algorithm, String elementName, Document signatureDocument) throws UnsupportedAlgorithmException
{
    Element algorithmElem = XMLUtils.createElementInSignatureSpace(signatureDocument, elementName);
    algorithmElem.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithm.getUri());

    List<Node> algorithmParams = this.algorithmsParametersMarshaller.marshalParameters(algorithm, signatureDocument);
    if (algorithmParams != null)
    {
        for (Node p : algorithmParams)
        {
            algorithmElem.appendChild(p);
        }
    }
    return algorithmElem;
}
 
Example #15
Source File: SignerBES.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
private XMLSignature createSignature(Document signatureDocument, String baseUri, String signingKeyAlgorithm) throws XAdES4jXMLSigException, UnsupportedAlgorithmException
{
    Algorithm signatureAlg = this.algorithmsProvider.getSignatureAlgorithm(signingKeyAlgorithm);
    if (null == signatureAlg)
    {
        throw new NullPointerException("Signature algorithm not provided");
    }
    Element signatureAlgElem = createElementForAlgorithm(signatureAlg, Constants._TAG_SIGNATUREMETHOD, signatureDocument);


    Algorithm canonAlg = this.algorithmsProvider.getCanonicalizationAlgorithmForSignature();
    if (null == canonAlg)
    {
        throw new NullPointerException("Canonicalization algorithm not provided");
    }
    Element canonAlgElem = createElementForAlgorithm(canonAlg, Constants._TAG_CANONICALIZATIONMETHOD, signatureDocument);

    try
    {
        return new XMLSignature(signatureDocument, baseUri, signatureAlgElem, canonAlgElem);
    } catch (XMLSecurityException ex)
    {
        // Following the code, doesn't seem to be thrown at all.
        throw new XAdES4jXMLSigException(ex.getMessage(), ex);
    }
}
 
Example #16
Source File: XadesSignatureFormatExtenderImpl.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void enrichSignature(
        XMLSignature sig,
        UnsignedProperties props) throws XAdES4jException
{
    if (props.isEmpty())
        return;
    if (!props.getDataObjProps().isEmpty())
        throw new NullPointerException();

    Element qualifProps = DOMHelper.getFirstDescendant(
            sig.getElement(),
            QualifyingProperty.XADES_XMLNS, QualifyingProperty.QUALIFYING_PROPS_TAG);
    if(null == qualifProps)
    {
        throw new IllegalArgumentException("Couldn't find XAdES QualifyingProperties");
    }

    Element signedProps = DOMHelper.getFirstChildElement(qualifProps);
    if (signedProps != null
        && signedProps.getLocalName().equals(QualifyingProperty.SIGNED_PROPS_TAG)
        && signedProps.getNamespaceURI().equals(QualifyingProperty.XADES_XMLNS))
    {
        // Register the SignedProperties XML ID.
        DOMHelper.useIdAsXmlId(signedProps);
    }

    SigAndDataObjsPropertiesData propsData = propsDataObjectsGenerator.generateUnsignedPropertiesData(
            props,
            new PropertiesDataGenerationContext(sig));
    
    // A little style trick to have nice prefixes.
    if(null == sig.getDocument().lookupPrefix(QualifyingProperty.XADESV141_XMLNS))
        qualifProps.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:xades141", QualifyingProperty.XADESV141_XMLNS);

    unsignedPropsMarshaller.marshal(propsData, qualifProps);
}
 
Example #17
Source File: DataGenSigTimeStamp.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void addPropSpecificTimeStampInput(
        SignatureTimeStampProperty prop,
        TimeStampDigestInput digestInput,
        PropertiesDataGenerationContext ctx) throws CannotAddDataToDigestInputException
{
    Element sigValueElem = DOMHelper.getFirstDescendant(
        ctx.getTargetXmlSignature().getElement(),
        Constants.SignatureSpecNS, Constants._TAG_SIGNATUREVALUE);

    digestInput.addNode(sigValueElem);
}
 
Example #18
Source File: Init.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
static void initXMLSec()
{
    org.apache.xml.security.Init.init();
    try
    {
        ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, "ds");
        ElementProxy.setDefaultPrefix(QualifyingProperty.XADES_XMLNS, "xades");
        ElementProxy.setDefaultPrefix(QualifyingProperty.XADESV141_XMLNS, "xades141");
    } catch (XMLSecurityException ex)
    {
    }
}
 
Example #19
Source File: DOMHelper.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Defines the element's "Id" attribute as its XML ID, if present.
 * @param e the element
 */
public static void useIdAsXmlId(Element e)
{
    if(e.hasAttributeNS(null, Constants._ATT_ID))
    {
        e.setIdAttributeNS(null, Constants._ATT_ID, true);
    }
}
 
Example #20
Source File: CounterSignatureVerifier.java    From xades4j with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public QualifyingProperty verify(
        GenericDOMData propData,
        QualifyingPropertyVerificationContext ctx) throws InvalidPropertyException
{


    XAdESVerificationResult res;
    try
    {
        Element sigElem = DOMHelper.getFirstChildElement(propData.getPropertyElement());
        res = verifier.verify(sigElem, null);
    } catch (XAdES4jException ex)
    {
        throw new CounterSignatureXadesVerificationException(ex);
    }

    // "Check that the enclosed signature correctly references the ds:SignatureValue
    // present in the countersigned XAdES signature."

    Node targetSigValueElem = ctx.getSignature().getElement().getElementsByTagNameNS(
            Constants.SignatureSpecNS, Constants._TAG_SIGNATUREVALUE).item(0);

    try
    {
        SignedInfo si = res.getXmlSignature().getSignedInfo();
        for (int i = 0; i < si.getLength(); i++)
        {
            Reference r = si.item(i);
            if (r.getContentsAfterTransformation().getSubNode() == targetSigValueElem)
            {
                // The signature references the SignatureValue element.
                return new CounterSignatureProperty(res);
            }
            else if (r.getContentsBeforeTransformation().getSubNode() == targetSigValueElem && CanonicalizerUtils.allTransformsAreC14N(r))
            {
                // The signature references the SignatureValue element with
                // C14N transforms only.
                return new CounterSignatureProperty(res);
            }
        }
        throw new CounterSignatureSigValueRefException();
    } catch (XMLSecurityException e)
    {
        // Shouldn't happen because the signature was already verified.
        throw new CounterSignatureVerificationException(e);
    }
}
 
Example #21
Source File: DataGenArchiveTimeStamp.java    From xades4j with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected void addPropSpecificTimeStampInput(
        ArchiveTimeStampProperty prop,
        TimeStampDigestInput digestInput,
        PropertiesDataGenerationContext ctx) throws CannotAddDataToDigestInputException, PropertyDataGenerationException
{
    Element unsignedSigPropsElem = DOMHelper.getFirstDescendant(
            ctx.getTargetXmlSignature().getElement(),
            QualifyingProperty.XADES_XMLNS, QualifyingProperty.UNSIGNED_SIGNATURE_PROPS_TAG);
    if (null == unsignedSigPropsElem)
        throw new PropertyDataGenerationException(prop, "no unsigned signature properties to get inputs");

    try
    {
        // References, processed accordingly to XML-DSIG.
        List<Reference> refs = ctx.getReferences();
        for (Reference r : refs)
        {
            digestInput.addReference(r);
        }

        // SignedInfo.
        Element e = ctx.getTargetXmlSignature().getSignedInfo().getElement();
        digestInput.addNode(e);

        // SignatureValue.
        e = DOMHelper.getFirstDescendant(
                ctx.getTargetXmlSignature().getElement(),
                Constants.SignatureSpecNS, Constants._TAG_SIGNATUREVALUE);
        digestInput.addNode(e);

        // KeyInfo, if present.
        KeyInfo ki = ctx.getTargetXmlSignature().getKeyInfo();
        if (ki != null)
            digestInput.addNode(ki.getElement());

        // Unsigned properties, in order of appearance.
        Map<String, Integer> propsCnt = new HashMap<String, Integer>(5);
        propsCnt.put(CertificateValuesProperty.PROP_NAME, 0);
        propsCnt.put(RevocationValuesProperty.PROP_NAME, 0);
        propsCnt.put(CompleteCertificateRefsProperty.PROP_NAME, 0);
        propsCnt.put(CompleteRevocationRefsProperty.PROP_NAME, 0);
        propsCnt.put(SignatureTimeStampProperty.PROP_NAME, 0);

        e = DOMHelper.getFirstChildElement(unsignedSigPropsElem);
        // UnsignedProperties shouldn't be empty!
        do
        {
            digestInput.addNode(e);

            Integer pCnt = propsCnt.get(e.getLocalName());
            if (pCnt != null)
                propsCnt.put(e.getLocalName(), pCnt += 1);

        } while ((e = DOMHelper.getNextSiblingElement(e)) != null);

        for (Map.Entry<String, Integer> entry : propsCnt.entrySet())
        {
            if (entry.getValue() == 0)
                throw new PropertyDataGenerationException(prop, String.format("no %s for input", entry.getKey()));
        }

        // Objects, except the one containing the qualifying properties.
        for (int i = 0; i < ctx.getTargetXmlSignature().getObjectLength(); i++)
        {
            ObjectContainer obj = ctx.getTargetXmlSignature().getObjectItem(i);
            if (null == DOMHelper.getFirstDescendant(obj.getElement(), QualifyingProperty.XADES_XMLNS, "*"))
                digestInput.addNode(obj.getElement());
        }

    } catch (CannotAddDataToDigestInputException ex)
    {
        throw new PropertyDataGenerationException(prop, "cannot create time stamp input", ex);
    }
}
 
Example #22
Source File: VerifierTestBase.java    From xades4j with GNU Lesser General Public License v3.0 4 votes vote down vote up
static public Element getSigElement(Document doc) throws Exception
{
    return (Element)doc.getElementsByTagNameNS(Constants.SignatureSpecNS, Constants._TAG_SIGNATURE).item(0);
}
 
Example #23
Source File: GenericIdentityProviderData.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Validate the given ds:KeyInfo element against the stored ds:KeyInfo element.
 *
 * @param issuerInfo Stored ds:KeyInfo element as a <code>java.lang.String</code>.
 * @param keyInfo    The incoming ds:KeyInfo element as a <code>org.w3c.dom.Element</code>.
 * @return true if the information matches, otherwise false.
 */
protected boolean validateKeyInfo(String issuerInfo, Element keyInfo) throws IdentityProviderException {

    if (log.isDebugEnabled()) {
        log.debug("Validating key info");
    }

    try {
        OMElement elem = new StAXOMBuilder(new ByteArrayInputStream(issuerInfo.getBytes())).getDocumentElement();

        OMElement keyValueElem = elem.getFirstElement();
        if (keyValueElem != null &&
            keyValueElem.getQName().equals(new QName(WSConstants.SIG_NS, Constants._TAG_KEYVALUE))) {
            // KeyValue structure : expect an RSAKeyValue
            OMElement rsaKeyValueElem = keyValueElem.getFirstElement();
            if (rsaKeyValueElem != null &&
                rsaKeyValueElem.getQName().equals(new QName(WSConstants.SIG_NS, Constants._TAG_RSAKEYVALUE))) {
                String modulus =
                        rsaKeyValueElem.getFirstChildWithName(new QName(WSConstants.SIG_NS, Constants._TAG_MODULUS))
                                       .getText().trim();
                String exponent = rsaKeyValueElem
                        .getFirstChildWithName(new QName(WSConstants.SIG_NS, Constants._TAG_EXPONENT)).getText()
                        .trim();

                // Now process the incoming element to check for ds:RSAKeyValue

                OMElement receivedKeyInfoElem = (OMElement) new OMDOMFactory().getDocument().importNode(keyInfo,
                                                                                                        true);

                OMElement receivedKeyValueElem = receivedKeyInfoElem.getFirstElement();
                if (receivedKeyValueElem != null && receivedKeyValueElem.getQName()
                                                                        .equals(new QName(WSConstants.SIG_NS,
                                                                                          Constants._TAG_KEYVALUE))) {
                    OMElement receivedRsaKeyValueElem = receivedKeyValueElem.getFirstChildWithName(
                            new QName(WSConstants.SIG_NS, Constants._TAG_RSAKEYVALUE));
                    if (receivedRsaKeyValueElem != null) {
                        // Obtain incoming mod and exp
                        String receivedModulus = receivedRsaKeyValueElem
                                .getFirstChildWithName(new QName(WSConstants.SIG_NS, Constants._TAG_MODULUS))
                                .getText().trim();
                        String receivedExponent = receivedRsaKeyValueElem.getFirstChildWithName(
                                new QName(WSConstants.SIG_NS, Constants._TAG_EXPONENT)).getText().trim();

                        // Compare
                        return modulus.equals(receivedModulus) && exponent.equals(receivedExponent);
                    } else {
                        log.error("Unknown received KeyInfo type");
                        throw new IdentityProviderException("Unknown received KeyInfo type");
                    }

                } else {
                    log.error("Unknown received KeyInfo type");
                    throw new IdentityProviderException("Unknown received KeyInfo type");
                }
            } else {
                log.error("Error while instantiating IdentityUserStore");
                throw new IdentityProviderException("Unknown received KeyInfo type");
            }
        } else {
            log.error("Unknown stored KeyInfo type");
            throw new IdentityProviderException("Unknown stored KeyInfo type");
        }
    } catch (XMLStreamException e) {
        log.error("Error parsing stored KeyInfo", e);
        throw new IdentityProviderException("Error parsing stored KeyInfo");
    }
}
 
Example #24
Source File: DataGenCounterSig.java    From xades4j with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public PropertyDataObject generatePropertyData(
        CounterSignatureProperty prop,
        PropertiesDataGenerationContext ctx) throws PropertyDataGenerationException
{
    // The element has to be in the document tree for the references to be
    // resolved. UGLY WORKAROUND.
    Element qPs = DOMHelper.getFirstDescendant(ctx.getTargetXmlSignature().getElement(),
            QualifyingProperty.XADES_XMLNS, QualifyingProperty.QUALIFYING_PROPS_TAG);

    // Create the CounterSignature property element.
    Element counterSigElem = ctx.createElementInSignatureDoc(
            "CounterSignature",
            qPs.getPrefix(),
            QualifyingProperty.XADES_XMLNS);

    qPs.appendChild(counterSigElem);

    try
    {
        // Rerence to the ds:SignatureValue element. This assumes that the
        // QualifyingProperties are in the signature's document and that the
        // SignatureValue element has an Id.
        Element sigValueElem = DOMHelper.getFirstDescendant(
                ctx.getTargetXmlSignature().getElement(),
                Constants.SignatureSpecNS, Constants._TAG_SIGNATUREVALUE);
        String sigValueId = sigValueElem.getAttribute(Constants._ATT_ID);
        DataObjectReference sigValueRef = new DataObjectReference('#' + sigValueId)
                .withType(CounterSignatureProperty.COUNTER_SIGNATURE_TYPE_URI);

        XadesSigner counterSigner = prop.getCounterSigSigner();
        if (null == counterSigner)
            throw new PropertyDataGenerationException(prop, "signer not specified");

        try
        {
            SignedDataObjects objs = prop.getSignedDataObjectsForCounterSig();
            if(null == objs)
                objs = new SignedDataObjects();

            objs.withSignedDataObject(sigValueRef);
            counterSigner.sign(objs, counterSigElem);
        }
        catch (XAdES4jException ex)
        {
            throw new PropertyDataGenerationException(prop, "cannot apply counter signature", ex);
        }
    } finally
    {
        qPs.removeChild(counterSigElem);
    }

    return new GenericDOMData(counterSigElem);
}
 
Example #25
Source File: DataGenSigAndRefsTimeStamp.java    From xades4j with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected void addPropSpecificTimeStampInput(
        SigAndRefsTimeStampProperty prop,
        TimeStampDigestInput digestInput,
        PropertiesDataGenerationContext ctx) throws CannotAddDataToDigestInputException, PropertyDataGenerationException
{
    Element unsignedSigPropsElem = DOMHelper.getFirstDescendant(
        ctx.getTargetXmlSignature().getElement(),
        QualifyingProperty.XADES_XMLNS, QualifyingProperty.UNSIGNED_SIGNATURE_PROPS_TAG);
    if (null == unsignedSigPropsElem)
        throw new PropertyDataGenerationException(prop, "no unsigned signature properties to get inputs");

    /**
     * This property contains a time-stamp token that covers the following data
     * objects: {@code ds:SignatureValue} element, all present {@code SignatureTimeStamp}
     * elements, {@code CompleteCertificateRefs}, {@code CompleteRevocationRefs}, and
     * when present, {@code AttributeCertificateRefs} and {@code AttributeRevocationRefs}.
     *
     * "Those (...) that appear before SigAndRefsTimeStamp, in their order of
     * appearance within the UnsignedSignatureProperties element."
     */
    Map<String, Integer> elegiblePropsCnt = new HashMap<String, Integer>(5);
    elegiblePropsCnt.put(CompleteCertificateRefsProperty.PROP_NAME, 0);
    elegiblePropsCnt.put(CompleteRevocationRefsProperty.PROP_NAME, 0);
    elegiblePropsCnt.put(SignatureTimeStampProperty.PROP_NAME, 0);
    elegiblePropsCnt.put("AttributeCertificateRefs", 0);
    elegiblePropsCnt.put("AttributeRevocationRefs", 0);

    try
    {
        // SignatureValue.
        Element e = DOMHelper.getFirstDescendant(
                ctx.getTargetXmlSignature().getElement(),
                Constants.SignatureSpecNS, Constants._TAG_SIGNATUREVALUE);
        digestInput.addNode(e);

        e = DOMHelper.getFirstChildElement(unsignedSigPropsElem);
        // UnsignedProperties shouldn't be empty!
        do
        {
            Integer pCnt = elegiblePropsCnt.get(e.getLocalName());
            if (pCnt != null)
            {
                elegiblePropsCnt.put(e.getLocalName(), pCnt += 1);
                digestInput.addNode(e);
            }

        } while ((e = DOMHelper.getNextSiblingElement(e)) != null);

        // SignatureTimeStamp has to be present.
        if (elegiblePropsCnt.get(SignatureTimeStampProperty.PROP_NAME) == 0)
            throw new PropertyDataGenerationException(prop, "no signature time-stamps for input");

        // CompleteCertificateRefs has to be present.
        if (elegiblePropsCnt.get(CompleteCertificateRefsProperty.PROP_NAME) != 1)
            throw new PropertyDataGenerationException(prop, "no CompleteCertificateRefs for input");

        // CompleteRevocationRefs has to be present.
        if (elegiblePropsCnt.get(CompleteRevocationRefsProperty.PROP_NAME) != 1)
            throw new PropertyDataGenerationException(prop, "no CompleteRevocationRefs for input");

    } catch (CannotAddDataToDigestInputException ex)
    {
        throw new PropertyDataGenerationException(prop, "cannot create timestamp input", ex);
    }
}
 
Example #26
Source File: AbstractXmlSigInHandler.java    From cxf with Apache License 2.0 4 votes vote down vote up
private Element getSignatureElement(Element sigParentElement) {
    if (isEnveloping(sigParentElement)) {
        return sigParentElement;
    }
    return DOMUtils.getFirstChildWithName(sigParentElement, Constants.SignatureSpecNS, "Signature");
}
 
Example #27
Source File: AbstractXmlSigInHandler.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected boolean isEnveloping(Element root) {
    return Constants.SignatureSpecNS.equals(root.getNamespaceURI())
            && "Signature".equals(root.getLocalName());
}
 
Example #28
Source File: DOMHelper.java    From xades4j with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Sets the "Id" attribute of an element and sets it as the element's XML ID.
 * @param e the element where the ID should be set
 * @param id the id
 */
public static void setIdAsXmlId(Element e, String id)
{
    e.setAttributeNS(null, Constants._ATT_ID, id);
    e.setIdAttributeNS(null, Constants._ATT_ID, true);
}