org.apache.xml.security.exceptions.XMLSecurityException Java Examples

The following examples show how to use org.apache.xml.security.exceptions.XMLSecurityException. 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: CanonicalizerUtils.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Checks if all the transforms in a ds:Reference are canonicalization transforms.
 * @param r the reference
 * @return true if all transforms are c14n, false otherwise.
 * @throws XMLSecurityException
 */
public static boolean allTransformsAreC14N(Reference r) throws XMLSecurityException
{
    Transforms transforms = r.getTransforms();
    try
    {
        for (int i = 0; i < transforms.getLength(); ++i)
        {
            Canonicalizer.getInstance(transforms.item(i).getURI());
        }
        return true;
    }
    catch (InvalidCanonicalizerException ex)
    {
        return false;
    }
}
 
Example #2
Source File: Signer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Signs a single XMLObject.
 * 
 * @param signature the signature to computer the signature on
 * @throws SignatureException thrown if there is an error computing the signature
 */
public static void signObject(Signature signature) throws SignatureException {
    Logger log = getLogger();
    try {
        XMLSignature xmlSignature = ((SignatureImpl) signature).getXMLSignature();

        if (xmlSignature == null) {
            log.error("Unable to compute signature, Signature XMLObject does not have the XMLSignature "
                    + "created during marshalling.");
            throw new SignatureException("XMLObject does not have an XMLSignature instance, unable to compute signature");
        }
        log.debug("Computing signature over XMLSignature object");
        xmlSignature.sign(SecurityHelper.extractSigningKey(signature.getSigningCredential()));
    } catch (XMLSecurityException e) {
        log.error("An error occured computing the digital signature", e);
        throw new SignatureException("Signature computation error", e);
    }
}
 
Example #3
Source File: XmlSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void addKeyInfo(Credential signatureCredential, XMLSignature sig) throws TechnicalConnectorException, XMLSecurityException {
   if (signatureCredential.getCertificateChain() != null) {
      Certificate[] arr$ = signatureCredential.getCertificateChain();
      int len$ = arr$.length;

      for(int i$ = 0; i$ < len$; ++i$) {
         Certificate cert = arr$[i$];
         if (sig.getKeyInfo().itemX509Data(0) == null) {
            X509Data x509data = new X509Data(sig.getDocument());
            sig.getKeyInfo().add(x509data);
         }

         sig.getKeyInfo().itemX509Data(0).addCertificate((X509Certificate)cert);
      }
   }

}
 
Example #4
Source File: KerberosTokenInterceptorProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
private SecretKey getSecretKeyFromToken(KerberosServiceSecurityToken kerberosToken) {
    try {
        Map<String, Key> secretKeys = kerberosToken.getSecretKey();
        if (secretKeys != null) {
            SecretKey foundKey = null;
            for (Entry<String, Key> entry : kerberosToken.getSecretKey().entrySet()) {
                if (entry.getValue() instanceof SecretKey) {
                    SecretKey secretKey = (SecretKey)entry.getValue();
                    if (foundKey == null
                        || secretKey.getEncoded().length > foundKey.getEncoded().length) {
                        foundKey = secretKey;
                    }
                }
            }
            return foundKey;
        }
    } catch (XMLSecurityException e) {
        LOG.fine(e.getMessage());
    }
    return null;
}
 
Example #5
Source File: SCTCanceller.java    From cxf with Apache License 2.0 6 votes vote down vote up
private boolean matchKey(TokenCancellerParameters tokenParameters, byte[] secretKey) {
    Map<String, Object> messageContext = tokenParameters.getMessageContext();

    if (matchDOMSignatureSecret(messageContext, secretKey)) {
        return true;
    }

    try {
        if (matchStreamingSignatureSecret(messageContext, secretKey)) {
            return true;
        }
    } catch (XMLSecurityException ex) {
        LOG.log(Level.FINE, ex.getMessage(), ex);
        return false;
    }

    return false;
}
 
