use of javax.xml.crypto.dsig.XMLSignature in project OpenAttestation by OpenAttestation.
the class SamlUtil method verifySAMLSignature.
/**
Seeks out the signature element in the given tree, and validates it.
Searches the configured keystore (asking it to function also as a
truststore) for a certificate with a matching fingerprint.
*
* Certificates trusted for SAML-signing must be marked with the
* tag "(saml)" or "(SAML)" in their alias
*
@return true if the signature validates and we know the signer;
false otherwise
*/
public boolean verifySAMLSignature(Element target, X509Certificate[] trustedSigners) throws MarshalException, XMLSignatureException, KeyStoreException {
// Validate the signature -- i.e. SAML object is pristine:
NodeList nl = target.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
if (nl.getLength() == 0) {
throw new IllegalArgumentException("Cannot find Signature element");
}
DOMValidateContext context = new DOMValidateContext(new KeyValueKeySelector(), nl.item(0));
// MarshalException
XMLSignature signature = factory.unmarshalXMLSignature(context);
log.debug("signature.validate(context): " + signature.validate(context));
for (Object keyInfoItem : signature.getKeyInfo().getContent()) {
if (keyInfoItem instanceof X509Data) {
for (Object X509Item : ((X509Data) keyInfoItem).getContent()) {
if (X509Item instanceof X509Certificate) {
X509Certificate theirCert = (X509Certificate) X509Item;
log.debug("Found X509 certificate in XML: {}", theirCert.getSubjectX500Principal().getName());
//theirCert.get
for (X509Certificate ourCert : trustedSigners) {
if (ourCert.equals(theirCert)) {
log.debug("Bingo!! match for cert: " + ourCert.getSubjectX500Principal().getName());
return true;
} else {
log.info("No match for cert: " + ourCert.getSubjectX500Principal().getName());
}
}
}
}
}
}
if (!signature.validate(context)) {
// XMLSignatureException
log.warn("XML signature is not valid");
return false;
}
// Find a trusted cert -- i.e. the signer is actually someone we trust:
for (Object keyInfoItem : signature.getKeyInfo().getContent()) {
if (keyInfoItem instanceof X509Data) {
for (Object X509Item : ((X509Data) keyInfoItem).getContent()) {
if (X509Item instanceof X509Certificate) {
X509Certificate theirCert = (X509Certificate) X509Item;
log.debug("Found X509 certificate in XML: {}", theirCert.getSubjectX500Principal().getName());
for (X509Certificate ourCert : trustedSigners) {
if (ourCert.equals(theirCert)) {
return true;
}
}
}
}
}
}
log.warn("Signature was valid, but signer was not known.");
return false;
}
use of javax.xml.crypto.dsig.XMLSignature in project camel by apache.
the class XmlSignerProcessor method sign.
protected Document sign(final Message out) throws Exception {
try {
XMLSignatureFactory fac;
// not work
try {
fac = XMLSignatureFactory.getInstance("DOM", "ApacheXMLDSig");
} catch (NoSuchProviderException ex) {
fac = XMLSignatureFactory.getInstance("DOM");
}
final Node node = getMessageBodyNode(out);
if (getConfiguration().getKeyAccessor() == null) {
throw new XmlSignatureNoKeyException("Key accessor is missing for XML signature generation. Specify a key accessor in the configuration.");
}
final KeySelector keySelector = getConfiguration().getKeyAccessor().getKeySelector(out);
if (keySelector == null) {
throw new XmlSignatureNoKeyException("Key selector is missing for XML signature generation. Specify a key selector in the configuration.");
}
SignatureType signatureType = determineSignatureType(out);
final List<String> contentReferenceUris = getContentReferenceUris(out, signatureType, node);
Node lastParent = null;
// only in the detached case there can be several
for (final String contentReferenceUri : contentReferenceUris) {
// the method KeyAccessor.getKeyInfo must be called after the method KeyAccessor.getKeySelector, this is part of the interface contract!
// and this method must be called within the loop over the content reference URIs, because for each signature the key info ID must be different
final KeyInfo keyInfo = getConfiguration().getKeyAccessor().getKeyInfo(out, node, fac.getKeyInfoFactory());
String signatureId = getConfiguration().getSignatureId();
if (signatureId == null) {
signatureId = "_" + UUID.randomUUID().toString();
} else if (signatureId.isEmpty()) {
// indicator that no signature Id attribute shall be generated
signatureId = null;
}
// parent only relevant for enveloped or detached signature
Node parent = getParentOfSignature(out, node, contentReferenceUri, signatureType);
if (parent == null) {
// for enveloping signature, create new document
parent = XmlSignatureHelper.newDocumentBuilder(Boolean.TRUE).newDocument();
}
lastParent = parent;
XmlSignatureProperties.Input input = new InputBuilder().contentDigestAlgorithm(getDigestAlgorithmUri()).keyInfo(keyInfo).message(out).messageBodyNode(node).parent(parent).signatureAlgorithm(getConfiguration().getSignatureAlgorithm()).signatureFactory(fac).signatureId(signatureId).contentReferenceUri(contentReferenceUri).signatureType(signatureType).prefixForXmlSignatureNamespace(getConfiguration().getPrefixForXmlSignatureNamespace()).build();
XmlSignatureProperties.Output properties = getSignatureProperties(input);
// the signature properties can overwrite the signature Id
if (properties != null && properties.getSignatureId() != null && !properties.getSignatureId().isEmpty()) {
signatureId = properties.getSignatureId();
}
List<? extends XMLObject> objects = getObjects(input, properties);
List<? extends Reference> refs = getReferences(input, properties, getKeyInfoId(keyInfo));
SignedInfo si = createSignedInfo(fac, refs);
DOMSignContext dsc = createAndConfigureSignContext(parent, keySelector);
XMLSignature signature = fac.newXMLSignature(si, keyInfo, objects, signatureId, null);
// generate the signature
signature.sign(dsc);
}
return XmlSignatureHelper.getDocument(lastParent);
} catch (XMLSignatureException se) {
if (se.getCause() instanceof InvalidKeyException) {
throw new XmlSignatureInvalidKeyException(se.getMessage(), se);
} else {
throw new XmlSignatureException(se);
}
} catch (GeneralSecurityException e) {
// like NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException
throw new XmlSignatureException(e);
}
}
use of javax.xml.crypto.dsig.XMLSignature in project cas by apereo.
the class AbstractSamlObjectBuilder method signSamlElement.
/**
* Sign SAML element.
*
* @param element the element
* @param privKey the priv key
* @param pubKey the pub key
* @return the element
*/
private static org.jdom.Element signSamlElement(final org.jdom.Element element, final PrivateKey privKey, final PublicKey pubKey) {
try {
final String providerName = System.getProperty("jsr105Provider", SIGNATURE_FACTORY_PROVIDER_CLASS);
final Class<?> clazz = Class.forName(providerName);
final XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance("DOM", (Provider) clazz.getDeclaredConstructor().newInstance());
final List<Transform> envelopedTransform = CollectionUtils.wrap(sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
final Reference ref = sigFactory.newReference(StringUtils.EMPTY, sigFactory.newDigestMethod(DigestMethod.SHA1, null), envelopedTransform, null, null);
// Create the SignatureMethod based on the type of key
final SignatureMethod signatureMethod;
final String algorithm = pubKey.getAlgorithm();
switch(algorithm) {
case "DSA":
signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null);
break;
case "RSA":
signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
break;
default:
throw new IllegalArgumentException("Error signing SAML element: Unsupported type of key");
}
final CanonicalizationMethod canonicalizationMethod = sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null);
// Create the SignedInfo
final SignedInfo signedInfo = sigFactory.newSignedInfo(canonicalizationMethod, signatureMethod, CollectionUtils.wrap(ref));
// Create a KeyValue containing the DSA or RSA PublicKey
final KeyInfoFactory keyInfoFactory = sigFactory.getKeyInfoFactory();
final KeyValue keyValuePair = keyInfoFactory.newKeyValue(pubKey);
// Create a KeyInfo and add the KeyValue to it
final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(CollectionUtils.wrap(keyValuePair));
// Convert the JDOM document to w3c (Java XML signature API requires w3c representation)
final Element w3cElement = toDom(element);
// Create a DOMSignContext and specify the DSA/RSA PrivateKey and
// location of the resulting XMLSignature's parent element
final DOMSignContext dsc = new DOMSignContext(privKey, w3cElement);
final Node xmlSigInsertionPoint = getXmlSignatureInsertLocation(w3cElement);
dsc.setNextSibling(xmlSigInsertionPoint);
// Marshal, generate (and sign) the enveloped signature
final XMLSignature signature = sigFactory.newXMLSignature(signedInfo, keyInfo);
signature.sign(dsc);
return toJdom(w3cElement);
} catch (final Exception e) {
throw new IllegalArgumentException("Error signing SAML element: " + e.getMessage(), e);
}
}
use of javax.xml.crypto.dsig.XMLSignature in project santuario-java by apache.
the class PKSignatureAlgorithmTest method test_create_signature_enveloping.
private void test_create_signature_enveloping(SignatureMethod sm, DigestMethod dm, KeyInfo ki, Key signingKey, KeySelector ks) throws Exception {
// create reference
Reference ref = fac.newReference("#DSig.Object_1", dm, null, XMLObject.TYPE, null);
// create SignedInfo
SignedInfo si = fac.newSignedInfo(withoutComments, sm, Collections.singletonList(ref));
Document doc = db.newDocument();
// create Objects
Element webElem = doc.createElementNS(null, "Web");
Text text = doc.createTextNode("up up and away");
webElem.appendChild(text);
XMLObject obj = fac.newXMLObject(Collections.singletonList(new DOMStructure(webElem)), "DSig.Object_1", "text/xml", null);
// create XMLSignature
XMLSignature sig = fac.newXMLSignature(si, ki, Collections.singletonList(obj), null, null);
DOMSignContext dsc = new DOMSignContext(signingKey, doc);
dsc.setDefaultNamespacePrefix("dsig");
sig.sign(dsc);
TestUtils.validateSecurityOrEncryptionElement(doc.getDocumentElement());
// XMLUtils.outputDOM(doc.getDocumentElement(), System.out);
DOMValidateContext dvc = new DOMValidateContext(ks, doc.getDocumentElement());
XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
assertTrue(sig.equals(sig2));
assertTrue(sig2.validate(dvc));
}
use of javax.xml.crypto.dsig.XMLSignature in project santuario-java by apache.
the class SignatureDigestMethodTest method test_create_signature_enveloping.
private void test_create_signature_enveloping(SignatureMethod sm, DigestMethod dm, KeyInfo ki, Key signingKey, KeySelector ks) throws Exception {
// create reference
Reference ref = fac.newReference("#DSig.Object_1", dm, null, XMLObject.TYPE, null);
// create SignedInfo
SignedInfo si = fac.newSignedInfo(withoutComments, sm, Collections.singletonList(ref));
Document doc = db.newDocument();
// create Objects
Element webElem = doc.createElementNS(null, "Web");
Text text = doc.createTextNode("up up and away");
webElem.appendChild(text);
XMLObject obj = fac.newXMLObject(Collections.singletonList(new DOMStructure(webElem)), "DSig.Object_1", "text/xml", null);
// create XMLSignature
XMLSignature sig = fac.newXMLSignature(si, ki, Collections.singletonList(obj), null, null);
DOMSignContext dsc = new DOMSignContext(signingKey, doc);
dsc.setDefaultNamespacePrefix("dsig");
sig.sign(dsc);
TestUtils.validateSecurityOrEncryptionElement(doc.getDocumentElement());
// XMLUtils.outputDOM(doc.getDocumentElement(), System.out);
DOMValidateContext dvc = new DOMValidateContext(ks, doc.getDocumentElement());
XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
assertTrue(sig.equals(sig2));
assertTrue(sig2.validate(dvc));
}
Aggregations