}
String nonce = Base64.encode(dkt.getNonce());
HashMap ekCache = context.getEncryptedKeyCache();
String ekId = (String)ekCache.get(x509TokenId);
EncryptedKey encryptedKey = null;
XMLCipher keyEncryptor = null;
if(!tokenInserted){
//Store SymmetricKey generated in ProcessingContext
context.setExtraneousProperty("SecretKey", originalKey); //this is the originalKey
//keyinfo for encryptedKey
keyInfoBlock = new KeyInfoHeaderBlock(secureMessage.getSOAPPart());
strategy.setCertificate(cert);
strategy.insertKey(keyInfoBlock, secureMessage, x509TokenId);
com.sun.org.apache.xml.internal.security.keys.KeyInfo apacheKeyInfo = keyInfoBlock.getKeyInfo();
//create an encrypted Key --- it encrypts the original key
try{
keyEncryptor = XMLCipher.getInstance(keyEncAlgo);
keyEncryptor.init(XMLCipher.WRAP_MODE, cert.getPublicKey());
if (keyEncryptor != null) {
encryptedKey = keyEncryptor.encryptKey(secureMessage.getSOAPPart(), originalKey);
}
}catch(Exception e){
logger.log(Level.SEVERE, LogStringsMessages.WSS_1335_UNSUPPORTED_KEYBINDING_SIGNATUREPOLICY());
throw new XWSSecurityException(e);
}
ekId = secureMessage.generateId();
ekCache.put(x509TokenId, ekId);
encryptedKey.setId(ekId);
// set its KeyInfo
encryptedKey.setKeyInfo(apacheKeyInfo);
}
//STR for DerivedKeyToken
SecurityTokenReference tokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
DirectReference reference = new DirectReference();
//TODO: PLUGFEST commenting this as Microsoft puts Value type on reference itself
//tokenRef.setTokenType(MessageConstants.EncryptedKey_NS);
//set id of encrypted key in STR of DKT
reference.setValueType(MessageConstants.EncryptedKey_NS);
reference.setURI("#"+ekId);
tokenRef.setReference(reference);
DerivedKeyTokenHeaderBlock dktHeadrBlock =
new DerivedKeyTokenHeaderBlock(securityHeader.getOwnerDocument(), tokenRef, nonce, dkt.getOffset(), dkt.getLength() ,dktId);
if(!tokenInserted){
Node nsX509 = null;
if (insertedx509 != null) {
nsX509 = insertedx509.getNextSibling();
}
// move DKT below X509 if present
if (nsX509 == null) {
secureMessage.findOrCreateSecurityHeader().insertHeaderBlock(dktHeadrBlock);
} else {
secureMessage.findOrCreateSecurityHeader().insertBefore(dktHeadrBlock, nsX509);
}
// move EK above DKT but below X509
if (insertedx509 != null) {
nsX509 = insertedx509.getNextSibling();
}
// insert the EK into the SOAPMessage - this goes on top of DKT Header block
SOAPElement se = (SOAPElement)keyEncryptor.martial(encryptedKey);
if (nsX509 == null) {
secureMessage.findOrCreateSecurityHeader().insertHeaderBlockElement(se);
}else {
secureMessage.findOrCreateSecurityHeader().insertBefore(se, nsX509);
}