Example #6
Source File: WSS4JStaxOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected SecurityEventListener configureSecurityEventListener(
    final SoapMessage msg, WSSSecurityProperties securityProperties
) throws WSSPolicyException {
    final List<SecurityEvent> outgoingSecurityEventList = new LinkedList<>();
    msg.getExchange().put(SecurityEvent.class.getName() + ".out", outgoingSecurityEventList);
    msg.put(SecurityEvent.class.getName() + ".out", outgoingSecurityEventList);

    return new SecurityEventListener() {
        @Override
        public void registerSecurityEvent(SecurityEvent securityEvent) throws XMLSecurityException {
            if (securityEvent.getSecurityEventType() == WSSecurityEventConstants.SAML_TOKEN) {
                // Store SAML keys in case we need them on the inbound side
                TokenSecurityEvent<?> tokenSecurityEvent = (TokenSecurityEvent<?>)securityEvent;
                try {
                    WSS4JUtils.parseAndStoreStreamingSecurityToken(tokenSecurityEvent.getSecurityToken(), msg);
                } catch (TokenStoreException e) {
                    throw new XMLSecurityException(e);
                }
            } else if (securityEvent.getSecurityEventType() == WSSecurityEventConstants.SignatureValue) {
                // Required for Signature Confirmation
                outgoingSecurityEventList.add(securityEvent);
            }
        }
    };
}
 
Example #7
Source File: XadesHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void before() throws TechnicalConnectorException, XMLSecurityException {
   if (!ArrayUtils.isEmpty(this.specs)) {
      ObjectContainer container = new ObjectContainer(this.sig.getDocument());
      this.sig.appendObject(container);
      QualifyingPropertiesBuilder qualProperties = new QualifyingPropertiesBuilder();
      String xadesSignedId = IdGeneratorFactory.getIdGenerator("uuid").generateId();
      XadesSpecification[] arr$ = this.specs;
      int len$ = arr$.length;

      for(int i$ = 0; i$ < len$; ++i$) {
         XadesSpecification spec = arr$[i$];
         spec.addOptionalBeforeSignatureParts(qualProperties.getSignedProps(), this.sig, this.signatureCredential, xadesSignedId, this.options);
      }

      Document xadesQualPropertiesDocument = qualProperties.buildBeforeSigningAsDocument();
      this.xadesQualProperties = (Element)this.sig.getDocument().importNode(xadesQualPropertiesDocument.getDocumentElement(), true);
      container.appendChild(this.xadesQualProperties);
      this.sig.addResourceResolver(new DocumentResolver(xadesQualPropertiesDocument));
      Transforms xadesTransform = new Transforms(this.sig.getDocument());
      xadesTransform.addTransform("http://www.w3.org/2001/10/xml-exc-c14n#");
      this.sig.addDocument(ref(qualProperties.getSignedProps().getId()), xadesTransform, (String)SignatureUtils.getOption("digestURI", this.options, "http://www.w3.org/2001/04/xmlenc#sha256"), (String)null, "http://uri.etsi.org/01903#SignedProperties");
   }
}
 
Example #8
Source File: PropertiesDataGenerationContext.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * A simple constructor to be used when only unsigned signature properties
 * will be processed.
 * @param targetXmlSignature the target signature
 * @param algorithmsProvider algorithms in use
 */
PropertiesDataGenerationContext(XMLSignature targetXmlSignature) throws XAdES4jXMLSigException
{
    this.targetXmlSignature = targetXmlSignature;
    this.sigDocument = targetXmlSignature.getDocument();
    this.referencesMappings = null;

    SignedInfo signedInfo = targetXmlSignature.getSignedInfo();
    List<Reference> refs = new ArrayList<Reference>(signedInfo.getLength());
    for (int i = 0; i < signedInfo.getLength(); i++)
    {
        try
        {
            refs.add(signedInfo.item(i));
        } catch (XMLSecurityException ex)
        {
            throw new XAdES4jXMLSigException(String.format("Cannot process the %dth reference", i), ex);
        }
    }
    this.references = Collections.unmodifiableList(refs);
}
 
