use of org.apache.xml.security.signature.XMLSignature in project OpenAM by OpenRock.
the class AMSignatureProvider method signXMLUsingKeyPass.
/**
* Sign part of the XML document referred by the supplied id attribute
* using enveloped signatures and use exclusive XML canonicalization.
* @param doc XML dom object
* @param certAlias Signer's certificate alias name
* @param encryptedKeyPass Use the supplied encrypted key password to get the private key
* @param algorithm XML signature algorithm
* @param idAttrName attribute name for the id attribute of the node to be
* signed.
* @param id id attribute value of the node to be signed
* @param includeCert if true, include the signing certificate in
* <code>KeyInfo</code>.
* if false, does not include the signing certificate.
* @param xpath expression should uniquely identify a node before which
* @return a signed dom object
* @throws XMLSignatureException if the document could not be signed
*/
public Element signXMLUsingKeyPass(Document doc, String certAlias, String encryptedKeyPass, String algorithm, String idAttrName, String id, boolean includeCert, String xpath) throws XMLSignatureException {
if (doc == null) {
SAMLUtilsCommon.debug.error("signXML: doc is null.");
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullInput"));
}
if (certAlias == null || certAlias.length() == 0) {
SAMLUtilsCommon.debug.error("signXML: certAlias is null.");
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullInput"));
}
Element root = null;
XMLSignature sig = null;
try {
ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, SAMLConstants.PREFIX_DS);
PrivateKey privateKey;
if (encryptedKeyPass == null || encryptedKeyPass.isEmpty()) {
privateKey = keystore.getPrivateKey(certAlias);
} else {
privateKey = keystore.getPrivateKey(certAlias, encryptedKeyPass);
}
if (privateKey == null) {
SAMLUtilsCommon.debug.error("private key is null");
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullprivatekey"));
}
root = (Element) XPathAPI.selectSingleNode(doc, "//*[@" + idAttrName + "=\"" + id + "\"]");
if (root == null) {
SAMLUtilsCommon.debug.error("signXML: could not" + " resolv id attribute");
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("invalidIDAttribute"));
}
// Set the ID attribute if idAttrName is not the default.
if (!idAttrName.equals(DEF_ID_ATTRIBUTE)) {
root.setIdAttribute(idAttrName, true);
}
if (algorithm == null || algorithm.length() == 0) {
algorithm = getKeyAlgorithm(privateKey);
;
}
if (!isValidAlgorithm(algorithm)) {
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("invalidalgorithm"));
}
sig = new XMLSignature(doc, "", algorithm, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
if (xpath == null) {
root.appendChild(sig.getElement());
} else {
Node beforeNode = XPathAPI.selectSingleNode(doc, xpath);
root.insertBefore(sig.getElement(), beforeNode);
}
sig.getSignedInfo().addResourceResolver(new OfflineResolver());
// do transform
Transforms transforms = new Transforms(doc);
transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
String ref = "#" + id;
sig.addDocument(ref, transforms, Constants.ALGO_ID_DIGEST_SHA1);
if (includeCert) {
X509Certificate cert = (X509Certificate) keystore.getX509Certificate(certAlias);
sig.addKeyInfo(cert);
}
sig.sign(privateKey);
} catch (Exception e) {
SAMLUtilsCommon.debug.error("signXML Exception: ", e);
throw new XMLSignatureException(e.getMessage());
}
return (sig.getElement());
}
use of org.apache.xml.security.signature.XMLSignature in project OpenAM by OpenRock.
the class AMSignatureProvider method signXML.
/**
* Sign the xml document using enveloped signatures.
* @param doc XML dom object
* @param certAlias Signer's certificate alias name
* @param algorithm XML signature algorithm
* @return signature dom object
* @throws XMLSignatureException if the document could not be signed
*/
public org.w3c.dom.Element signXML(org.w3c.dom.Document doc, java.lang.String certAlias, java.lang.String algorithm) throws XMLSignatureException {
if (doc == null) {
SAMLUtilsCommon.debug.error("signXML: doc is null.");
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullInput"));
}
if (certAlias == null || certAlias.length() == 0) {
SAMLUtilsCommon.debug.error("signXML: certAlias is null.");
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullInput"));
}
org.w3c.dom.Element root = null;
XMLSignature sig = null;
try {
ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, SAMLConstants.PREFIX_DS);
if (keystore == null) {
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullkeystore"));
}
PrivateKey privateKey = (PrivateKey) keystore.getPrivateKey(certAlias);
if (privateKey == null) {
SAMLUtilsCommon.debug.error("private key is null");
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullprivatekey"));
}
root = doc.getDocumentElement();
if (algorithm == null || algorithm.length() == 0) {
algorithm = getKeyAlgorithm(privateKey);
}
if (!isValidAlgorithm(algorithm)) {
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("invalidalgorithm"));
}
if (c14nMethod == null || c14nMethod.length() == 0) {
sig = new XMLSignature(doc, "", algorithm);
} else {
if (!isValidCanonicalizationMethod(c14nMethod)) {
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("invalidCanonicalizationMethod"));
}
sig = new XMLSignature(doc, "", algorithm, c14nMethod);
}
root.appendChild(sig.getElement());
sig.getSignedInfo().addResourceResolver(new com.sun.identity.saml.xmlsig.OfflineResolver());
// do transform
Transforms transforms = new Transforms(doc);
transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
// such transform due to performance reason.
if (transformAlg != null && transformAlg.length() != 0) {
if (!isValidTransformAlgorithm(transformAlg)) {
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("invalidTransformAlgorithm"));
}
transforms.addTransform(transformAlg);
}
sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
// add certificate
X509Certificate cert = (X509Certificate) keystore.getX509Certificate(certAlias);
sig.addKeyInfo(cert);
sig.sign(privateKey);
} catch (Exception e) {
SAMLUtilsCommon.debug.error("signXML Exception: ", e);
throw new XMLSignatureException(e.getMessage());
}
return (sig.getElement());
}
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());
}
}
}
Aggregations