Search in sources :

Example 1 with XMLSignatureException

use of org.apache.xml.security.signature.XMLSignatureException in project OpenAM by OpenRock.

the class FMSigProvider method verify.

public boolean verify(String xmlString, String idValue, Set<X509Certificate> verificationCerts) throws SAML2Exception {
    String classMethod = "FMSigProvider.verify: ";
    if (xmlString == null || xmlString.length() == 0 || idValue == null || idValue.length() == 0) {
        SAML2SDKUtils.debug.error(classMethod + "Either input xmlString or idValue is null.");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("nullInput"));
    }
    Document doc = XMLUtils.toDOMDocument(xmlString, SAML2SDKUtils.debug);
    if (doc == null) {
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("errorObtainingElement"));
    }
    Element nscontext = org.apache.xml.security.utils.XMLUtils.createDSctx(doc, "ds", Constants.SignatureSpecNS);
    Element sigElement = null;
    try {
        sigElement = (Element) org.apache.xpath.XPathAPI.selectSingleNode(doc, "//ds:Signature[1]", nscontext);
    } catch (TransformerException te) {
        throw new SAML2Exception(te);
    }
    Element refElement;
    try {
        refElement = (Element) XPathAPI.selectSingleNode(doc, "//ds:Reference[1]", nscontext);
    } catch (TransformerException te) {
        throw new SAML2Exception(te);
    }
    String refUri = refElement.getAttribute("URI");
    String signedId = ((Element) sigElement.getParentNode()).getAttribute(SAML2Constants.ID);
    if (refUri == null || signedId == null || !refUri.substring(1).equals(signedId)) {
        SAML2SDKUtils.debug.error(classMethod + "Signature reference ID does " + "not match with element ID");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("uriNoMatchWithId"));
    }
    doc.getDocumentElement().setIdAttribute(SAML2Constants.ID, true);
    XMLSignature signature = null;
    try {
        signature = new XMLSignature((Element) sigElement, "");
    } catch (XMLSignatureException sige) {
        throw new SAML2Exception(sige);
    } catch (XMLSecurityException xse) {
        throw new SAML2Exception(xse);
    }
    signature.addResourceResolver(new com.sun.identity.saml.xmlsig.OfflineResolver());
    KeyInfo ki = signature.getKeyInfo();
    X509Certificate certToUse = null;
    if (ki != null && ki.containsX509Data()) {
        try {
            certToUse = ki.getX509Certificate();
        } catch (KeyResolverException kre) {
            SAML2SDKUtils.debug.error(classMethod + "Could not obtain a certificate " + "from inside the document.");
            certToUse = null;
        }
        if (certToUse != null && checkCert) {
            if (!verificationCerts.contains(certToUse)) {
                SAML2SDKUtils.debug.error(classMethod + "The cert contained in the document is NOT trusted");
                throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalidCertificate"));
            }
            if (SAML2SDKUtils.debug.messageEnabled()) {
                SAML2SDKUtils.debug.message(classMethod + "The cert contained in the document is trusted");
            }
        }
    }
    if (certToUse != null) {
        verificationCerts = Collections.singleton(certToUse);
    }
    if (!isValidSignature(signature, verificationCerts)) {
        SAML2SDKUtils.debug.error(classMethod + "Signature verification failed.");
        return false;
    }
    if (SAML2SDKUtils.debug.messageEnabled()) {
        SAML2SDKUtils.debug.message(classMethod + "Signature verification successful.");
    }
    return true;
}
Also used : Element(org.w3c.dom.Element) KeyResolverException(org.apache.xml.security.keys.keyresolver.KeyResolverException) Document(org.w3c.dom.Document) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) X509Certificate(java.security.cert.X509Certificate) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) KeyInfo(org.apache.xml.security.keys.KeyInfo) XMLSignature(org.apache.xml.security.signature.XMLSignature) XMLSignatureException(org.apache.xml.security.signature.XMLSignatureException) TransformerException(javax.xml.transform.TransformerException)

Example 2 with XMLSignatureException

use of org.apache.xml.security.signature.XMLSignatureException in project xades4j by luisgoncalves.

the class KeyInfoBuilder method buildKeyInfo.