Example #9
Source File: StaxSecurityContextInInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private SubjectAndPrincipalSecurityToken getSubjectPrincipalToken(List<SecurityEvent> incomingSecurityEventList,
                                                                  Event desiredEvent,
                                                                  Message msg) throws XMLSecurityException {
    for (SecurityEvent event : incomingSecurityEventList) {
        if (desiredEvent == event.getSecurityEventType()) {
            if (event.getSecurityEventType() == WSSecurityEventConstants.USERNAME_TOKEN
                && isUsernameTokenEventAllowed((UsernameTokenSecurityEvent)event, msg)) {
                return ((UsernameTokenSecurityEvent)event).getSecurityToken();
            } else if (event.getSecurityEventType() == WSSecurityEventConstants.SAML_TOKEN
                && isSamlEventAllowed((SamlTokenSecurityEvent)event, msg)) {
                return ((SamlTokenSecurityEvent)event).getSecurityToken();
            } else if (event.getSecurityEventType() == WSSecurityEventConstants.X509Token
                && isUsedForPublicKeySignature(((X509TokenSecurityEvent)event).getSecurityToken())) {
                return ((X509TokenSecurityEvent)event).getSecurityToken();
            } else if (event.getSecurityEventType() == WSSecurityEventConstants.KeyValueToken
                && isUsedForPublicKeySignature(((KeyValueTokenSecurityEvent)event).getSecurityToken())) {
                return ((KeyValueTokenSecurityEvent)event).getSecurityToken();
            } else if (event.getSecurityEventType() == WSSecurityEventConstants.KERBEROS_TOKEN) {
                return ((KerberosTokenSecurityEvent)event).getSecurityToken();
            }
        }
    }
    return null;
}
 
Example #10
Source File: STSStaxTokenValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
private byte[] getBinarySecurityTokenBytes(BinarySecurityTokenType binarySecurityTokenType,
                                           WSSSecurityProperties wssSecurityProperties
) throws XMLSecurityException {

    StringBuilder sb = new StringBuilder();

    for (Object obj : binarySecurityTokenType.getContent()) {
        if (obj instanceof String) {
            sb.append((String)obj);
        } else if (obj instanceof JAXBElement<?>) {
            JAXBElement<?> element = (JAXBElement<?>)obj;
            if (XMLSecurityConstants.TAG_XOP_INCLUDE.equals(element.getName())) {
                Include include = (Include)element.getValue();
                if (include != null && include.getHref() != null && include.getHref().startsWith("cid:")) {
                    CallbackHandler callbackHandler = wssSecurityProperties.getAttachmentCallbackHandler();
                    return AttachmentUtils.getBytesFromAttachment(include.getHref(),
                                                                  callbackHandler,
                                                                  true);
                }
            }
        }
    }

    return Base64.decodeBase64(sb.toString());
}
 
Example #11
Source File: SAMLSignatureProfileValidator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Validate the Signature's SignedInfo Reference.
 * 
 * The SignedInfo must contain exactly 1 Reference.
 * 
 * @param apacheSig the Apache XML Signature instance
 * @return the valid Reference contained within the SignedInfo
 * @throws ValidationException thrown if the Signature does not contain exactly 1 Reference, or if there is an error
 *             obtaining the Reference instance
 */
protected Reference validateReference(XMLSignature apacheSig) throws ValidationException {
    int numReferences = apacheSig.getSignedInfo().getLength();
    if (numReferences != 1) {
        log.error("Signature SignedInfo had invalid number of References: " + numReferences);
        throw new ValidationException("Signature SignedInfo must have exactly 1 Reference element");
    }

    Reference ref = null;
    try {
        ref = apacheSig.getSignedInfo().item(0);
    } catch (XMLSecurityException e) {
        log.error("Apache XML Security exception obtaining Reference", e);
        throw new ValidationException("Could not obtain Reference from Signature/SignedInfo", e);
    }
    if (ref == null) {
        log.error("Signature Reference was null");
        throw new ValidationException("Signature Reference was null");
    }
    return ref;
}
 
