List of usage examples for org.w3c.dom Element setAttributeNS
public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException;
From source file:org.apache.ws.security.message.WSSecEncrypt.java
private Vector doEncryption(Document doc, SecretKey secretKey, Vector references) throws WSSecurityException { KeyInfo keyInfo = null;/*from w w w . j a v a2 s. c om*/ // Prepare KeyInfo if useKeyIdentifier is set if (useKeyIdentifier && keyIdentifierType == WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER) { keyInfo = new KeyInfo(document); SecurityTokenReference secToken = new SecurityTokenReference(document); if (this.customReferenceValue != null) { secToken.setKeyIdentifierEncKeySHA1(this.customReferenceValue); } else { secToken.setKeyIdentifierEncKeySHA1(getSHA1(encryptedEphemeralKey)); } keyInfo.addUnknownElement(secToken.getElement()); Element keyInfoElement = keyInfo.getElement(); keyInfoElement.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX, WSConstants.SIG_NS); } return doEncryption(doc, secretKey, keyInfo, references); }
From source file:org.apache.ws.security.message.WSSecEncrypt.java
private Vector doEncryption(Document doc, SecretKey secretKey, KeyInfo keyInfo, Vector references) throws WSSecurityException { XMLCipher xmlCipher = null;/*from w w w. j a v a2 s.c om*/ try { xmlCipher = XMLCipher.getInstance(symEncAlgo); } catch (XMLEncryptionException e3) { throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, e3); } Vector encDataRef = new Vector(); boolean cloneKeyInfo = false; for (int part = 0; part < references.size(); part++) { WSEncryptionPart encPart = (WSEncryptionPart) references.get(part); String idToEnc = encPart.getId(); String elemName = encPart.getName(); String nmSpace = encPart.getNamespace(); String modifier = encPart.getEncModifier(); // // Third step: get the data to encrypt. // Element body = null; if (idToEnc != null) { body = WSSecurityUtil.findElementById(document.getDocumentElement(), idToEnc, WSConstants.WSU_NS); if (body == null) { body = WSSecurityUtil.findElementById(document.getDocumentElement(), idToEnc, null); } } else { body = (Element) WSSecurityUtil.findElement(document, elemName, nmSpace); } if (body == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "noEncElement", new Object[] { "{" + nmSpace + "}" + elemName }); } boolean content = modifier.equals("Content") ? true : false; String xencEncryptedDataId = wssConfig.getIdAllocator().createId("EncDataId-", body); encPart.setEncId(xencEncryptedDataId); cloneKeyInfo = true; if (keyInfo == null) { keyInfo = new KeyInfo(document); SecurityTokenReference secToken = new SecurityTokenReference(document); if (useKeyIdentifier && SecurityTokenReference.SAML_ID_URI.equals(customReferenceValue)) { secToken.setSAMLKeyIdentifier((encKeyIdDirectId ? "" : "#") + encKeyId); } else { Reference ref = new Reference(document); if (encKeyIdDirectId) { ref.setURI(encKeyId); } else { ref.setURI("#" + encKeyId); } if (encKeyValueType != null) { ref.setValueType(encKeyValueType); } secToken.setReference(ref); } keyInfo.addUnknownElement(secToken.getElement()); Element keyInfoElement = keyInfo.getElement(); keyInfoElement.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX, WSConstants.SIG_NS); } // // Fourth step: encrypt data, and set necessary attributes in // xenc:EncryptedData // try { if (modifier.equals("Header")) { Element elem = doc.createElementNS(WSConstants.WSSE11_NS, "wsse11:" + WSConstants.ENCRYPTED_HEADER); WSSecurityUtil.setNamespace(elem, WSConstants.WSSE11_NS, WSConstants.WSSE11_PREFIX); String wsuPrefix = WSSecurityUtil.setNamespace(elem, WSConstants.WSU_NS, WSConstants.WSU_PREFIX); elem.setAttributeNS(WSConstants.WSU_NS, wsuPrefix + ":Id", wssConfig.getIdAllocator().createId("EncHeader-", body)); NamedNodeMap map = body.getAttributes(); for (int i = 0; i < map.getLength(); i++) { Attr attr = (Attr) map.item(i); if (attr.getNamespaceURI().equals(WSConstants.URI_SOAP11_ENV) || attr.getNamespaceURI().equals(WSConstants.URI_SOAP12_ENV)) { String soapEnvPrefix = WSSecurityUtil.setNamespace(elem, attr.getNamespaceURI(), WSConstants.DEFAULT_SOAP_PREFIX); elem.setAttributeNS(attr.getNamespaceURI(), soapEnvPrefix + ":" + attr.getLocalName(), attr.getValue()); } } xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey); EncryptedData encData = xmlCipher.getEncryptedData(); encData.setId(xencEncryptedDataId); encData.setKeyInfo(keyInfo); xmlCipher.doFinal(doc, body, content); Element encDataElem = WSSecurityUtil.findElementById(document.getDocumentElement(), xencEncryptedDataId, null); Node clone = encDataElem.cloneNode(true); elem.appendChild(clone); encDataElem.getParentNode().appendChild(elem); encDataElem.getParentNode().removeChild(encDataElem); } else { xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey); EncryptedData encData = xmlCipher.getEncryptedData(); encData.setId(xencEncryptedDataId); encData.setKeyInfo(keyInfo); xmlCipher.doFinal(doc, body, content); } if (cloneKeyInfo) { keyInfo = new KeyInfo((Element) keyInfo.getElement().cloneNode(true), null); } } catch (Exception e2) { throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e2); } encDataRef.add("#" + xencEncryptedDataId); } return encDataRef; }
From source file:org.apache.ws.security.message.WSSecEncrypt.java
private Document buildEmbedded(Document doc, WSSecHeader secHeader) throws WSSecurityException { doDebug = log.isDebugEnabled();//from w w w . jav a 2 s .c om if (doDebug) { log.debug("Beginning Encryption embedded..."); } envelope = doc.getDocumentElement(); envelope.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.ENC_PREFIX, WSConstants.ENC_NS); // // Second step: generate a symmetric key from the specified key // (password) for this algorithm, and set the cipher into encryption // mode. // if (this.symmetricKey == null) { if (embeddedKey == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "noKeySupplied"); } this.symmetricKey = WSSecurityUtil.prepareSecretKey(symEncAlgo, embeddedKey); } KeyInfo keyInfo = null; if (this.keyIdentifierType == WSConstants.EMBEDDED_KEYNAME) { keyInfo = new KeyInfo(doc); keyInfo.addKeyName(embeddedKeyName == null ? user : embeddedKeyName); } else if (this.keyIdentifierType == WSConstants.EMBED_SECURITY_TOKEN_REF) { // // This means that we want to embed a <wsse:SecurityTokenReference> // into keyInfo element. If we need this functionality, this.secRef // MUST be set before calling the build(doc, crypto) method. So if // secRef is null then throw an exception. // if (this.securityTokenReference == null) { throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "You must set keyInfo element, if the keyIdentifier == EMBED_SECURITY_TOKEN_REF"); } else { keyInfo = new KeyInfo(doc); Element tmpE = securityTokenReference.getElement(); tmpE.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + tmpE.getPrefix(), tmpE.getNamespaceURI()); keyInfo.addUnknownElement(securityTokenReference.getElement()); } } Element keyInfoElement = keyInfo.getElement(); keyInfoElement.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX, WSConstants.SIG_NS); SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(envelope); if (parts == null) { parts = new Vector(); WSEncryptionPart encP = new WSEncryptionPart(soapConstants.getBodyQName().getLocalPart(), soapConstants.getEnvelopeURI(), "Content"); parts.add(encP); } Vector encDataRefs = doEncryption(doc, this.symmetricKey, keyInfo, parts); // // At this point data is encrypted with the symmetric key and can be // referenced via the above Id // // // Now we need to setup the wsse:Security header block 1) get (or // create) the wsse:Security header block 2) The last step sets up the // reference list that pints to the encrypted data // Element wsseSecurity = secHeader.getSecurityHeader(); Element referenceList = doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":ReferenceList"); referenceList = createDataRefList(doc, referenceList, encDataRefs); WSSecurityUtil.prependChildElement(wsseSecurity, referenceList); return doc; }
From source file:org.apache.ws.security.message.WSSecEncrypt.java
/** * Create DOM subtree for <code>xenc:EncryptedKey</code> * /* w w w . j a va 2 s. c om*/ * @param doc the SOAP envelope parent document * @param referenceList * @param encDataRefs * @return an <code>xenc:EncryptedKey</code> element */ public static Element createDataRefList(Document doc, Element referenceList, Vector encDataRefs) { for (int i = 0; i < encDataRefs.size(); i++) { String dataReferenceUri = (String) encDataRefs.get(i); Element dataReference = doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":DataReference"); dataReference.setAttributeNS(null, "URI", dataReferenceUri); referenceList.appendChild(dataReference); } return referenceList; }
From source file:org.apache.ws.security.message.WSSecEncryptedKey.java
/** * Encrypt the symmetric key data and prepare the EncryptedKey element * /*from www . j a v a 2 s. c o m*/ * This method does the most work for to prepare the EncryptedKey element. * It is also used by the WSSecEncrypt sub-class. * * @param keyBytes The bytes that represent the symmetric key * @param remoteCert The certificate that contains the public key to encrypt the * symmetric key data * @param crypto An instance of the Crypto API to handle keystore and certificates * @throws WSSecurityException */ protected void prepareInternal(byte[] keyBytes, X509Certificate remoteCert, Crypto crypto) throws WSSecurityException { String certUri = UUIDGenerator.getUUID(); Cipher cipher = WSSecurityUtil.getCipherInstance(keyEncAlgo); try { cipher.init(Cipher.ENCRYPT_MODE, remoteCert.getPublicKey()); } catch (InvalidKeyException e) { throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e); } if (doDebug) { log.debug("cipher blksize: " + cipher.getBlockSize() + ", symm key length: " + keyBytes.length); } int blockSize = cipher.getBlockSize(); if (blockSize > 0 && blockSize < keyBytes.length) { throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyTransp", new Object[] { "public key algorithm too weak to encrypt symmetric key" }); } try { this.encryptedEphemeralKey = cipher.doFinal(keyBytes); } catch (IllegalStateException e1) { throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e1); } catch (IllegalBlockSizeException e1) { throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e1); } catch (BadPaddingException e1) { throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e1); } Text keyText = WSSecurityUtil.createBase64EncodedTextNode(document, this.encryptedEphemeralKey); // // Now we need to setup the EncryptedKey header block 1) create a // EncryptedKey element and set a wsu:Id for it 2) Generate ds:KeyInfo // element, this wraps the wsse:SecurityTokenReference 3) Create and set // up the SecurityTokenReference according to the keyIdentifier parameter // 4) Create the CipherValue element structure and insert the encrypted // session key // encryptedKeyElement = createEncryptedKey(document, keyEncAlgo); if (this.encKeyId == null || "".equals(this.encKeyId)) { this.encKeyId = "EncKeyId-" + UUIDGenerator.getUUID(); } encryptedKeyElement.setAttributeNS(null, "Id", this.encKeyId); KeyInfo keyInfo = new KeyInfo(document); SecurityTokenReference secToken = new SecurityTokenReference(document); switch (keyIdentifierType) { case WSConstants.X509_KEY_IDENTIFIER: secToken.setKeyIdentifier(remoteCert); break; case WSConstants.SKI_KEY_IDENTIFIER: secToken.setKeyIdentifierSKI(remoteCert, crypto); break; case WSConstants.THUMBPRINT_IDENTIFIER: secToken.setKeyIdentifierThumb(remoteCert); break; case WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER: // // This identifier is not applicable for this case, so fall back to // ThumbprintRSA. // secToken.setKeyIdentifierThumb(remoteCert); break; case WSConstants.ISSUER_SERIAL: XMLX509IssuerSerial data = new XMLX509IssuerSerial(document, remoteCert); X509Data x509Data = new X509Data(document); x509Data.add(data); secToken.setX509IssuerSerial(x509Data); break; case WSConstants.BST_DIRECT_REFERENCE: Reference ref = new Reference(document); ref.setURI("#" + certUri); bstToken = new X509Security(document); ((X509Security) bstToken).setX509Certificate(remoteCert); bstToken.setID(certUri); ref.setValueType(bstToken.getValueType()); secToken.setReference(ref); break; case WSConstants.CUSTOM_KEY_IDENTIFIER: secToken.setKeyIdentifier(customEKTokenValueType, customEKTokenId); break; default: throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyId"); } keyInfo.addUnknownElement(secToken.getElement()); Element keyInfoElement = keyInfo.getElement(); keyInfoElement.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX, WSConstants.SIG_NS); encryptedKeyElement.appendChild(keyInfoElement); Element xencCipherValue = createCipherValue(document, encryptedKeyElement); xencCipherValue.appendChild(keyText); envelope = document.getDocumentElement(); envelope.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.ENC_PREFIX, WSConstants.ENC_NS); }
From source file:org.apache.ws.security.message.WSSecEncryptedKey.java
/** * Create DOM subtree for <code>xenc:EncryptedKey</code> * //from ww w.ja v a 2s. c o m * @param doc the SOAP envelope parent document * @param keyTransportAlgo specifies which algorithm to use to encrypt the symmetric key * @return an <code>xenc:EncryptedKey</code> element */ protected Element createEncryptedKey(Document doc, String keyTransportAlgo) { Element encryptedKey = doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":EncryptedKey"); WSSecurityUtil.setNamespace(encryptedKey, WSConstants.ENC_NS, WSConstants.ENC_PREFIX); Element encryptionMethod = doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":EncryptionMethod"); encryptionMethod.setAttributeNS(null, "Algorithm", keyTransportAlgo); encryptedKey.appendChild(encryptionMethod); return encryptedKey; }
From source file:org.apache.ws.security.message.WSSecSignature.java
/** * Initialize a WSSec Signature./*w w w . jav a2s .c om*/ * * The method sets up and initializes a WSSec Signature structure after the * relevant information was set. After setup of the references to elements * to sign may be added. After all references are added they can be signed. * * This method does not add the Signature element to the security header. * See <code>prependSignatureElementToHeader()</code> method. * * @param doc The SOAP envelope as <code>Document</code> * @param cr An instance of the Crypto API to handle keystore and certificates * @param secHeader The security header that will hold the Signature. This is used * to construct namespace prefixes for Signature. This method * @throws WSSecurityException */ public void prepare(Document doc, Crypto cr, WSSecHeader secHeader) throws WSSecurityException { // // Gather some info about the document to process and store it for // retrieval // crypto = cr; document = doc; wsDocInfo = new WSDocInfo(doc); wsDocInfo.setCrypto(cr); // // At first get the security token (certificate) according to the // parameters. // X509Certificate[] certs = null; if (keyIdentifierType != WSConstants.UT_SIGNING && keyIdentifierType != WSConstants.CUSTOM_SYMM_SIGNING && keyIdentifierType != WSConstants.CUSTOM_SYMM_SIGNING_DIRECT && keyIdentifierType != WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER && keyIdentifierType != WSConstants.CUSTOM_KEY_IDENTIFIER) { if (useThisCert == null) { certs = crypto.getCertificates(user); } else { certs = new X509Certificate[] { useThisCert }; } if (certs == null || certs.length <= 0) { throw new WSSecurityException(WSSecurityException.FAILURE, "noUserCertsFound", new Object[] { user, "signature" }); } certUri = wssConfig.getIdAllocator().createSecureId("CertId-", certs[0]); // // If no signature algorithm was set try to detect it according to the // data stored in the certificate. // if (sigAlgo == null) { String pubKeyAlgo = certs[0].getPublicKey().getAlgorithm(); log.debug("automatic sig algo detection: " + pubKeyAlgo); if (pubKeyAlgo.equalsIgnoreCase("DSA")) { sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_DSA; } else if (pubKeyAlgo.equalsIgnoreCase("RSA")) { sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_RSA; } else { throw new WSSecurityException(WSSecurityException.FAILURE, "unknownSignatureAlgorithm", new Object[] { pubKeyAlgo }); } } } // // Get an initialized XMLSignature element. // if (canonAlgo.equals(WSConstants.C14N_EXCL_OMIT_COMMENTS)) { Element canonElem = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_CANONICALIZATIONMETHOD); canonElem.setAttributeNS(null, Constants._ATT_ALGORITHM, canonAlgo); if (wssConfig.isWsiBSPCompliant()) { Set prefixes = getInclusivePrefixes(secHeader.getSecurityHeader(), false); InclusiveNamespaces inclusiveNamespaces = new InclusiveNamespaces(doc, prefixes); canonElem.appendChild(inclusiveNamespaces.getElement()); } try { SignatureAlgorithm signatureAlgorithm = new SignatureAlgorithm(doc, sigAlgo); sig = new XMLSignature(doc, null, signatureAlgorithm.getElement(), canonElem); } catch (XMLSecurityException e) { log.error("", e); throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e); } } else { try { sig = new XMLSignature(doc, null, sigAlgo, canonAlgo); } catch (XMLSecurityException e) { log.error("", e); throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e); } } EnvelopeIdResolver resolver = (EnvelopeIdResolver) EnvelopeIdResolver.getInstance(); resolver.setWsDocInfo(wsDocInfo); sig.addResourceResolver(resolver); sig.setId(wssConfig.getIdAllocator().createId("Signature-", sig)); keyInfo = sig.getKeyInfo(); keyInfoUri = wssConfig.getIdAllocator().createSecureId("KeyId-", keyInfo); keyInfo.setId(keyInfoUri); secRef = new SecurityTokenReference(doc); strUri = wssConfig.getIdAllocator().createSecureId("STRId-", secRef); secRef.setID(strUri); // // Prepare and setup the token references for this Signature // switch (keyIdentifierType) { case WSConstants.BST_DIRECT_REFERENCE: Reference ref = new Reference(document); ref.setURI("#" + certUri); if (!useSingleCert) { bstToken = new PKIPathSecurity(document); ((PKIPathSecurity) bstToken).setX509Certificates(certs, false, crypto); } else { bstToken = new X509Security(document); ((X509Security) bstToken).setX509Certificate(certs[0]); } ref.setValueType(bstToken.getValueType()); secRef.setReference(ref); bstToken.setID(certUri); wsDocInfo.setBst(bstToken.getElement()); break; case WSConstants.EMBED_SECURITY_TOKEN_REF: XMLX509Certificate cert = null; XMLX509SubjectName subject = null; try { cert = new XMLX509Certificate(document, certs[0]); } catch (XMLSecurityException e) { throw new WSSecurityException(WSSecurityException.FAILURE, ""); } subject = new XMLX509SubjectName(doc, certs[0]); X509Data x509KeyVal = new X509Data(document); x509KeyVal.add(subject); x509KeyVal.add(cert); keyInfo.add(x509KeyVal); break; case WSConstants.ISSUER_SERIAL: XMLX509IssuerSerial data = new XMLX509IssuerSerial(document, certs[0]); X509Data x509Data = new X509Data(document); x509Data.add(data); secRef.setX509IssuerSerial(x509Data); break; case WSConstants.X509_KEY_IDENTIFIER: secRef.setKeyIdentifier(certs[0]); break; case WSConstants.SKI_KEY_IDENTIFIER: secRef.setKeyIdentifierSKI(certs[0], crypto); break; case WSConstants.UT_SIGNING: Reference refUt = new Reference(document); refUt.setValueType(WSConstants.USERNAMETOKEN_NS + "#UsernameToken"); String utId = usernameToken.getId(); refUt.setURI("#" + utId); secRef.setReference(refUt); secretKey = usernameToken.getSecretKey(); break; case WSConstants.THUMBPRINT_IDENTIFIER: secRef.setKeyIdentifierThumb(certs[0]); break; case WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER: if (encrKeySha1value != null) { secRef.setKeyIdentifierEncKeySHA1(encrKeySha1value); } else { secRef.setKeyIdentifierEncKeySHA1(getSHA1(secretKey)); } break; case WSConstants.CUSTOM_SYMM_SIGNING: if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(customTokenValueType) || WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(customTokenValueType)) { secRef.setKeyIdentifier(customTokenValueType, customTokenId); } else { Reference refCust = new Reference(document); refCust.setValueType(customTokenValueType); refCust.setURI((new StringBuilder()).append("#").append(customTokenId).toString()); secRef.setReference(refCust); } break; case WSConstants.CUSTOM_SYMM_SIGNING_DIRECT: Reference refCustd = new Reference(document); refCustd.setValueType(this.customTokenValueType); refCustd.setURI(this.customTokenId); secRef.setReference(refCustd); break; case WSConstants.CUSTOM_KEY_IDENTIFIER: secRef.setKeyIdentifier(customTokenValueType, customTokenId); break; case WSConstants.KEY_VALUE: java.security.PublicKey publicKey = certs[0].getPublicKey(); String pubKeyAlgo = publicKey.getAlgorithm(); if (pubKeyAlgo.equalsIgnoreCase("DSA")) { DSAKeyValue dsaKeyValue = new DSAKeyValue(document, publicKey); keyInfo.add(dsaKeyValue); } else if (pubKeyAlgo.equalsIgnoreCase("RSA")) { RSAKeyValue rsaKeyValue = new RSAKeyValue(document, publicKey); keyInfo.add(rsaKeyValue); } else { throw new WSSecurityException(WSSecurityException.FAILURE, "unknownSignatureAlgorithm", new Object[] { pubKeyAlgo }); } break; default: throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyId"); } if (keyIdentifierType != WSConstants.KEY_VALUE && keyIdentifierType != WSConstants.EMBED_SECURITY_TOKEN_REF) { keyInfo.addUnknownElement(secRef.getElement()); wsDocInfo.setSecurityTokenReference(secRef.getElement()); } }
From source file:org.apache.ws.security.message.WSSecSignature.java
/** * This method adds references to the Signature. * /*from w w w . ja v a2s .c o m*/ * The added references are signed when calling * <code>computeSignature()</code>. This method can be called several * times to add references as required. <code>addReferencesToSign()</code> * can be called any time after <code>prepare</code>. * * @param references A vector containing <code>WSEncryptionPart</code> objects * that define the parts to sign. * @param secHeader Used to compute namespaces to be inserted by * InclusiveNamespaces to be WSI compliant. * @throws WSSecurityException */ public void addReferencesToSign(Vector references, WSSecHeader secHeader) throws WSSecurityException { Element envelope = document.getDocumentElement(); for (int part = 0; part < references.size(); part++) { WSEncryptionPart encPart = (WSEncryptionPart) references.get(part); String idToSign = encPart.getId(); String elemName = encPart.getName(); String nmSpace = encPart.getNamespace(); // // Set up the elements to sign. There are two reserved element // names: "Token" and "STRTransform" "Token": Setup the Signature to // either sign the information that points to the security token or // the token itself. If its a direct reference sign the token, // otherwise sign the KeyInfo Element. "STRTransform": Setup the // ds:Reference to use STR Transform // Transforms transforms = new Transforms(document); try { if (idToSign != null) { Element toSignById = WSSecurityUtil.findElementById(document.getDocumentElement(), idToSign, WSConstants.WSU_NS); if (toSignById == null) { toSignById = WSSecurityUtil.findElementById(document.getDocumentElement(), idToSign, null); } if (SecurityTokenReference.SECURITY_TOKEN_REFERENCE.equals(elemName)) { Element ctx = createSTRParameter(document); transforms.addTransform(STRTransform.implementedTransformURI, ctx); sig.addDocument("#" + idToSign, transforms, digestAlgo); continue; } transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS); if (wssConfig.isWsiBSPCompliant()) { transforms.item(0).getElement().appendChild( new InclusiveNamespaces(document, getInclusivePrefixes(toSignById)).getElement()); } sig.addDocument("#" + idToSign, transforms, digestAlgo); } else if (elemName.equals("Token")) { transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS); if (keyIdentifierType == WSConstants.BST_DIRECT_REFERENCE) { if (wssConfig.isWsiBSPCompliant()) { transforms.item(0).getElement().appendChild(new InclusiveNamespaces(document, getInclusivePrefixes(secHeader.getSecurityHeader())).getElement()); } sig.addDocument("#" + certUri, transforms, digestAlgo); } else { if (wssConfig.isWsiBSPCompliant()) { transforms.item(0).getElement().appendChild( new InclusiveNamespaces(document, getInclusivePrefixes(keyInfo.getElement())) .getElement()); } sig.addDocument("#" + keyInfoUri, transforms, digestAlgo); } } else if (elemName.equals("STRTransform")) { // STRTransform Element ctx = createSTRParameter(document); transforms.addTransform(STRTransform.implementedTransformURI, ctx); sig.addDocument("#" + strUri, transforms, digestAlgo); } else if (elemName.equals("Assertion")) { // Assertion String id = null; id = SAMLUtil.getAssertionId(envelope, elemName, nmSpace); Element body = (Element) WSSecurityUtil.findElement(envelope, elemName, nmSpace); if (body == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "noEncElement", new Object[] { nmSpace + ", " + elemName }); } transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS); if (wssConfig.isWsiBSPCompliant()) { transforms.item(0).getElement().appendChild( new InclusiveNamespaces(document, getInclusivePrefixes(body)).getElement()); } String prefix = WSSecurityUtil.setNamespace(body, WSConstants.WSU_NS, WSConstants.WSU_PREFIX); body.setAttributeNS(WSConstants.WSU_NS, prefix + ":Id", id); sig.addDocument("#" + id, transforms, digestAlgo); } else { Element body = (Element) WSSecurityUtil.findElement(envelope, elemName, nmSpace); if (body == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "noEncElement", new Object[] { nmSpace + ", " + elemName }); } transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS); if (wssConfig.isWsiBSPCompliant()) { transforms.item(0).getElement().appendChild( new InclusiveNamespaces(document, getInclusivePrefixes(body)).getElement()); } sig.addDocument("#" + setWsuId(body), transforms, digestAlgo); } } catch (TransformationException e1) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e1); } catch (XMLSignatureException e1) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e1); } } }
From source file:org.apache.ws.security.message.WSSecSignatureBase.java
/** * Create an STRTransformationParameters element *///w w w .j ava2 s .c o m public Element createSTRParameter(Document doc) { Element transformParam = doc.createElementNS(WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX + ":TransformationParameters"); Element canonElem = doc.createElementNS(WSConstants.SIG_NS, WSConstants.SIG_PREFIX + ":CanonicalizationMethod"); canonElem.setAttributeNS(null, "Algorithm", WSConstants.C14N_EXCL_OMIT_COMMENTS); transformParam.appendChild(canonElem); return transformParam; }
From source file:org.apache.ws.security.message.WSSignEnvelope.java
/** * Builds a signed soap envelope./* ww w . j av a2 s . c om*/ * * The method first gets an appropriate * security header. According to the defined parameters for certificate * handling the signature elements are constructed and inserted into the * <code>wsse:Signature</code> * * @param doc The unsigned SOAP envelope as <code>Document</code> * @param crypto An instance of the Crypto API to handle keystore and * certificates * @return A signed SOAP envelope as <code>Document</code> * @throws WSSecurityException * @deprecated replaced by {@link WSSecSignature#build(Document, Crypto, WSSecHeader)} */ public Document build(Document doc, Crypto crypto) throws WSSecurityException { doDebug = log.isDebugEnabled(); long t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0; if (tlog.isDebugEnabled()) { t0 = System.currentTimeMillis(); } if (doDebug) { log.debug("Beginning signing..."); } /* * Gather some info about the document to process and store it for * retrieval */ WSDocInfo wsDocInfo = new WSDocInfo(doc); wsDocInfo.setCrypto(crypto); Element envelope = doc.getDocumentElement(); SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(envelope); Element securityHeader = insertSecurityHeader(doc); // Set the id of the elements to be used as digest source // String id = setBodyID(doc); String certUri = null; X509Certificate[] certs = null; if (keyIdentifierType != WSConstants.UT_SIGNING) { certs = crypto.getCertificates(user); if (certs == null || certs.length <= 0) { throw new WSSecurityException(WSSecurityException.FAILURE, "noUserCertsFound", new Object[] { user, "signature" }); } certUri = wssConfig.getIdAllocator().createSecureId("CertId-", certs[0]); if (sigAlgo == null) { String pubKeyAlgo = certs[0].getPublicKey().getAlgorithm(); log.debug("automatic sig algo detection: " + pubKeyAlgo); if (pubKeyAlgo.equalsIgnoreCase("DSA")) { sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_DSA; } else if (pubKeyAlgo.equalsIgnoreCase("RSA")) { sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_RSA; } else { throw new WSSecurityException(WSSecurityException.FAILURE, "unknownSignatureAlgorithm", new Object[] { pubKeyAlgo }); } } } XMLSignature sig = null; if (canonAlgo.equals(WSConstants.C14N_EXCL_OMIT_COMMENTS)) { Element canonElem = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_CANONICALIZATIONMETHOD); canonElem.setAttributeNS(null, Constants._ATT_ALGORITHM, canonAlgo); if (wssConfig.isWsiBSPCompliant()) { Set prefixes = getInclusivePrefixes(securityHeader, false); InclusiveNamespaces inclusiveNamespaces = new InclusiveNamespaces(doc, prefixes); canonElem.appendChild(inclusiveNamespaces.getElement()); } try { SignatureAlgorithm signatureAlgorithm = new SignatureAlgorithm(doc, sigAlgo); sig = new XMLSignature(doc, null, signatureAlgorithm.getElement(), canonElem); } catch (XMLSecurityException e) { log.error("", e); throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e); } } else { try { sig = new XMLSignature(doc, null, sigAlgo, canonAlgo); } catch (XMLSecurityException e) { log.error("", e); throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e); } } /* * If we don't generate a new Transforms for each addDocument here, then * only the last Transforms is put into the according ds:Reference * element, i.e. the first ds:Reference does not contain a Transforms * element. Thus the verification fails (somehow) */ KeyInfo info = sig.getKeyInfo(); String keyInfoUri = wssConfig.getIdAllocator().createSecureId("KeyId-", info); info.setId(keyInfoUri); SecurityTokenReference secRef = new SecurityTokenReference(doc); String secRefId = wssConfig.getIdAllocator().createSecureId("STRId-", info); secRef.setID(secRefId); if (tlog.isDebugEnabled()) { t1 = System.currentTimeMillis(); } if (parts == null) { parts = new Vector(); WSEncryptionPart encP = new WSEncryptionPart(soapConstants.getBodyQName().getLocalPart(), soapConstants.getEnvelopeURI(), "Content"); parts.add(encP); } Transforms transforms = null; for (int part = 0; part < parts.size(); part++) { WSEncryptionPart encPart = (WSEncryptionPart) parts.get(part); String idToSign = encPart.getId(); String elemName = encPart.getName(); String nmSpace = encPart.getNamespace(); /* * Set up the elements to sign. There are two reserved element * names: "Token" and "STRTransform" "Token": Setup the Signature to * either sign the information that points to the security token or * the token itself. If its a direct reference sign the token, * otherwise sign the KeyInfo Element. "STRTransform": Setup the * ds:Reference to use STR Transform * */ try { if (idToSign != null) { Element toSignById = WSSecurityUtil.findElementById(doc.getDocumentElement(), idToSign, WSConstants.WSU_NS); if (toSignById == null) { toSignById = WSSecurityUtil.findElementById(doc.getDocumentElement(), idToSign, null); } transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS); if (wssConfig.isWsiBSPCompliant()) { transforms.item(0).getElement().appendChild( new InclusiveNamespaces(doc, getInclusivePrefixes(toSignById)).getElement()); } sig.addDocument("#" + idToSign, transforms); } else if (elemName.equals("Token")) { transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS); if (keyIdentifierType == WSConstants.BST_DIRECT_REFERENCE) { if (wssConfig.isWsiBSPCompliant()) { transforms.item(0).getElement() .appendChild(new InclusiveNamespaces(doc, getInclusivePrefixes(securityHeader)) .getElement()); } sig.addDocument("#" + certUri, transforms); } else { if (wssConfig.isWsiBSPCompliant()) { transforms.item(0).getElement().appendChild( new InclusiveNamespaces(doc, getInclusivePrefixes(info.getElement())) .getElement()); } sig.addDocument("#" + keyInfoUri, transforms); } } else if (elemName.equals("STRTransform")) { // STRTransform Element ctx = createSTRParameter(doc); transforms = new Transforms(doc); transforms.addTransform(STRTransform.implementedTransformURI, ctx); sig.addDocument("#" + secRefId, transforms); } else if (elemName.equals("Assertion")) { // Assertion String id = null; id = SAMLUtil.getAssertionId(envelope, elemName, nmSpace); Element body = (Element) WSSecurityUtil.findElement(envelope, elemName, nmSpace); if (body == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "noEncElement", new Object[] { nmSpace + ", " + elemName }); } transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS); if (wssConfig.isWsiBSPCompliant()) { transforms.item(0).getElement() .appendChild(new InclusiveNamespaces(doc, getInclusivePrefixes(body)).getElement()); } String prefix = WSSecurityUtil.setNamespace(body, WSConstants.WSU_NS, WSConstants.WSU_PREFIX); body.setAttributeNS(WSConstants.WSU_NS, prefix + ":Id", id); sig.addDocument("#" + id, transforms); } else { Element body = (Element) WSSecurityUtil.findElement(envelope, elemName, nmSpace); if (body == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "noEncElement", new Object[] { nmSpace + ", " + elemName }); } transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS); if (wssConfig.isWsiBSPCompliant()) { transforms.item(0).getElement() .appendChild(new InclusiveNamespaces(doc, getInclusivePrefixes(body)).getElement()); } sig.addDocument("#" + setWsuId(body), transforms); } } catch (TransformationException e1) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e1); } catch (XMLSignatureException e1) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e1); } } sig.addResourceResolver(EnvelopeIdResolver.getInstance()); WSSecurityUtil.prependChildElement(securityHeader, sig.getElement()); if (tlog.isDebugEnabled()) { t2 = System.currentTimeMillis(); } byte[] secretKey = null; switch (keyIdentifierType) { case WSConstants.BST_DIRECT_REFERENCE: Reference ref = new Reference(doc); ref.setURI("#" + certUri); BinarySecurity bstToken = null; if (!useSingleCert) { bstToken = new PKIPathSecurity(doc); ((PKIPathSecurity) bstToken).setX509Certificates(certs, false, crypto); } else { bstToken = new X509Security(doc); ((X509Security) bstToken).setX509Certificate(certs[0]); } ref.setValueType(bstToken.getValueType()); secRef.setReference(ref); bstToken.setID(certUri); WSSecurityUtil.prependChildElement(securityHeader, bstToken.getElement()); wsDocInfo.setBst(bstToken.getElement()); break; case WSConstants.ISSUER_SERIAL: XMLX509IssuerSerial data = new XMLX509IssuerSerial(doc, certs[0]); X509Data x509Data = new X509Data(doc); x509Data.add(data); secRef.setX509IssuerSerial(x509Data); break; case WSConstants.X509_KEY_IDENTIFIER: secRef.setKeyIdentifier(certs[0]); break; case WSConstants.SKI_KEY_IDENTIFIER: secRef.setKeyIdentifierSKI(certs[0], crypto); break; case WSConstants.UT_SIGNING: Reference refUt = new Reference(doc); refUt.setValueType(WSConstants.USERNAMETOKEN_NS + "#UsernameToken"); String utId = usernameToken.getId(); if (utId == null) { utId = wssConfig.getIdAllocator().createId("usernameTokenId-", usernameToken); usernameToken.setId(utId); } refUt.setURI("#" + utId); secRef.setReference(refUt); secretKey = usernameToken.getSecretKey(); break; case WSConstants.THUMBPRINT_IDENTIFIER: secRef.setKeyIdentifierThumb(certs[0]); break; default: throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyId"); } if (tlog.isDebugEnabled()) { t3 = System.currentTimeMillis(); } info.addUnknownElement(secRef.getElement()); boolean remove = WSDocInfoStore.store(wsDocInfo); try { if (keyIdentifierType == WSConstants.UT_SIGNING) { sig.sign(sig.createSecretKey(secretKey)); } else { sig.sign(crypto.getPrivateKey(user, password)); } signatureValue = sig.getSignatureValue(); } catch (XMLSignatureException e1) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, null, null, e1); } catch (Exception e1) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, null, null, e1); } finally { if (remove) { WSDocInfoStore.delete(wsDocInfo); } } if (tlog.isDebugEnabled()) { t4 = System.currentTimeMillis(); tlog.debug("SignEnvelope: cre-Sig= " + (t1 - t0) + " set transform= " + (t2 - t1) + " sec-ref= " + (t3 - t2) + " signature= " + (t4 - t3)); } if (doDebug) { log.debug("Signing complete."); } return (doc); }