void buildKeyInfo(X509Certificate signingCertificate, XMLSignature xmlSig) throws KeyingDataException, UnsupportedAlgorithmException {
    // Check key usage.
    // - KeyUsage[0] = digitalSignature
    // - KeyUsage[1] = nonRepudiation
    boolean[] keyUsage = signingCertificate.getKeyUsage();
    if (keyUsage != null && !keyUsage[0] && !keyUsage[1]) {
        throw new SigningCertKeyUsageException(signingCertificate);
    }
    try {
        signingCertificate.checkValidity();
    } catch (CertificateException ce) {
        // CertificateExpiredException or CertificateNotYetValidException
        throw new SigningCertValidityException(signingCertificate);
    }
    if (this.basicSignatureOptionsProvider.includeSigningCertificate()) {
        try {
            X509Data x509Data = new X509Data(xmlSig.getDocument());
            x509Data.addCertificate(signingCertificate);
            x509Data.addSubjectName(signingCertificate);
            x509Data.addIssuerSerial(signingCertificate.getIssuerX500Principal().getName(), signingCertificate.getSerialNumber());
            xmlSig.getKeyInfo().add(x509Data);
            if (this.basicSignatureOptionsProvider.signSigningCertificate()) {
                String keyInfoId = xmlSig.getId() + "-keyinfo";
                xmlSig.getKeyInfo().setId(keyInfoId);
                // Use same canonicalization URI as specified in the ds:CanonicalizationMethod for Signature.
                Algorithm canonAlg = this.algorithmsProvider.getCanonicalizationAlgorithmForSignature();
                CanonicalizerUtils.checkC14NAlgorithm(canonAlg);
                Transforms transforms = TransformUtils.createTransforms(canonAlg, this.algorithmsParametersMarshaller, xmlSig.getDocument());
                xmlSig.addDocument('#' + keyInfoId, transforms, this.algorithmsProvider.getDigestAlgorithmForDataObjsReferences());
            }
        } catch (XMLSignatureException ex) {
            throw new UnsupportedAlgorithmException("Digest algorithm not supported in the XML Signature provider", this.algorithmsProvider.getDigestAlgorithmForDataObjsReferences(), ex);
        } catch (XMLSecurityException ex) {
            throw new KeyingDataException(ex.getMessage(), ex);
        }
    }
    if (this.basicSignatureOptionsProvider.includePublicKey()) {
        xmlSig.addKeyInfo(signingCertificate.getPublicKey());
    }
}
Also used : Transforms(org.apache.xml.security.transforms.Transforms) UnsupportedAlgorithmException(xades4j.UnsupportedAlgorithmException) CertificateException(java.security.cert.CertificateException) X509Data(org.apache.xml.security.keys.content.X509Data) Algorithm(xades4j.algorithms.Algorithm) XMLSignatureException(org.apache.xml.security.signature.XMLSignatureException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException)

Example 3 with XMLSignatureException

use of org.apache.xml.security.signature.XMLSignatureException in project xades4j by luisgoncalves.

the class XadesVerifierImpl method doCoreVerification.

private static void doCoreVerification(XMLSignature signature, SignatureSpecificVerificationOptions verificationOptions, X509Certificate validationCert) throws XAdES4jXMLSigException, InvalidSignatureException {
    List<ResourceResolver> resolvers = verificationOptions.getResolvers();
    if (!CollectionUtils.nullOrEmpty(resolvers)) {
        for (ResourceResolver resolver : resolvers) {
            signature.addResourceResolver(resolver);
        }
    }
    InputStream nullURIReferenceData = verificationOptions.getDataForAnonymousReference();
    if (nullURIReferenceData != null) {
        signature.addResourceResolver(new ResolverAnonymous(nullURIReferenceData));
    }
    try {
        if (signature.checkSignatureValue(validationCert)) {
            return;
        }
    } catch (XMLSignatureException ex) {
        throw new XAdES4jXMLSigException("Error verifying the signature", ex);
    }
    try {
        if (signature.getSignedInfo().verifyReferences()) // References are OK; this is a problem on the signature value
        // itself.
        {
            throw new SignatureValueException(signature);
        } else {
            // References are NOT OK; get the first invalid Reference.
            SignedInfo si = signature.getSignedInfo();
            for (int i = 0; i < si.getLength(); i++) {
                Reference r = si.item(i);
                if (!r.verify()) {
                    throw new ReferenceValueException(signature, r);
                }
            }
        }
    } catch (XMLSecurityException ex) {
        throw new XAdES4jXMLSigException("Error verifying the references", ex);
    }
}
Also used : XAdES4jXMLSigException(xades4j.XAdES4jXMLSigException) InputStream(java.io.InputStream) Reference(org.apache.xml.security.signature.Reference) ResourceResolver(org.apache.xml.security.utils.resolver.ResourceResolver) ResolverAnonymous(org.apache.xml.security.utils.resolver.implementations.ResolverAnonymous) XMLSignatureException(org.apache.xml.security.signature.XMLSignatureException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) SignedInfo(org.apache.xml.security.signature.SignedInfo)