Example #12
Source File: XadesHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void before() throws TechnicalConnectorException, XMLSecurityException {
   if (!ArrayUtils.isEmpty(this.specs)) {
      ObjectContainer container = new ObjectContainer(this.sig.getDocument());
      this.sig.appendObject(container);
      QualifyingPropertiesBuilder qualProperties = new QualifyingPropertiesBuilder();
      String xadesSignedId = IdGeneratorFactory.getIdGenerator("uuid").generateId();
      XadesSpecification[] arr$ = this.specs;
      int len$ = arr$.length;

      for(int i$ = 0; i$ < len$; ++i$) {
         XadesSpecification spec = arr$[i$];
         spec.addOptionalBeforeSignatureParts(qualProperties.getSignedProps(), this.sig, this.signatureCredential, xadesSignedId, this.options);
      }

      Document xadesQualPropertiesDocument = qualProperties.buildBeforeSigningAsDocument();
      this.xadesQualProperties = (Element)this.sig.getDocument().importNode(xadesQualPropertiesDocument.getDocumentElement(), true);
      container.appendChild(this.xadesQualProperties);
      this.sig.addResourceResolver(new DocumentResolver(xadesQualPropertiesDocument));
      Transforms xadesTransform = new Transforms(this.sig.getDocument());
      xadesTransform.addTransform("http://www.w3.org/2001/10/xml-exc-c14n#");
      this.sig.addDocument(ref(qualProperties.getSignedProps().getId()), xadesTransform, (String)SignatureUtils.getOption("digestURI", this.options, "http://www.w3.org/2001/04/xmlenc#sha256"), (String)null, "http://uri.etsi.org/01903#SignedProperties");
   }
}
 
Example #13
Source File: XmlSecOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private SecurityToken getSignatureToken(List<SecurityEvent> incomingSecurityEventList)
    throws XMLSecurityException {
    if (incomingSecurityEventList != null) {
        for (int i = 0; i < incomingSecurityEventList.size(); i++) {
            SecurityEvent securityEvent = incomingSecurityEventList.get(i);
            if (securityEvent instanceof TokenSecurityEvent) {
                @SuppressWarnings("unchecked")
                TokenSecurityEvent<? extends SecurityToken> tokenSecurityEvent
                    = (TokenSecurityEvent<? extends SecurityToken>) securityEvent;
                if (tokenSecurityEvent.getSecurityToken().getTokenUsages().contains(
                    SecurityTokenConstants.TokenUsage_Signature)
                ) {
                    return tokenSecurityEvent.getSecurityToken();
                }
            }
        }
    }
    return null;
}
 
Example #14
Source File: XmlSecInInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected SecurityEventListener configureSecurityEventListener(
    final Crypto sigCrypto, final Message msg, XMLSecurityProperties securityProperties
) {
    final List<SecurityEvent> incomingSecurityEventList = new LinkedList<>();
    SecurityEventListener securityEventListener = new SecurityEventListener() {
        @Override
        public void registerSecurityEvent(SecurityEvent securityEvent) throws XMLSecurityException {
            if (securityEvent.getSecurityEventType() == SecurityEventConstants.AlgorithmSuite) {
                if (encryptionProperties != null) {
                    checkEncryptionAlgorithms((AlgorithmSuiteSecurityEvent)securityEvent);
                }
                if (sigProps != null) {
                    checkSignatureAlgorithms((AlgorithmSuiteSecurityEvent)securityEvent);
                }
            } else if (securityEvent.getSecurityEventType() != SecurityEventConstants.EncryptedKeyToken
                && securityEvent instanceof TokenSecurityEvent<?>) {
                checkSignatureTrust(sigCrypto, msg, (TokenSecurityEvent<?>)securityEvent);
            }
            incomingSecurityEventList.add(securityEvent);
        }
    };
    msg.getExchange().put(SecurityEvent.class.getName() + ".in", incomingSecurityEventList);
    msg.put(SecurityEvent.class.getName() + ".in", incomingSecurityEventList);

    return securityEventListener;
}
 
Example #15
Source File: XmlSecInInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void checkEncryptionAlgorithms(AlgorithmSuiteSecurityEvent event)
    throws XMLSecurityException {
    if (XMLSecurityConstants.Enc.equals(event.getAlgorithmUsage())
        && encryptionProperties.getEncryptionSymmetricKeyAlgo() != null
        && !encryptionProperties.getEncryptionSymmetricKeyAlgo().equals(event.getAlgorithmURI())) {
        throw new XMLSecurityException("empty", new Object[] {"The symmetric encryption algorithm "
                                       + event.getAlgorithmURI() + " is not allowed"});
    } else if ((XMLSecurityConstants.Sym_Key_Wrap.equals(event.getAlgorithmUsage())
        || XMLSecurityConstants.Asym_Key_Wrap.equals(event.getAlgorithmUsage()))
        && encryptionProperties.getEncryptionKeyTransportAlgo() != null
        && !encryptionProperties.getEncryptionKeyTransportAlgo().equals(event.getAlgorithmURI())) {
        throw new XMLSecurityException("empty", new Object[] {"The key transport algorithm "
            + event.getAlgorithmURI() + " is not allowed"});
    } else if (XMLSecurityConstants.EncDig.equals(event.getAlgorithmUsage())
        && encryptionProperties.getEncryptionDigestAlgo() != null
        && !encryptionProperties.getEncryptionDigestAlgo().equals(event.getAlgorithmURI())) {
        throw new XMLSecurityException("empty", new Object[] {"The encryption digest algorithm "
            + event.getAlgorithmURI() + " is not allowed"});
    }
}
 
