use of javax.xml.crypto.dsig.Reference in project cxf by apache.
the class SymmetricBindingHandler method doSignatureDK.
private byte[] doSignatureDK(List<WSEncryptionPart> sigs, AbstractTokenWrapper policyAbstractTokenWrapper, AbstractToken policyToken, SecurityToken tok, boolean included) throws WSSecurityException {
Document doc = saaj.getSOAPPart();
WSSecDKSign dkSign = new WSSecDKSign(secHeader);
dkSign.setIdAllocator(wssConfig.getIdAllocator());
dkSign.setCallbackLookup(callbackLookup);
dkSign.setAttachmentCallbackHandler(new AttachmentCallbackHandler(message));
dkSign.setStoreBytesInAttachment(storeBytesInAttachment);
dkSign.setExpandXopInclude(isExpandXopInclude());
dkSign.setWsDocInfo(wsDocInfo);
if (policyAbstractTokenWrapper.getToken().getVersion() == SPConstants.SPVersion.SP11) {
dkSign.setWscVersion(ConversationConstants.VERSION_05_02);
}
// Check for whether the token is attached in the message or not
boolean attached = false;
if (isTokenRequired(policyToken.getIncludeTokenType())) {
attached = true;
}
// Setting the AttachedReference or the UnattachedReference according to the flag
Element ref;
if (attached) {
ref = tok.getAttachedReference();
} else {
ref = tok.getUnattachedReference();
}
if (ref != null) {
dkSign.setExternalKey(tok.getSecret(), cloneElement(ref));
} else if (!isRequestor() && policyToken.getDerivedKeys() == DerivedKeys.RequireDerivedKeys && tok.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(doc);
if (tok.getSHA1() != null) {
String tokenType = tok.getTokenType();
if (policyToken instanceof KerberosToken) {
tokenRef.setKeyIdentifier(WSS4JConstants.WSS_KRB_KI_VALUE_TYPE, tok.getSHA1(), true);
if (tokenType == null) {
tokenType = WSS4JConstants.WSS_GSS_KRB_V5_AP_REQ;
}
} else {
tokenRef.setKeyIdentifierEncKeySHA1(tok.getSHA1());
if (tokenType == null) {
tokenType = WSS4JConstants.WSS_ENC_KEY_VALUE_TYPE;
}
}
tokenRef.addTokenType(tokenType);
}
dkSign.setExternalKey(tok.getSecret(), tokenRef.getElement());
} else {
if ((!attached && !isRequestor()) || policyToken instanceof SecureConversationToken || policyToken instanceof SecurityContextToken) {
dkSign.setTokenIdDirectId(true);
}
dkSign.setExternalKey(tok.getSecret(), tok.getId());
}
// Set the algo info
dkSign.setSignatureAlgorithm(sbinding.getAlgorithmSuite().getSymmetricSignature());
dkSign.setSigCanonicalization(sbinding.getAlgorithmSuite().getC14n().getValue());
AlgorithmSuiteType algType = sbinding.getAlgorithmSuite().getAlgorithmSuiteType();
dkSign.setDigestAlgorithm(algType.getDigest());
dkSign.setDerivedKeyLength(algType.getSignatureDerivedKeyLength() / 8);
boolean includePrefixes = MessageUtils.getContextualBoolean(message, SecurityConstants.ADD_INCLUSIVE_PREFIXES, true);
dkSign.setAddInclusivePrefixes(includePrefixes);
if (tok.getSHA1() != null) {
// Set the value type of the reference
String tokenType = tok.getTokenType();
if (tokenType == null) {
tokenType = WSS4JConstants.WSS_ENC_KEY_VALUE_TYPE;
}
dkSign.setCustomValueType(tokenType);
} else {
String tokenType = tok.getTokenType();
if (WSS4JConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) || WSS4JConstants.SAML_NS.equals(tokenType)) {
dkSign.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
dkSign.setCustomValueType(WSS4JConstants.WSS_SAML_KI_VALUE_TYPE);
} else if (WSS4JConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) || WSS4JConstants.SAML2_NS.equals(tokenType)) {
dkSign.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
dkSign.setCustomValueType(WSS4JConstants.WSS_SAML2_KI_VALUE_TYPE);
} else if (policyToken instanceof UsernameToken) {
dkSign.setCustomValueType(WSS4JConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
} else {
dkSign.setCustomValueType(tokenType);
}
}
dkSign.prepare();
if (sbinding.isProtectTokens()) {
String sigTokId = tok.getId();
if (included) {
sigTokId = tok.getWsuId();
if (sigTokId == null) {
sigTokId = tok.getId();
}
if (sigTokId.startsWith("#")) {
sigTokId = sigTokId.substring(1);
}
}
sigs.add(new WSEncryptionPart(sigTokId));
assertPolicy(new QName(sbinding.getName().getNamespaceURI(), SPConstants.PROTECT_TOKENS));
}
dkSign.getParts().addAll(sigs);
List<Reference> referenceList = dkSign.addReferencesToSign(sigs);
if (!referenceList.isEmpty()) {
// Add elements to header
Element el = dkSign.getdktElement();
addDerivedKeyElement(el);
// Do signature
if (bottomUpElement == null) {
dkSign.computeSignature(referenceList, false, null);
} else {
dkSign.computeSignature(referenceList, true, bottomUpElement);
}
bottomUpElement = dkSign.getSignatureElement();
this.mainSigId = dkSign.getSignatureId();
return dkSign.getSignatureValue();
}
return null;
}
use of javax.xml.crypto.dsig.Reference in project cxf by apache.
the class TransportBindingHandler method doSignature.
private byte[] doSignature(boolean tokenIncluded, SecurityToken secTok, AbstractToken token, SupportingTokens wrapper, List<WSEncryptionPart> sigParts) throws Exception {
WSSecSignature sig = new WSSecSignature(secHeader);
sig.setIdAllocator(wssConfig.getIdAllocator());
sig.setCallbackLookup(callbackLookup);
sig.setAttachmentCallbackHandler(new AttachmentCallbackHandler(message));
sig.setStoreBytesInAttachment(storeBytesInAttachment);
sig.setExpandXopInclude(isExpandXopInclude());
sig.setWsDocInfo(wsDocInfo);
// Setting the AttachedReference or the UnattachedReference according to the flag
Element ref;
if (tokenIncluded) {
ref = secTok.getAttachedReference();
} else {
ref = secTok.getUnattachedReference();
}
if (ref != null) {
SecurityTokenReference secRef = new SecurityTokenReference(cloneElement(ref), new BSPEnforcer());
sig.setSecurityTokenReference(secRef);
sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
} else if (token instanceof UsernameToken) {
sig.setCustomTokenId(secTok.getId());
sig.setCustomTokenValueType(WSS4JConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
int type = tokenIncluded ? WSConstants.CUSTOM_SYMM_SIGNING : WSConstants.CUSTOM_SYMM_SIGNING_DIRECT;
sig.setKeyIdentifierType(type);
} else if (secTok.getTokenType() == null) {
sig.setCustomTokenValueType(WSS4JConstants.WSS_SAML_KI_VALUE_TYPE);
sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
} else {
String id = secTok.getWsuId();
if (id == null) {
sig.setCustomTokenId(secTok.getId());
sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING_DIRECT);
} else {
sig.setCustomTokenId(secTok.getWsuId());
sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
}
String tokenType = secTok.getTokenType();
if (WSS4JConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) || WSS4JConstants.SAML_NS.equals(tokenType)) {
sig.setCustomTokenValueType(WSS4JConstants.WSS_SAML_KI_VALUE_TYPE);
sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
} else if (WSS4JConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) || WSS4JConstants.SAML2_NS.equals(tokenType)) {
sig.setCustomTokenValueType(WSS4JConstants.WSS_SAML2_KI_VALUE_TYPE);
sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
} else {
sig.setCustomTokenValueType(tokenType);
}
}
Crypto crypto = null;
if (secTok.getSecret() == null) {
sig.setX509Certificate(secTok.getX509Certificate());
crypto = secTok.getCrypto();
if (crypto == null) {
crypto = getSignatureCrypto();
}
if (crypto == null) {
LOG.fine("No signature Crypto properties are available");
Exception ex = new Exception("No signature Crypto properties are available");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex);
}
String uname = crypto.getX509Identifier(secTok.getX509Certificate());
if (uname == null) {
String userNameKey = SecurityConstants.SIGNATURE_USERNAME;
uname = (String) SecurityUtils.getSecurityPropertyValue(userNameKey, message);
}
String password = getPassword(uname, token, WSPasswordCallback.SIGNATURE);
sig.setUserInfo(uname, password);
sig.setSignatureAlgorithm(binding.getAlgorithmSuite().getAsymmetricSignature());
} else {
crypto = getSignatureCrypto();
sig.setSecretKey(secTok.getSecret());
sig.setSignatureAlgorithm(binding.getAlgorithmSuite().getSymmetricSignature());
}
sig.setSigCanonicalization(binding.getAlgorithmSuite().getC14n().getValue());
AlgorithmSuiteType algType = binding.getAlgorithmSuite().getAlgorithmSuiteType();
sig.setDigestAlgo(algType.getDigest());
sig.prepare(crypto);
sig.getParts().addAll(sigParts);
List<Reference> referenceList = sig.addReferencesToSign(sigParts);
// Do signature
if (bottomUpElement == null) {
sig.computeSignature(referenceList, false, null);
} else {
sig.computeSignature(referenceList, true, bottomUpElement);
}
bottomUpElement = sig.getSignatureElement();
mainSigId = sig.getId();
return sig.getSignatureValue();
}
use of javax.xml.crypto.dsig.Reference in project cxf by apache.
the class TransportBindingHandler method doX509TokenSignature.
private byte[] doX509TokenSignature(AbstractToken token, SupportingTokens wrapper) throws Exception {
List<WSEncryptionPart> sigParts = signPartsAndElements(wrapper.getSignedParts(), wrapper.getSignedElements());
if (token.getDerivedKeys() == DerivedKeys.RequireDerivedKeys) {
WSSecEncryptedKey encrKey = getEncryptedKeyBuilder(token);
assertPolicy(wrapper);
Element bstElem = encrKey.getBinarySecurityTokenElement();
if (bstElem != null) {
addTopDownElement(bstElem);
}
encrKey.appendToHeader();
WSSecDKSign dkSig = new WSSecDKSign(secHeader);
dkSig.setIdAllocator(wssConfig.getIdAllocator());
dkSig.setCallbackLookup(callbackLookup);
if (token.getVersion() == SPConstants.SPVersion.SP11) {
dkSig.setWscVersion(ConversationConstants.VERSION_05_02);
}
dkSig.setSigCanonicalization(binding.getAlgorithmSuite().getC14n().getValue());
dkSig.setSignatureAlgorithm(binding.getAlgorithmSuite().getSymmetricSignature());
dkSig.setAttachmentCallbackHandler(new AttachmentCallbackHandler(message));
dkSig.setStoreBytesInAttachment(storeBytesInAttachment);
dkSig.setExpandXopInclude(isExpandXopInclude());
dkSig.setWsDocInfo(wsDocInfo);
AlgorithmSuiteType algType = binding.getAlgorithmSuite().getAlgorithmSuiteType();
dkSig.setDerivedKeyLength(algType.getSignatureDerivedKeyLength() / 8);
dkSig.setExternalKey(encrKey.getEphemeralKey(), encrKey.getId());
dkSig.prepare();
dkSig.getParts().addAll(sigParts);
List<Reference> referenceList = dkSig.addReferencesToSign(sigParts);
// Do signature
dkSig.appendDKElementToHeader();
dkSig.computeSignature(referenceList, false, null);
return dkSig.getSignatureValue();
}
WSSecSignature sig = getSignatureBuilder(token, false, false);
assertPolicy(wrapper);
if (sig != null) {
sig.prependBSTElementToHeader();
List<Reference> referenceList = sig.addReferencesToSign(sigParts);
if (bottomUpElement == null) {
sig.computeSignature(referenceList, false, null);
} else {
sig.computeSignature(referenceList, true, bottomUpElement);
}
bottomUpElement = sig.getSignatureElement();
mainSigId = sig.getId();
return sig.getSignatureValue();
}
return new byte[0];
}
use of javax.xml.crypto.dsig.Reference in project camel by apache.
the class TimestampProperty method get.
@Override
public Output get(Input input) throws Exception {
Transform transform = input.getSignatureFactory().newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null);
Reference ref = input.getSignatureFactory().newReference("#propertiesObject", input.getSignatureFactory().newDigestMethod(input.getContentDigestAlgorithm(), null), Collections.singletonList(transform), null, null);
String doc2 = "<ts:timestamp xmlns:ts=\"http:/timestamp\">" + System.currentTimeMillis() + "</ts:timestamp>";
InputStream is = new ByteArrayInputStream(doc2.getBytes("UTF-8"));
Document doc = XmlSignatureHelper.newDocumentBuilder(Boolean.TRUE).parse(is);
DOMStructure structure = new DOMStructure(doc.getDocumentElement());
SignatureProperty prop = input.getSignatureFactory().newSignatureProperty(Collections.singletonList(structure), input.getSignatureId(), "property");
SignatureProperties properties = input.getSignatureFactory().newSignatureProperties(Collections.singletonList(prop), "properties");
XMLObject propertiesObject = input.getSignatureFactory().newXMLObject(Collections.singletonList(properties), "propertiesObject", null, null);
XmlSignatureProperties.Output result = new Output();
result.setReferences(Collections.singletonList(ref));
result.setObjects(Collections.singletonList(propertiesObject));
return result;
}
use of javax.xml.crypto.dsig.Reference in project camel by apache.
the class XmlVerifierProcessor method verify.
@SuppressWarnings("unchecked")
protected void verify(InputStream input, final Message out) throws Exception {
//NOPMD
LOG.debug("Verification of XML signature document started");
final Document doc = parseInput(input, out);
XMLSignatureFactory fac;
// not work
try {
fac = XMLSignatureFactory.getInstance("DOM", "ApacheXMLDSig");
} catch (NoSuchProviderException ex) {
fac = XMLSignatureFactory.getInstance("DOM");
}
KeySelector selector = getConfiguration().getKeySelector();
if (selector == null) {
throw new IllegalStateException("Wrong configuration. Key selector is missing.");
}
DOMValidateContext valContext = new DOMValidateContext(selector, doc);
valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
valContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE);
if (getConfiguration().getSecureValidation() == Boolean.TRUE) {
valContext.setProperty("org.apache.jcp.xml.dsig.secureValidation", Boolean.TRUE);
valContext.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.TRUE);
}
setUriDereferencerAndBaseUri(valContext);
setCryptoContextProperties(valContext);
NodeList signatureNodes = getSignatureNodes(doc);
List<XMLObject> collectedObjects = new ArrayList<XMLObject>(3);
List<Reference> collectedReferences = new ArrayList<Reference>(3);
int totalCount = signatureNodes.getLength();
for (int i = 0; i < totalCount; i++) {
Element signatureNode = (Element) signatureNodes.item(i);
valContext.setNode(signatureNode);
final XMLSignature signature = fac.unmarshalXMLSignature(valContext);
if (getConfiguration().getXmlSignatureChecker() != null) {
XmlSignatureChecker.Input checkerInput = new CheckerInputBuilder().message(out).messageBodyDocument(doc).keyInfo(signature.getKeyInfo()).currentCountOfSignatures(i + 1).currentSignatureElement(signatureNode).objects(signature.getObjects()).signatureValue(signature.getSignatureValue()).signedInfo(signature.getSignedInfo()).totalCountOfSignatures(totalCount).xmlSchemaValidationExecuted(getSchemaResourceUri(out) != null).build();
getConfiguration().getXmlSignatureChecker().checkBeforeCoreValidation(checkerInput);
}
boolean coreValidity;
try {
coreValidity = signature.validate(valContext);
} catch (XMLSignatureException se) {
throw getConfiguration().getValidationFailedHandler().onXMLSignatureException(se);
}
// Check core validation status
boolean goon = coreValidity;
if (!coreValidity) {
goon = handleSignatureValidationFailed(valContext, signature);
}
if (goon) {
LOG.debug("XML signature {} verified", i + 1);
} else {
throw new XmlSignatureInvalidException("XML signature validation failed");
}
collectedObjects.addAll(signature.getObjects());
collectedReferences.addAll(signature.getSignedInfo().getReferences());
}
map2Message(collectedReferences, collectedObjects, out, doc);
}
Aggregations