Token encrToken,
boolean attached,
List<WSEncryptionPart> encrParts,
boolean atEnd) {
try {
WSSecDKEncrypt dkEncr = new WSSecDKEncrypt(wssConfig);
if (recToken.getToken().getSPConstants() == SP12Constants.INSTANCE) {
dkEncr.setWscVersion(ConversationConstants.VERSION_05_12);
}
if (attached && encrTok.getAttachedReference() != null) {
dkEncr.setExternalKey(
encrTok.getSecret(), cloneElement(encrTok.getAttachedReference())
);
} else if (encrTok.getUnattachedReference() != null) {
dkEncr.setExternalKey(
encrTok.getSecret(), cloneElement(encrTok.getUnattachedReference())
);
} else if (!isRequestor() && encrTok.getSHA1() != null) {
// If the Encrypted key used to create the derived key is not
// attached use key identifier as defined in WSS1.1 section
// 7.7 Encrypted Key reference
SecurityTokenReference tokenRef = new SecurityTokenReference(saaj.getSOAPPart());
tokenRef.setKeyIdentifierEncKeySHA1(encrTok.getSHA1());
String tokenType = encrTok.getTokenType();
if (tokenType == null) {
tokenType = WSConstants.WSS_ENC_KEY_VALUE_TYPE;
}
tokenRef.addTokenType(tokenType);
dkEncr.setExternalKey(encrTok.getSecret(), tokenRef.getElement());
} else {
if (attached) {
String id = encrTok.getWsuId();
if (id == null
&& (encrToken instanceof SecureConversationToken
|| encrToken instanceof SecurityContextToken)) {
dkEncr.setTokenIdDirectId(true);
id = encrTok.getId();
} else if (id == null) {
id = encrTok.getId();
}
if (id.startsWith("#")) {
id = id.substring(1);
}
dkEncr.setExternalKey(encrTok.getSecret(), id);
} else {
dkEncr.setTokenIdDirectId(true);
dkEncr.setExternalKey(encrTok.getSecret(), encrTok.getId());
}
}
if (encrTok.getSHA1() != null) {
String tokenType = encrTok.getTokenType();
if (tokenType == null) {
tokenType = WSConstants.WSS_ENC_KEY_VALUE_TYPE;
}
dkEncr.setCustomValueType(tokenType);
} else {
String tokenType = encrTok.getTokenType();
if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType)
|| WSConstants.SAML_NS.equals(tokenType)) {
dkEncr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
dkEncr.setCustomValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
} else if (WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType)
|| WSConstants.SAML2_NS.equals(tokenType)) {
dkEncr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
dkEncr.setCustomValueType(WSConstants.WSS_SAML2_KI_VALUE_TYPE);
} else {
dkEncr.setCustomValueType(tokenType);
}
}
dkEncr.setSymmetricEncAlgorithm(sbinding.getAlgorithmSuite().getEncryption());
dkEncr.setDerivedKeyLength(sbinding.getAlgorithmSuite()
.getEncryptionDerivedKeyLength() / 8);
dkEncr.prepare(saaj.getSOAPPart());
Element encrDKTokenElem = null;
encrDKTokenElem = dkEncr.getdktElement();
addDerivedKeyElement(encrDKTokenElem);
Element refList = dkEncr.encryptForExternalRef(null, encrParts);
if (atEnd) {
this.insertBeforeBottomUp(refList);
} else {
this.addDerivedKeyElement(refList);
}