Example #16
Source File: XadesHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void before() throws TechnicalConnectorException, XMLSecurityException {
   if (!ArrayUtils.isEmpty(this.specs)) {
      ObjectContainer container = new ObjectContainer(this.sig.getDocument());
      this.sig.appendObject(container);
      QualifyingPropertiesBuilder qualProperties = new QualifyingPropertiesBuilder();
      String xadesSignedId = IdGeneratorFactory.getIdGenerator("uuid").generateId();
      XadesSpecification[] arr$ = this.specs;
      int len$ = arr$.length;

      for(int i$ = 0; i$ < len$; ++i$) {
         XadesSpecification spec = arr$[i$];
         spec.addOptionalBeforeSignatureParts(qualProperties.getSignedProps(), this.sig, this.signatureCredential, xadesSignedId, this.options);
      }

      Document xadesQualPropertiesDocument = qualProperties.buildBeforeSigningAsDocument();
      this.xadesQualProperties = (Element)this.sig.getDocument().importNode(xadesQualPropertiesDocument.getDocumentElement(), true);
      container.appendChild(this.xadesQualProperties);
      this.sig.addResourceResolver(new DocumentResolver(xadesQualPropertiesDocument));
      Transforms xadesTransform = new Transforms(this.sig.getDocument());
      xadesTransform.addTransform("http://www.w3.org/2001/10/xml-exc-c14n#");
      this.sig.addDocument(ref(qualProperties.getSignedProps().getId()), xadesTransform, (String)SignatureUtils.getOption("digestURI", this.options, "http://www.w3.org/2001/04/xmlenc#sha256"), (String)null, "http://uri.etsi.org/01903#SignedProperties");
   }
}
 
Example #17
Source File: XmlSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void addKeyInfo(Credential signatureCredential, XMLSignature sig) throws TechnicalConnectorException, XMLSecurityException {
   if (signatureCredential.getCertificateChain() != null) {
      Certificate[] arr$ = signatureCredential.getCertificateChain();
      int len$ = arr$.length;

      for(int i$ = 0; i$ < len$; ++i$) {
         Certificate cert = arr$[i$];
         if (sig.getKeyInfo().itemX509Data(0) == null) {
            X509Data x509data = new X509Data(sig.getDocument());
            sig.getKeyInfo().add(x509data);
         }

         sig.getKeyInfo().itemX509Data(0).addCertificate((X509Certificate)cert);
      }
   }

}
 
Example #18
Source File: XmlSecInInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void checkSignatureAlgorithms(AlgorithmSuiteSecurityEvent event)
    throws XMLSecurityException {
    if ((XMLSecurityConstants.Asym_Sig.equals(event.getAlgorithmUsage())
        || XMLSecurityConstants.Sym_Sig.equals(event.getAlgorithmUsage()))
        && sigProps.getSignatureAlgo() != null
        && !sigProps.getSignatureAlgo().equals(event.getAlgorithmURI())) {
        throw new XMLSecurityException("empty", new Object[] {"The signature algorithm "
                                       + event.getAlgorithmURI() + " is not allowed"});
    } else if (XMLSecurityConstants.SigDig.equals(event.getAlgorithmUsage())
        && sigProps.getSignatureDigestAlgo() != null
        && !sigProps.getSignatureDigestAlgo().equals(event.getAlgorithmURI())) {
        throw new XMLSecurityException("empty", new Object[] {"The signature digest algorithm "
            + event.getAlgorithmURI() + " is not allowed"});
    } else if (XMLSecurityConstants.SigC14n.equals(event.getAlgorithmUsage())
        && sigProps.getSignatureC14nMethod() != null
        && !sigProps.getSignatureC14nMethod().equals(event.getAlgorithmURI())) {
        throw new XMLSecurityException("empty", new Object[] {"The signature c14n algorithm "
            + event.getAlgorithmURI() + " is not allowed"});
    } else if (XMLSecurityConstants.SigTransform.equals(event.getAlgorithmUsage())
        && !XMLSecurityConstants.NS_XMLDSIG_ENVELOPED_SIGNATURE.equals(event.getAlgorithmURI())
        && sigProps.getSignatureC14nTransform() != null
        && !sigProps.getSignatureC14nTransform().equals(event.getAlgorithmURI())) {
        throw new XMLSecurityException("empty", new Object[] {"The signature transformation algorithm "
            + event.getAlgorithmURI() + " is not allowed"});
    }
}
 