Example 4 with XMLSignatureException

use of org.apache.xml.security.signature.XMLSignatureException in project santuario-java by apache.

the class MessageDigestAlgorithm method getDigestInstance.

private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSignatureException {
    String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI);
    if (algorithmID == null) {
        Object[] exArgs = { algorithmURI };
        throw new XMLSignatureException("algorithms.NoSuchMap", exArgs);
    }
    MessageDigest md;
    String provider = JCEMapper.getProviderId();
    try {
        if (provider == null) {
            md = MessageDigest.getInstance(algorithmID);
        } else {
            md = MessageDigest.getInstance(algorithmID, provider);
        }
    } catch (java.security.NoSuchAlgorithmException ex) {
        Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
        throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
    } catch (NoSuchProviderException ex) {
        Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
        throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
    }
    return md;
}
Also used : MessageDigest(java.security.MessageDigest) NoSuchProviderException(java.security.NoSuchProviderException) XMLSignatureException(org.apache.xml.security.signature.XMLSignatureException)

Example 5 with XMLSignatureException

use of org.apache.xml.security.signature.XMLSignatureException in project santuario-java by apache.

the class SignatureAlgorithm method register.

/**
 * Registers implementing class of the SignatureAlgorithm with algorithmURI
 *
 * @param algorithmURI algorithmURI URI representation of <code>SignatureAlgorithm</code>.
 * @param implementingClass <code>implementingClass</code> the implementing class of
 * {@link SignatureAlgorithmSpi}
 * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered
 * @throws XMLSignatureException
 * @throws SecurityException if a security manager is installed and the
 *    caller does not have permission to register the signature algorithm
 */
@SuppressWarnings("unchecked")
public static void register(String algorithmURI, String implementingClass) throws AlgorithmAlreadyRegisteredException, ClassNotFoundException, XMLSignatureException {
    JavaUtils.checkRegisterPermission();
    LOG.debug("Try to register {} {}", algorithmURI, implementingClass);
    // are we already registered?
    Class<? extends SignatureAlgorithmSpi> registeredClass = algorithmHash.get(algorithmURI);
    if (registeredClass != null) {
        Object[] exArgs = { algorithmURI, registeredClass };
        throw new AlgorithmAlreadyRegisteredException("algorithm.alreadyRegistered", exArgs);
    }
    try {
        Class<? extends SignatureAlgorithmSpi> clazz = (Class<? extends SignatureAlgorithmSpi>) ClassLoaderUtils.loadClass(implementingClass, SignatureAlgorithm.class);
        algorithmHash.put(algorithmURI, clazz);
    } catch (NullPointerException ex) {
        Object[] exArgs = { algorithmURI, ex.getMessage() };
        throw new XMLSignatureException(ex, "algorithms.NoSuchAlgorithm", exArgs);
    }
}
Also used : AlgorithmAlreadyRegisteredException(org.apache.xml.security.exceptions.AlgorithmAlreadyRegisteredException) XMLSignatureException(org.apache.xml.security.signature.XMLSignatureException)

Aggregations

XMLSignatureException (org.apache.xml.security.signature.XMLSignatureException)28 InvalidKeyException (java.security.InvalidKeyException)8 XMLSignature (org.apache.xml.security.signature.XMLSignature)8 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)5 X509Certificate (java.security.cert.X509Certificate)5 XMLSecurityException (org.apache.xml.security.exceptions.XMLSecurityException)5 Document (org.w3c.dom.Document)5 Element (org.w3c.dom.Element)5 PrivateKey (java.security.PrivateKey)4 Transforms (org.apache.xml.security.transforms.Transforms)4 SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)3 NoSuchProviderException (java.security.NoSuchProviderException)3 PublicKey (java.security.PublicKey)3 Signature (java.security.Signature)3 SignatureException (java.security.SignatureException)3 Reference (org.apache.xml.security.signature.Reference)3 OfflineResolver (org.apache.xml.security.test.dom.utils.resolver.OfflineResolver)3 ResourceResolverSpi (org.apache.xml.security.utils.resolver.ResourceResolverSpi)3 UnsupportedAlgorithmException (xades4j.UnsupportedAlgorithmException)3 IOException (java.io.IOException)2