use of org.apache.xml.security.keys.KeyInfo in project camel by apache.
the class XMLSecurityDataFormat method embedKeyInfoInEncryptedData.
private void embedKeyInfoInEncryptedData(Document document, XMLCipher keyCipher, XMLCipher xmlCipher, Key dataEncryptionkey, Key keyEncryptionKey) throws XMLEncryptionException {
EncryptedKey encryptedKey = keyCipher.encryptKey(document, dataEncryptionkey, mgfAlgorithm, null);
if (addKeyValueForEncryptedKey && keyEncryptionKey instanceof PublicKey) {
KeyInfo keyInfo = new KeyInfo(document);
keyInfo.add((PublicKey) keyEncryptionKey);
encryptedKey.setKeyInfo(keyInfo);
}
KeyInfo keyInfo = new KeyInfo(document);
keyInfo.add(encryptedKey);
EncryptedData encryptedDataElement = xmlCipher.getEncryptedData();
encryptedDataElement.setKeyInfo(keyInfo);
}
use of org.apache.xml.security.keys.KeyInfo 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.keys.KeyInfo 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.keys.KeyInfo 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.keys.KeyInfo in project OpenAM by OpenRock.
the class AMEncryptionProvider method encryptAndReplace.
/**
* Encrypts the given XML element in a given XML Context document.
* @param doc the context XML Document.
* @param element Element to be encrypted.
* @param secretKeyAlg Encryption Key Algorithm.
* @param keyStrength Encryption Key Strength.
* @param kek Key Encryption Key.
* @param kekStrength Key Encryption Key Strength,
* @param providerID Provider ID
* @param isEncryptResourceID A flag indicates whether it's to encrypt
* ResourceID or not.
* @return org.w3c.dom.Document EncryptedResourceID XML Document if
* isEncryptResourceID is set. Otherwise, return the XML Document
* replaced with encrypted data for a given XML element.
*/
private org.w3c.dom.Document encryptAndReplace(org.w3c.dom.Document doc, org.w3c.dom.Element element, java.lang.String secretKeyAlg, int keyStrength, java.security.Key kek, int kekStrength, String providerID, boolean isEncryptResourceID) throws EncryptionException {
if (doc == null || element == null || kek == null) {
EncryptionUtils.debug.error("AMEncryptionProvider.encryptAnd" + "Replace: Null values");
throw new EncryptionException(EncryptionUtils.bundle.getString("nullValues"));
}
SecretKey secretKey = null;
String secretKeyAlgShortName = getEncryptionAlgorithmShortName(secretKeyAlg);
if (providerID != null) {
if (keyMap.containsKey(providerID)) {
secretKey = (SecretKey) keyMap.get(providerID);
} else {
secretKey = generateSecretKey(secretKeyAlgShortName, keyStrength);
keyMap.put(providerID, secretKey);
}
} else {
secretKey = generateSecretKey(secretKeyAlgShortName, keyStrength);
}
if (secretKey == null) {
throw new EncryptionException(EncryptionUtils.bundle.getString("generateKeyError"));
}
try {
XMLCipher cipher = null;
String keyEncAlg = kek.getAlgorithm();
if (keyEncAlg.equals(EncryptionConstants.RSA)) {
cipher = XMLCipher.getInstance(XMLCipher.RSA_v1dot5);
} else if (keyEncAlg.equals(EncryptionConstants.TRIPLEDES)) {
cipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES_KeyWrap);
} else if (keyEncAlg.equals(EncryptionConstants.AES)) {
if (kekStrength == 0 || kekStrength == 128) {
cipher = XMLCipher.getInstance(XMLCipher.AES_128_KeyWrap);
} else if (kekStrength == 192) {
cipher = XMLCipher.getInstance(XMLCipher.AES_192_KeyWrap);
} else if (kekStrength == 256) {
cipher = XMLCipher.getInstance(XMLCipher.AES_256_KeyWrap);
} else {
throw new EncryptionException(EncryptionUtils.bundle.getString("invalidKeyStrength"));
}
} else {
throw new EncryptionException(EncryptionUtils.bundle.getString("unsupportedKeyAlg"));
}
// Encrypt the key with key encryption key
cipher.init(XMLCipher.WRAP_MODE, kek);
EncryptedKey encryptedKey = cipher.encryptKey(doc, secretKey);
KeyInfo insideKi = new KeyInfo(doc);
X509Data x509Data = new X509Data(doc);
x509Data.addCertificate((X509Certificate) keyProvider.getCertificate((PublicKey) kek));
insideKi.add(x509Data);
encryptedKey.setKeyInfo(insideKi);
String ekID = null;
if (isEncryptResourceID) {
ekID = com.sun.identity.saml.common.SAMLUtils.generateID();
encryptedKey.setId(ekID);
}
if (EncryptionUtils.debug.messageEnabled()) {
EncryptionUtils.debug.message("AMEncryptionProvider.encrypt" + "AndReplace: Encrypted key = " + toString(cipher.martial(doc, encryptedKey)));
}
String encAlgorithm = getEncryptionAlgorithm(secretKeyAlgShortName, keyStrength);
cipher = XMLCipher.getInstance(encAlgorithm);
cipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
EncryptedData builder = cipher.getEncryptedData();
KeyInfo builderKeyInfo = builder.getKeyInfo();
if (builderKeyInfo == null) {
builderKeyInfo = new KeyInfo(doc);
builder.setKeyInfo(builderKeyInfo);
}
if (isEncryptResourceID) {
builderKeyInfo.addKeyName(providerID);
builderKeyInfo.addRetrievalMethod("#" + ekID, null, "http://www.w3.org/2001/04/xmlenc#EncryptedKey");
} else {
builderKeyInfo.add(encryptedKey);
}
Document result = cipher.doFinal(doc, element);
if (isEncryptResourceID) {
Element ee = (Element) result.getElementsByTagNameNS("http://www.w3.org/2001/04/xmlenc#", "EncryptedData").item(0);
Node parentNode = ee.getParentNode();
Element newone = result.createElementNS("urn:liberty:disco:2003-08", "EncryptedResourceID");
parentNode.replaceChild(newone, ee);
newone.appendChild(ee);
Element ek = cipher.martial(doc, encryptedKey);
Element carriedName = doc.createElementNS("http://www.w3.org/2001/04/xmlenc#", "xenc:CarriedKeyName");
carriedName.appendChild(doc.createTextNode(providerID));
ek.appendChild(carriedName);
newone.appendChild(ek);
}
return result;
} catch (Exception xe) {
EncryptionUtils.debug.error("AMEncryptionProvider.encryptAnd" + "Replace: XML Encryption error", xe);
throw new EncryptionException(xe);
}
}
Aggregations