Example #19
Source File: XadesHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void before() throws TechnicalConnectorException, XMLSecurityException {
   if (!ArrayUtils.isEmpty(this.specs)) {
      ObjectContainer container = new ObjectContainer(this.sig.getDocument());
      this.sig.appendObject(container);
      QualifyingPropertiesBuilder qualProperties = new QualifyingPropertiesBuilder();
      String xadesSignedId = IdGeneratorFactory.getIdGenerator("uuid").generateId();
      XadesSpecification[] arr$ = this.specs;
      int len$ = arr$.length;

      for(int i$ = 0; i$ < len$; ++i$) {
         XadesSpecification spec = arr$[i$];
         spec.addOptionalBeforeSignatureParts(qualProperties.getSignedProps(), this.sig, this.signatureCredential, xadesSignedId, this.options);
      }

      Document xadesQualPropertiesDocument = qualProperties.buildBeforeSigningAsDocument();
      this.xadesQualProperties = (Element)this.sig.getDocument().importNode(xadesQualPropertiesDocument.getDocumentElement(), true);
      container.appendChild(this.xadesQualProperties);
      this.sig.addResourceResolver(new DocumentResolver(xadesQualPropertiesDocument));
      Transforms xadesTransform = new Transforms(this.sig.getDocument());
      xadesTransform.addTransform("http://www.w3.org/2001/10/xml-exc-c14n#");
      this.sig.addDocument(ref(qualProperties.getSignedProps().getId()), xadesTransform, (String)SignatureUtils.getOption("digestURI", this.options, "http://www.w3.org/2001/04/xmlenc#sha256"), (String)null, "http://uri.etsi.org/01903#SignedProperties");
   }
}
 
Example #20
Source File: XmlSecInInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private X509Certificate[] getX509CertificatesForKeyName(Crypto sigCrypto, Message msg, KeyNameSecurityToken token)
    throws XMLSecurityException {
    X509Certificate[] certs;
    KeyNameSecurityToken keyNameSecurityToken = token;
    String keyName = keyNameSecurityToken.getKeyName();
    String alias = null;
    if (sigProps != null && sigProps.getKeyNameAliasMap() != null) {
        alias = sigProps.getKeyNameAliasMap().get(keyName);
    }
    try {
        certs = RSSecurityUtils.getCertificates(sigCrypto, alias);
    } catch (Exception e) {
        throw new XMLSecurityException("empty", new Object[] {"Error during Signature Trust "
            + "validation"});
    }
    return certs;
}
 
