use of org.apache.xml.security.signature.XMLSignature in project OpenAM by OpenRock.
the class AMSignatureProvider method verifyXMLSignature.
/**
* Verify all the signatures of the xml document
* @param wsfVersion the web services version.
* @param doc XML dom document whose signature to be verified
* @param certAlias certAlias alias for Signer's certificate, this is used
* to search signer's public certificate if it is not presented in
* ds:KeyInfo
* @return true if the xml signature is verified, false otherwise
* @exception XMLSignatureException if problem occurs during verification
*/
public boolean verifyXMLSignature(String wsfVersion, String certAlias, Document doc) throws XMLSignatureException {
if (doc == null) {
SAMLUtilsCommon.debug.error("verifyXMLSignature:" + " document is null.");
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullInput"));
}
try {
this.wsfVersion = wsfVersion;
String wsuNS = SAMLConstants.NS_WSU;
String wsseNS = SAMLConstants.NS_WSSE;
if ((wsfVersion != null) && (wsfVersion.equals(SOAPBindingConstants.WSF_11_VERSION))) {
wsuNS = WSSEConstants.NS_WSU_WSF11;
wsseNS = WSSEConstants.NS_WSSE_WSF11;
}
Element wsucontext = org.apache.xml.security.utils.XMLUtils.createDSctx(doc, "wsu", wsuNS);
NodeList wsuNodes = (NodeList) XPathAPI.selectNodeList(doc, "//*[@wsu:Id]", wsucontext);
if ((wsuNodes != null) && (wsuNodes.getLength() != 0)) {
for (int i = 0; i < wsuNodes.getLength(); i++) {
Element elem = (Element) wsuNodes.item(i);
String id = elem.getAttributeNS(wsuNS, "Id");
if ((id != null) && (id.length() != 0)) {
elem.setIdAttributeNS(wsuNS, "Id", true);
}
}
}
Element nscontext = org.apache.xml.security.utils.XMLUtils.createDSctx(doc, "ds", Constants.SignatureSpecNS);
NodeList sigElements = XPathAPI.selectNodeList(doc, "//ds:Signature", nscontext);
if (SAMLUtilsCommon.debug.messageEnabled()) {
SAMLUtilsCommon.debug.message("verifyXMLSignature: " + "sigElements size = " + sigElements.getLength());
}
X509Certificate newcert = keystore.getX509Certificate(certAlias);
PublicKey key = keystore.getPublicKey(certAlias);
Element sigElement = null;
//loop
for (int i = 0; i < sigElements.getLength(); i++) {
sigElement = (Element) sigElements.item(i);
if (SAMLUtilsCommon.debug.messageEnabled()) {
SAMLUtilsCommon.debug.message("Sig(" + i + ") = " + XMLUtils.print(sigElement));
}
Element refElement;
try {
refElement = (Element) XPathAPI.selectSingleNode(sigElement, "//ds:Reference[1]", nscontext);
} catch (TransformerException te) {
throw new XMLSignatureException(te);
}
String refUri = refElement.getAttribute("URI");
String signedId = null;
Element parentElement = (Element) sigElement.getParentNode();
if (parentElement != null) {
String idAttrName = null;
if ("Assertion".equals(parentElement.getLocalName())) {
idAttrName = "AssertionID";
} else if ("Response".equals(parentElement.getLocalName())) {
idAttrName = "ResponseID";
} else if ("Request".equals(parentElement.getLocalName())) {
idAttrName = "RequestID";
} else {
throw new UnsupportedOperationException("Enveloping and detached XML signatures are no longer" + " supported");
}
if (idAttrName != null) {
parentElement.setIdAttribute(idAttrName, true);
signedId = parentElement.getAttribute(idAttrName);
}
}
//no longer supported.
if (refUri == null || signedId == null || !refUri.substring(1).equals(signedId)) {
SAMLUtilsCommon.debug.error("Signature reference ID does not match with element ID");
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("uriNoMatchWithId"));
}
XMLSignature signature = new XMLSignature(sigElement, "");
signature.addResourceResolver(new com.sun.identity.saml.xmlsig.OfflineResolver());
KeyInfo ki = signature.getKeyInfo();
PublicKey pk = this.getX509PublicKey(doc, ki);
if (pk != null) {
// verify using public key
if (signature.checkSignatureValue(pk)) {
if (SAMLUtilsCommon.debug.messageEnabled()) {
SAMLUtilsCommon.debug.message("verifyXMLSignature:" + " Signature " + i + " verified");
}
} else {
if (SAMLUtilsCommon.debug.messageEnabled()) {
SAMLUtilsCommon.debug.message("verifyXMLSignature:" + " Signature Verfication failed");
}
return false;
}
} else {
if (certAlias == null || certAlias.equals("")) {
if (SAMLUtilsCommon.debug.messageEnabled()) {
SAMLUtilsCommon.debug.message("verifyXMLSignature:" + "Certificate Alias is null");
}
return false;
}
if (SAMLUtilsCommon.debug.messageEnabled()) {
SAMLUtilsCommon.debug.message("Could not find a KeyInfo, " + "try to use certAlias");
}
if (newcert != null) {
if (signature.checkSignatureValue(newcert)) {
if (SAMLUtilsCommon.debug.messageEnabled()) {
SAMLUtilsCommon.debug.message("verifyXMLSignature:" + " Signature " + i + " verified");
}
} else {
return false;
}
} else {
if (key != null) {
if (signature.checkSignatureValue(key)) {
if (SAMLUtilsCommon.debug.messageEnabled()) {
SAMLUtilsCommon.debug.message("verifyXMLSignature: Signature " + i + " verified");
}
} else {
return false;
}
} else {
SAMLUtilsCommon.debug.error("Could not find public key" + " based on certAlias to verify signature");
return false;
}
}
}
}
return true;
} catch (Exception ex) {
SAMLUtilsCommon.debug.error("verifyXMLSignature Exception: ", ex);
throw new XMLSignatureException(ex.getMessage());
}
}
use of org.apache.xml.security.signature.XMLSignature in project OpenAM by OpenRock.
the class AMSignatureProvider method signWithWSSX509TokenProfile.
/**
* Sign part of the xml document referered by the supplied a list
* of id attributes of nodes
* @param doc XML dom object
* @param cert Signer's certificate
* @param algorithm XML signature algorithm
* @param ids list of id attribute values of nodes to be signed
* @param wsfVersion the web services version.
* @return X509 Security Token signature
* @throws XMLSignatureException if the document could not be signed
*/
public Element signWithWSSX509TokenProfile(Document doc, java.security.cert.Certificate cert, String algorithm, List ids, String wsfVersion) throws XMLSignatureException {
if (doc == null) {
SAMLUtilsCommon.debug.error("signXML: doc is null.");
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullInput"));
}
if (SAMLUtilsCommon.debug.messageEnabled()) {
SAMLUtilsCommon.debug.message("Soap Envlope: " + XMLUtils.print(doc.getDocumentElement()));
}
this.wsfVersion = wsfVersion;
String wsseNS = SAMLConstants.NS_WSSE;
String wsuNS = SAMLConstants.NS_WSU;
if ((wsfVersion != null) && (wsfVersion.equals(SOAPBindingConstants.WSF_11_VERSION))) {
wsseNS = WSSEConstants.NS_WSSE_WSF11;
wsuNS = WSSEConstants.NS_WSU_WSF11;
}
Element root = (Element) doc.getDocumentElement().getElementsByTagNameNS(wsseNS, SAMLConstants.TAG_SECURITY).item(0);
XMLSignature signature = null;
try {
ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, SAMLConstants.PREFIX_DS);
Element wsucontext = org.apache.xml.security.utils.XMLUtils.createDSctx(doc, "wsu", wsuNS);
NodeList wsuNodes = (NodeList) XPathAPI.selectNodeList(doc, "//*[@wsu:Id]", wsucontext);
if ((wsuNodes != null) && (wsuNodes.getLength() != 0)) {
for (int i = 0; i < wsuNodes.getLength(); i++) {
Element elem = (Element) wsuNodes.item(i);
String id = elem.getAttributeNS(wsuNS, "Id");
if (id != null && id.length() != 0) {
elem.setIdAttributeNS(wsuNS, "Id", true);
}
}
}
String certAlias = keystore.getCertificateAlias(cert);
PrivateKey privateKey = (PrivateKey) keystore.getPrivateKey(certAlias);
if (privateKey == null) {
SAMLUtilsCommon.debug.error("private key is null");
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullprivatekey"));
}
// to avoid code duplication
if (algorithm == null || algorithm.length() == 0) {
algorithm = getKeyAlgorithm(privateKey);
}
if (!isValidAlgorithm(algorithm)) {
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("invalidalgorithm"));
}
signature = new XMLSignature(doc, "", algorithm, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
root.appendChild(signature.getElement());
int size = ids.size();
for (int i = 0; i < size; ++i) {
Transforms transforms = new Transforms(doc);
transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
String id = (String) ids.get(i);
if (SAMLUtilsCommon.debug.messageEnabled()) {
SAMLUtilsCommon.debug.message("id = " + id);
}
signature.addDocument("#" + id, transforms, Constants.ALGO_ID_DIGEST_SHA1);
}
KeyInfo keyInfo = signature.getKeyInfo();
Element securityTokenRef = doc.createElementNS(wsseNS, SAMLConstants.TAG_SECURITYTOKENREFERENCE);
keyInfo.addUnknownElement(securityTokenRef);
securityTokenRef.setAttributeNS(SAMLConstants.NS_XMLNS, SAMLConstants.TAG_XMLNS, wsseNS);
securityTokenRef.setAttributeNS(SAMLConstants.NS_XMLNS, SAMLConstants.TAG_XMLNS_SEC, SAMLConstants.NS_SEC);
securityTokenRef.setAttributeNS(null, SAMLConstants.TAG_USAGE, SAMLConstants.TAG_SEC_MESSAGEAUTHENTICATION);
Element bsf = (Element) root.getElementsByTagNameNS(wsseNS, SAMLConstants.BINARYSECURITYTOKEN).item(0);
String certId = bsf.getAttributeNS(wsuNS, SAMLConstants.TAG_ID);
Element reference = doc.createElementNS(wsseNS, SAMLConstants.TAG_REFERENCE);
securityTokenRef.appendChild(reference);
reference.setAttributeNS(null, SAMLConstants.TAG_URI, "#" + certId);
signature.sign(privateKey);
} catch (Exception e) {
SAMLUtilsCommon.debug.error("signWithWSSX509TokenProfile" + " Exception: ", e);
throw new XMLSignatureException(e.getMessage());
}
return (signature.getElement());
}
use of org.apache.xml.security.signature.XMLSignature in project OpenAM by OpenRock.
the class SAML2MetaSecurityUtils method verifySignature.
/**
* Verifies signatures in entity descriptor represented by the
* <code>Document</code>.
* @param doc The document.
* @throws SAML2MetaException if unable to verify the entity descriptor.
*/
public static void verifySignature(Document doc) throws SAML2MetaException {
NodeList sigElements = null;
try {
Element nscontext = org.apache.xml.security.utils.XMLUtils.createDSctx(doc, "ds", Constants.SignatureSpecNS);
sigElements = XPathAPI.selectNodeList(doc, "//ds:Signature", nscontext);
} catch (Exception ex) {
if (debug.messageEnabled()) {
debug.message("SAML2MetaSecurityUtils.verifySignature:", ex);
throw new SAML2MetaException(ex.getMessage());
}
}
int numSigs = sigElements.getLength();
if (debug.messageEnabled()) {
debug.message("SAML2MetaSecurityUtils.verifySignature:" + " # of signatures = " + numSigs);
}
if (numSigs == 0) {
return;
}
// If there are signatures then explicitly identify the ID Attribute, See comments section of
// http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8017265
doc.getDocumentElement().setIdAttribute(SAML2Constants.ID, true);
initializeKeyStore();
for (int i = 0; i < numSigs; i++) {
Element sigElement = (Element) sigElements.item(i);
String sigParentName = sigElement.getParentNode().getLocalName();
Object[] objs = { sigParentName };
if (debug.messageEnabled()) {
debug.message("SAML2MetaSecurityUtils.verifySignature: " + "verifying signature under " + sigParentName);
}
try {
XMLSignature signature = new XMLSignature(sigElement, "");
signature.addResourceResolver(new com.sun.identity.saml.xmlsig.OfflineResolver());
KeyInfo ki = signature.getKeyInfo();
X509Certificate x509cert = null;
if (ki != null && ki.containsX509Data()) {
if (keyStore != null) {
StorageResolver sr = new StorageResolver(new KeyStoreResolver(keyStore));
ki.addStorageResolver(sr);
}
x509cert = ki.getX509Certificate();
}
if (x509cert == null) {
if (debug.messageEnabled()) {
debug.message("SAML2MetaSecurityUtils.verifySignature:" + " try to find cert in KeyDescriptor");
}
String xpath = "following-sibling::*[local-name()=\"" + TAG_KEY_DESCRIPTOR + "\" and namespace-uri()=\"" + NS_META + "\"]";
Node node = XPathAPI.selectSingleNode(sigElement, xpath);
if (node != null) {
Element kd = (Element) node;
String use = kd.getAttributeNS(null, ATTR_USE);
if ((use.length() == 0) || use.equals("signing")) {
NodeList nl = kd.getChildNodes();
for (int j = 0; j < nl.getLength(); j++) {
Node child = nl.item(j);
if (child.getNodeType() == Node.ELEMENT_NODE) {
String localName = child.getLocalName();
String ns = child.getNamespaceURI();
if (TAG_KEY_INFO.equals(localName) && NS_XMLSIG.equals(ns)) {
ki = new KeyInfo((Element) child, "");
if (ki.containsX509Data()) {
if (keyStore != null) {
KeyStoreResolver ksr = new KeyStoreResolver(keyStore);
StorageResolver sr = new StorageResolver(ksr);
ki.addStorageResolver(sr);
}
x509cert = ki.getX509Certificate();
}
}
break;
}
}
}
}
}
if (x509cert == null) {
throw new SAML2MetaException("verify_no_cert", objs);
}
if (checkCert && ((keyProvider == null) || (keyProvider.getCertificateAlias(x509cert) == null))) {
throw new SAML2MetaException("untrusted_cert", objs);
}
PublicKey pk = x509cert.getPublicKey();
if (!signature.checkSignatureValue(pk)) {
throw new SAML2MetaException("verify_fail", objs);
}
} catch (SAML2MetaException sme) {
throw sme;
} catch (Exception ex) {
debug.error("SAML2MetaSecurityUtils.verifySignature: ", ex);
throw new SAML2MetaException(Locale.getString(SAML2MetaUtils.resourceBundle, "verify_fail", objs) + "\n" + ex.getMessage());
}
}
}
use of org.apache.xml.security.signature.XMLSignature in project OpenAM by OpenRock.
the class FMSigProvider method sign.
/**
* Sign the xml document node whose identifying attribute value
* is as supplied, using enveloped signatures and use exclusive xml
* canonicalization. The resulting signature is inserted after the
* first child node (normally Issuer element for SAML2) of the node
* to be signed.
* @param xmlString String representing an XML document to be signed
* @param idValue id attribute value of the root node to be signed
* @param privateKey Signing key
* @param cert Certificate which contain the public key correlated to
* the signing key; It if is not null, then the signature
* will include the certificate; Otherwise, the signature
* will not include any certificate
* @return Element representing the signature element
* @throws SAML2Exception if the document could not be signed
*/
public Element sign(String xmlString, String idValue, PrivateKey privateKey, X509Certificate cert) throws SAML2Exception {
String classMethod = "FMSigProvider.sign: ";
if (xmlString == null || xmlString.length() == 0 || idValue == null || idValue.length() == 0 || privateKey == null) {
SAML2SDKUtils.debug.error(classMethod + "Either input xml string or id value or " + "private key 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 root = doc.getDocumentElement();
XMLSignature sig = null;
try {
ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, SAMLConstants.PREFIX_DS);
} catch (XMLSecurityException xse1) {
throw new SAML2Exception(xse1);
}
root.setIdAttribute(SAML2Constants.ID, true);
try {
if ((sigAlg == null) || (sigAlg.trim().length() == 0)) {
if (privateKey.getAlgorithm().equalsIgnoreCase(SAML2Constants.DSA)) {
sigAlg = XMLSignature.ALGO_ID_SIGNATURE_DSA;
} else {
if (privateKey.getAlgorithm().equalsIgnoreCase(SAML2Constants.RSA)) {
sigAlg = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
}
}
}
sig = new XMLSignature(doc, "", sigAlg, c14nMethod);
} catch (XMLSecurityException xse2) {
throw new SAML2Exception(xse2);
}
Node firstChild = root.getFirstChild();
while (firstChild != null && (firstChild.getLocalName() == null || !firstChild.getLocalName().equals("Issuer"))) {
firstChild = firstChild.getNextSibling();
}
Node nextSibling = null;
if (firstChild != null) {
nextSibling = firstChild.getNextSibling();
}
if (nextSibling == null) {
root.appendChild(sig.getElement());
} else {
root.insertBefore(sig.getElement(), nextSibling);
}
sig.getSignedInfo().addResourceResolver(new com.sun.identity.saml.xmlsig.OfflineResolver());
Transforms transforms = new Transforms(doc);
try {
transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
} catch (TransformationException te1) {
throw new SAML2Exception(te1);
}
try {
transforms.addTransform(transformAlg);
} catch (TransformationException te2) {
throw new SAML2Exception(te2);
}
String ref = "#" + idValue;
try {
sig.addDocument(ref, transforms, Constants.ALGO_ID_DIGEST_SHA1);
} catch (XMLSignatureException sige1) {
throw new SAML2Exception(sige1);
}
if (cert != null) {
try {
sig.addKeyInfo(cert);
} catch (XMLSecurityException xse3) {
throw new SAML2Exception(xse3);
}
}
try {
sig.sign(privateKey);
} catch (XMLSignatureException sige2) {
throw new SAML2Exception(sige2);
}
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message(classMethod + "Signing is successful.");
}
return sig.getElement();
}
use of org.apache.xml.security.signature.XMLSignature in project xades4j by luisgoncalves.
the class SignerBES method createSignature.
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);
}
}
Aggregations