Example #21
Source File: XadesHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void before() throws TechnicalConnectorException, XMLSecurityException {
   if (!ArrayUtils.isEmpty(this.specs)) {
      ObjectContainer container = new ObjectContainer(this.sig.getDocument());
      this.sig.appendObject(container);
      QualifyingPropertiesBuilder qualProperties = new QualifyingPropertiesBuilder();
      String xadesSignedId = IdGeneratorFactory.getIdGenerator("uuid").generateId();
      XadesSpecification[] arr$ = this.specs;
      int len$ = arr$.length;

      for(int i$ = 0; i$ < len$; ++i$) {
         XadesSpecification spec = arr$[i$];
         spec.addOptionalBeforeSignatureParts(qualProperties.getSignedProps(), this.sig, this.signatureCredential, xadesSignedId, this.options);
      }

      Document xadesQualPropertiesDocument = qualProperties.buildBeforeSigningAsDocument();
      this.xadesQualProperties = (Element)this.sig.getDocument().importNode(xadesQualPropertiesDocument.getDocumentElement(), true);
      container.appendChild(this.xadesQualProperties);
      this.sig.addResourceResolver(new DocumentResolver(xadesQualPropertiesDocument));
      Transforms xadesTransform = new Transforms(this.sig.getDocument());
      xadesTransform.addTransform("http://www.w3.org/2001/10/xml-exc-c14n#");
      this.sig.addDocument(ref(qualProperties.getSignedProps().getId()), xadesTransform, (String)SignatureUtils.getOption("digestURI", this.options, "http://www.w3.org/2001/04/xmlenc#sha256"), (String)null, "http://uri.etsi.org/01903#SignedProperties");
   }
}
 
Example #22
Source File: XmlSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void addKeyInfo(Credential signatureCredential, XMLSignature sig) throws TechnicalConnectorException, XMLSecurityException {
   if (signatureCredential.getCertificateChain() != null) {
      Certificate[] arr$ = signatureCredential.getCertificateChain();
      int len$ = arr$.length;

      for(int i$ = 0; i$ < len$; ++i$) {
         Certificate cert = arr$[i$];
         if (sig.getKeyInfo().itemX509Data(0) == null) {
            X509Data x509data = new X509Data(sig.getDocument());
            sig.getKeyInfo().add(x509data);
         }

         sig.getKeyInfo().itemX509Data(0).addCertificate((X509Certificate)cert);
      }
   }

}
 
Example #23
Source File: XAdESReferenceValidation.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public List<String> getTransformationNames() {
	if (transforms == null) {
		transforms = new ArrayList<>();
		try {
			Transforms referenceTransforms = reference.getTransforms();
			if (referenceTransforms != null) {
				Element transformsElement = referenceTransforms.getElement();
				NodeList transfromChildNodes = transformsElement.getChildNodes();
				if (transfromChildNodes != null && transfromChildNodes.getLength() > 0) {
					for (int i = 0; i < transfromChildNodes.getLength(); i++) {
						Node transformation = transfromChildNodes.item(i);
						if (Node.ELEMENT_NODE == transformation.getNodeType()) {
							transforms.add(buildTransformationName(transformation));
						}
					}
				}
			}
		} catch (XMLSecurityException e) {
			LOG.warn("Unable to analyze trasnformations", e);
		}
	}
	return transforms;
}
 
Example #24
Source File: XPathTransformParamsMarshaller.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public List<Node> marshalParameters(XPathTransform alg, Document doc)
{
    XPathContainer xpathContainer = new XPathContainer(doc);
    xpathContainer.setXPath(alg.getXPath());
            
    for(Map.Entry<String, String> ns : alg.getNamespaces().entrySet())
    {
        try 
        {
            xpathContainer.setXPathNamespaceContext(ns.getKey(), ns.getValue());
        }catch (XMLSecurityException ex) 
        {
            throw new IllegalArgumentException("Invalid namespaces for XPath query", ex);
        }
    }

    return Collections.singletonList((Node)xpathContainer.getElement());
}
 
Example #25
Source File: ComplexTransform.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] getBytesAfterTranformation(Node node, String uri) {
	if (transformObject == null) {
		buildTransformObject();
	}
	try {
		final XMLSignatureInput xmlSignatureInput = getXMLSignatureInput(node, uri);
		final XMLSignatureInput xmlSignatureInputOut = transformObject.performTransform(xmlSignatureInput);
		return xmlSignatureInputOut.getBytes();
	} catch (IOException | XMLSecurityException e) {
		throw new DSSException(String.format("Cannot process transformation [%s] on the given DOM object. Reason : [%s]", 
				algorithm, e.getMessage()), e);
	}
}
 
Example #26
Source File: AbstractOperation.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected static org.apache.xml.security.stax.securityToken.SecurityToken
findInboundSecurityToken(SecurityEventConstants.Event event,
                         Map<String, Object> messageContext) throws XMLSecurityException {
    @SuppressWarnings("unchecked")
    final List<SecurityEvent> incomingEventList =
        (List<SecurityEvent>) messageContext.get(SecurityEvent.class.getName() + ".in");
    if (incomingEventList != null) {
        for (SecurityEvent incomingEvent : incomingEventList) {
            if (event == incomingEvent.getSecurityEventType()) {
                return ((TokenSecurityEvent<?>)incomingEvent).getSecurityToken();
            }
        }
    }
    return null;
}
 
Example #27
Source File: SCTCanceller.java    From cxf with Apache License 2.0 5 votes vote down vote up
private boolean matchStreamingSignatureSecret(
    Map<String, Object> messageContext, byte[] secretToMatch
) throws XMLSecurityException {
    @SuppressWarnings("unchecked")
    final List<SecurityEvent> incomingEventList =
        (List<SecurityEvent>) messageContext.get(SecurityEvent.class.getName() + ".in");
    if (incomingEventList != null) {
        for (SecurityEvent incomingEvent : incomingEventList) {
            if (WSSecurityEventConstants.SIGNED_PART == incomingEvent.getSecurityEventType()
                || WSSecurityEventConstants.SignedElement
                    == incomingEvent.getSecurityEventType()) {
                org.apache.xml.security.stax.securityToken.SecurityToken token =
                    ((AbstractSecuredElementSecurityEvent)incomingEvent).getSecurityToken();
                if (token != null && token.getSecretKey() != null) {
                    for (String key : token.getSecretKey().keySet()) {
                        Key keyObject = token.getSecretKey().get(key);
                        if (keyObject instanceof SecretKey
                            && MessageDigest.isEqual(secretToMatch, ((SecretKey)keyObject).getEncoded())) {
                            LOG.log(
                                Level.FINE,
                                "Verification of the proof of possession of the key associated with "
                                + "the security context successful."
                            );
                            return true;
                        }
                    }
                }
            }
        }
    }

    return false;
}
 
Example #28
Source File: XAdESTimestampDataBuilder.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private byte[] getReferenceBytes(final Reference reference, final String canonicalizationMethod) throws XMLSecurityException {
	byte[] referencedBytes = reference.getReferencedBytes();
	if (DomUtils.isDOM(referencedBytes)) {
		referencedBytes = DSSXMLUtils.canonicalize(canonicalizationMethod, referencedBytes);
	}
	if (LOG.isTraceEnabled()) {
		LOG.trace("ReferencedBytes : {}", new String(referencedBytes));
	}
	return referencedBytes;
}
 
Example #29
Source File: AbstractPkiFactoryTestSignature.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private String getDigest(DSSDocument doc, boolean toBeCanonicalized) {
	byte[] byteArray = DSSUtils.toByteArray(doc);
	if (toBeCanonicalized) {
		try {
			// we canonicalize to ignore the header (which is not covered by the signature)
			Canonicalizer c14n = Canonicalizer.getInstance(getCanonicalizationMethod());
			byteArray = c14n.canonicalize(byteArray);
		} catch (XMLSecurityException | ParserConfigurationException | IOException | SAXException e) {
			// Not always able to canonicalize (more than one file can be covered (XML +
			// something else) )
		}
	}
	// LOG.info("Bytes : {}", new String(byteArray));
	return Utils.toBase64(DSSUtils.digest(DigestAlgorithm.SHA256, byteArray));
}
 
Example #30
Source File: DSSXMLUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Extracts signing certificate's public key from KeyInfo element of a given signature if present
 * NOTE: can return null (the value is optional)
 * 
 * @param signatureElement {@link Element} representing a signature to get KeyInfo signing certificate for
 * @return {@link PublicKey} of the signature extracted from KeyInfo element if present
 */
public static PublicKey getKeyInfoSigningCertificatePublicKey(final Element signatureElement) {
	Element keyInfoElement = DomUtils.getElement(signatureElement, XMLDSigPaths.KEY_INFO_PATH);
	if (keyInfoElement != null) {
		try {
			KeyInfo keyInfo = new KeyInfo(keyInfoElement, "");
			return keyInfo.getPublicKey();
		} catch (XMLSecurityException e) {
			LOG.warn("Unable to extract signing certificate's public key. Reason : {}", e.getMessage(), e);
		}
	}
	LOG.warn("Unable to extract the public key. Reason : KeyInfo element is null");
	return null;
}