use of org.apache.xml.security.transforms.Transforms in project OpenAM by OpenRock.
the class FMSigProvider method sign.
/**
* Sign the xml document node whose identifying attribute value
* is as supplied, using enveloped signatures and use exclusive xml
* canonicalization. The resulting signature is inserted after the
* first child node (normally Issuer element for SAML2) of the node
* to be signed.
* @param xmlString String representing an XML document to be signed
* @param idValue id attribute value of the root node to be signed
* @param privateKey Signing key
* @param cert Certificate which contain the public key correlated to
* the signing key; It if is not null, then the signature
* will include the certificate; Otherwise, the signature
* will not include any certificate
* @return Element representing the signature element
* @throws SAML2Exception if the document could not be signed
*/
public Element sign(String xmlString, String idValue, PrivateKey privateKey, X509Certificate cert) throws SAML2Exception {
String classMethod = "FMSigProvider.sign: ";
if (xmlString == null || xmlString.length() == 0 || idValue == null || idValue.length() == 0 || privateKey == null) {
SAML2SDKUtils.debug.error(classMethod + "Either input xml string or id value or " + "private key is null.");
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("nullInput"));
}
Document doc = XMLUtils.toDOMDocument(xmlString, SAML2SDKUtils.debug);
if (doc == null) {
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("errorObtainingElement"));
}
Element root = doc.getDocumentElement();
XMLSignature sig = null;
try {
ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, SAMLConstants.PREFIX_DS);
} catch (XMLSecurityException xse1) {
throw new SAML2Exception(xse1);
}
root.setIdAttribute(SAML2Constants.ID, true);
try {
if ((sigAlg == null) || (sigAlg.trim().length() == 0)) {
if (privateKey.getAlgorithm().equalsIgnoreCase(SAML2Constants.DSA)) {
sigAlg = XMLSignature.ALGO_ID_SIGNATURE_DSA;
} else {
if (privateKey.getAlgorithm().equalsIgnoreCase(SAML2Constants.RSA)) {
sigAlg = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
}
}
}
sig = new XMLSignature(doc, "", sigAlg, c14nMethod);
} catch (XMLSecurityException xse2) {
throw new SAML2Exception(xse2);
}
Node firstChild = root.getFirstChild();
while (firstChild != null && (firstChild.getLocalName() == null || !firstChild.getLocalName().equals("Issuer"))) {
firstChild = firstChild.getNextSibling();
}
Node nextSibling = null;
if (firstChild != null) {
nextSibling = firstChild.getNextSibling();
}
if (nextSibling == null) {
root.appendChild(sig.getElement());
} else {
root.insertBefore(sig.getElement(), nextSibling);
}
sig.getSignedInfo().addResourceResolver(new com.sun.identity.saml.xmlsig.OfflineResolver());
Transforms transforms = new Transforms(doc);
try {
transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
} catch (TransformationException te1) {
throw new SAML2Exception(te1);
}
try {
transforms.addTransform(transformAlg);
} catch (TransformationException te2) {
throw new SAML2Exception(te2);
}
String ref = "#" + idValue;
try {
sig.addDocument(ref, transforms, Constants.ALGO_ID_DIGEST_SHA1);
} catch (XMLSignatureException sige1) {
throw new SAML2Exception(sige1);
}
if (cert != null) {
try {
sig.addKeyInfo(cert);
} catch (XMLSecurityException xse3) {
throw new SAML2Exception(xse3);
}
}
try {
sig.sign(privateKey);
} catch (XMLSignatureException sige2) {
throw new SAML2Exception(sige2);
}
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message(classMethod + "Signing is successful.");
}
return sig.getElement();
}
use of org.apache.xml.security.transforms.Transforms in project xades4j by luisgoncalves.
the class SignedDataObjectsProcessor method process.
/**
* Processes the signed data objects and adds the corresponding {@code Reference}s
* and {@code Object}s to the signature. This method must be invoked before
* adding any other {@code Reference}s to the signature.
*
* @return the reference mappings resulting from the data object descriptions.
*
* @throws UnsupportedAlgorithmException
* @throws IllegalStateException if the signature already contains {@code Reference}s
*/
Map<DataObjectDesc, Reference> process(SignedDataObjects signedDataObjects, XMLSignature xmlSignature) throws UnsupportedAlgorithmException {
if (xmlSignature.getSignedInfo().getLength() != 0) {
throw new IllegalStateException("XMLSignature already contais references");
}
for (ResourceResolver resolver : signedDataObjects.getResourceResolvers()) {
xmlSignature.addResourceResolver(resolver);
}
Collection<DataObjectDesc> dataObjsDescs = signedDataObjects.getDataObjectsDescs();
Map<DataObjectDesc, Reference> referenceMappings = new IdentityHashMap<DataObjectDesc, Reference>(dataObjsDescs.size());
String refUri, refType;
Transforms transforms;
String digestMethodUri = this.algorithmsProvider.getDigestAlgorithmForDataObjsReferences();
boolean hasNullURIReference = false;
/**/
try {
for (DataObjectDesc dataObjDesc : dataObjsDescs) {
transforms = processTransforms(dataObjDesc, xmlSignature.getDocument());
if (dataObjDesc instanceof DataObjectReference) {
// If the data object info is a DataObjectReference, the Reference uri
// and type are the ones specified on the object.
DataObjectReference dataObjRef = (DataObjectReference) dataObjDesc;
refUri = dataObjRef.getUri();
refType = dataObjRef.getType();
} else if (dataObjDesc instanceof EnvelopedXmlObject) {
// If the data object info is a EnvelopedXmlObject we need to create a
// XMLObject to embed it. The Reference uri will refer the new
// XMLObject's id.
EnvelopedXmlObject envXmlObj = (EnvelopedXmlObject) dataObjDesc;
refUri = String.format("%s-object%d", xmlSignature.getId(), xmlSignature.getObjectLength());
refType = Reference.OBJECT_URI;
ObjectContainer xmlObj = new ObjectContainer(xmlSignature.getDocument());
xmlObj.setId(refUri);
xmlObj.appendChild(envXmlObj.getContent());
xmlObj.setMimeType(envXmlObj.getMimeType());
xmlObj.setEncoding(envXmlObj.getEncoding());
xmlSignature.appendObject(xmlObj);
refUri = '#' + refUri;
} else if (dataObjDesc instanceof AnonymousDataObjectReference) {
if (hasNullURIReference) {
// This shouldn't happen because SignedDataObjects does the validation.
throw new IllegalStateException("Multiple AnonymousDataObjectReference detected");
}
hasNullURIReference = true;
refUri = refType = null;
AnonymousDataObjectReference anonymousRef = (AnonymousDataObjectReference) dataObjDesc;
xmlSignature.addResourceResolver(new ResolverAnonymous(anonymousRef.getDataStream()));
} else {
throw new ClassCastException("Unsupported SignedDataObjectDesc. Must be one of DataObjectReference, EnvelopedXmlObject and AnonymousDataObjectReference");
}
// Add the Reference. References need an ID because data object
// properties may refer them.
xmlSignature.addDocument(refUri, transforms, digestMethodUri, // id
String.format("%s-ref%d", xmlSignature.getId(), referenceMappings.size()), refType);
// SignedDataObjects doesn't allow repeated instances, so there's no
// need to check for duplicate entries on the map.
Reference ref = xmlSignature.getSignedInfo().item(referenceMappings.size());
referenceMappings.put(dataObjDesc, ref);
}
} catch (XMLSignatureException ex) {
// algorithm is not supported.
throw new UnsupportedAlgorithmException("Digest algorithm not supported in the XML Signature provider", digestMethodUri, ex);
} catch (org.apache.xml.security.exceptions.XMLSecurityException ex) {
// when signing.
throw new IllegalStateException(ex);
}
return Collections.unmodifiableMap(referenceMappings);
}
use of org.apache.xml.security.transforms.Transforms in project santuario-java by apache.
the class AbstractSignatureVerificationTest method signUsingDOM.
/**
* Sign the document using DOM
*/
protected XMLSignature signUsingDOM(String algorithm, Document document, List<String> localNames, Key signingKey, String c14nMethod, String digestMethod, List<ReferenceInfo> additionalReferences, String referenceC14NMethod, ResourceResolverSpi resourceResolverSpi) throws Exception {
XMLSignature sig = new XMLSignature(document, "", algorithm, c14nMethod);
if (resourceResolverSpi != null) {
sig.addResourceResolver(resourceResolverSpi);
}
Element root = document.getDocumentElement();
root.appendChild(sig.getElement());
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
xpath.setNamespaceContext(new DSNamespaceContext());
for (String localName : localNames) {
String expression = "//*[local-name()='" + localName + "']";
NodeList elementsToSign = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);
for (int i = 0; i < elementsToSign.getLength(); i++) {
Element elementToSign = (Element) elementsToSign.item(i);
Assert.assertNotNull(elementToSign);
String id = UUID.randomUUID().toString();
elementToSign.setAttributeNS(null, "Id", id);
elementToSign.setIdAttributeNS(null, "Id", true);
Transforms transforms = new Transforms(document);
transforms.addTransform(referenceC14NMethod);
sig.addDocument("#" + id, transforms, digestMethod);
}
}
if (additionalReferences != null) {
for (int i = 0; i < additionalReferences.size(); i++) {
ReferenceInfo referenceInfo = additionalReferences.get(i);
if (referenceInfo.isBinary()) {
sig.addDocument(referenceInfo.getResource(), null, referenceInfo.getDigestMethod());
} else {
Transforms transforms = new Transforms(document);
for (int j = 0; j < referenceInfo.getC14NMethod().length; j++) {
String transform = referenceInfo.getC14NMethod()[j];
transforms.addTransform(transform);
}
sig.addDocument(referenceInfo.getResource(), transforms, referenceInfo.getDigestMethod());
}
}
}
sig.sign(signingKey);
String expression = "//ds:Signature[1]";
Element sigElement = (Element) xpath.evaluate(expression, document, XPathConstants.NODE);
Assert.assertNotNull(sigElement);
return sig;
}
use of org.apache.xml.security.transforms.Transforms in project santuario-java by apache.
the class ECDSASignatureTest method doSign.
private byte[] doSign() throws Exception {
PrivateKey privateKey = (PrivateKey) keyStore.getKey("ECDSA", ECDSA_JKS_PASSWORD.toCharArray());
org.w3c.dom.Document doc = db.newDocument();
doc.appendChild(doc.createComment(" Comment before "));
Element root = doc.createElementNS("", "RootElement");
doc.appendChild(root);
root.appendChild(doc.createTextNode("Some simple text\n"));
Element canonElem = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_CANONICALIZATIONMETHOD);
canonElem.setAttributeNS(null, Constants._ATT_ALGORITHM, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
SignatureAlgorithm signatureAlgorithm = new SignatureAlgorithm(doc, XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1);
XMLSignature sig = new XMLSignature(doc, null, signatureAlgorithm.getElement(), canonElem);
root.appendChild(sig.getElement());
doc.appendChild(doc.createComment(" Comment after "));
Transforms transforms = new Transforms(doc);
transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
X509Certificate x509 = (X509Certificate) keyStore.getCertificate("ECDSA");
sig.addKeyInfo(x509);
sig.sign(privateKey);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
XMLUtils.outputDOMc14nWithComments(doc, bos);
return bos.toByteArray();
}
use of org.apache.xml.security.transforms.Transforms in project xades4j by luisgoncalves.
the class SignerBES method sign.
@Override
public final XadesSignatureResult sign(SignedDataObjects signedDataObjects, Node referenceNode, SignatureAppendingStrategy appendingStrategy) throws XAdES4jException {
if (null == referenceNode) {
throw new NullPointerException("Reference node node cannot be null");
}
if (null == signedDataObjects) {
throw new NullPointerException("References cannot be null");
}
if (signedDataObjects.isEmpty()) {
throw new IllegalArgumentException("Data objects list is empty");
}
Document signatureDocument = DOMHelper.getOwnerDocument(referenceNode);
// Generate unique identifiers for the Signature and the SignedProperties.
String signatureId = String.format("xmldsig-%s", UUID.randomUUID());
String signedPropsId = String.format("%s-signedprops", signatureId);
// Signing certificate chain (may contain only the signing certificate).
List<X509Certificate> signingCertificateChain = this.keyingProvider.getSigningCertificateChain();
if (null == signingCertificateChain || signingCertificateChain.isEmpty()) {
throw new SigningCertChainException("Signing certificate not provided");
}
X509Certificate signingCertificate = signingCertificateChain.get(0);
// The XMLSignature (ds:Signature).
XMLSignature signature = createSignature(signatureDocument, signedDataObjects.getBaseUri(), signingCertificate.getPublicKey().getAlgorithm());
signature.setId(signatureId);
/* References */
// Process the data object descriptions to get the References and mappings.
// After this call all the signed data objects References and XMLObjects
// are added to the signature.
SignedDataObjectsProcessor.Result signedDataObjectsResult = this.dataObjectDescsProcessor.process(signedDataObjects, signature);
/* ds:KeyInfo */
this.keyInfoBuilder.buildKeyInfo(signingCertificateChain, signature);
/* QualifyingProperties element */
// Create the QualifyingProperties element
Element qualifyingPropsElem = ElementProxy.createElementForFamily(signature.getDocument(), QualifyingProperty.XADES_XMLNS, QualifyingProperty.QUALIFYING_PROPS_TAG);
qualifyingPropsElem.setAttributeNS(null, QualifyingProperty.TARGET_ATTR, '#' + signatureId);
qualifyingPropsElem.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:xades141", QualifyingProperty.XADESV141_XMLNS);
// ds:Object to contain QualifyingProperties
ObjectContainer qPropsXmlObj = new ObjectContainer(signature.getDocument());
qPropsXmlObj.appendChild(qualifyingPropsElem);
try {
signature.appendObject(qPropsXmlObj);
} catch (XMLSignatureException ex) {
// -> xmlSignature.appendObject(xmlObj): not thrown when signing.
throw new IllegalStateException(ex);
}
/* Collect the properties */
// Get the format specific signature properties.
Collection<SignedSignatureProperty> fsssp = new ArrayList<SignedSignatureProperty>(2);
Collection<UnsignedSignatureProperty> fsusp = new ArrayList<UnsignedSignatureProperty>(2);
getFormatSpecificSignatureProperties(fsssp, fsusp, signingCertificateChain);
// Gather all the signature and data objects properties.
QualifyingProperties qualifProps = qualifPropsProcessor.getQualifyingProperties(signedDataObjects, fsssp, fsusp);
try {
// The signature needs to be appended to the document from now on because
// property data generation may need to dereference same-document data
// object references.
appendingStrategy.append(signature.getElement(), referenceNode);
// Digest manifests because property data generation may need to get Reference digest values
digestManifests(signedDataObjectsResult.manifests);
/* Signed properties */
// Create the context for signed properties data objects generation.
PropertiesDataGenerationContext propsDataGenCtx = new PropertiesDataGenerationContext(signedDataObjects.getDataObjectsDescs(), signedDataObjectsResult.referenceMappings, signatureDocument);
// Generate the signed properties data objects. The data objects structure
// is verifier in the process.
SigAndDataObjsPropertiesData signedPropsData = this.propsDataObjectsGenerator.generateSignedPropertiesData(qualifProps.getSignedProperties(), propsDataGenCtx);
// Marshal the signed properties data to the QualifyingProperties node.
this.signedPropsMarshaller.marshal(signedPropsData, qualifyingPropsElem);
Element signedPropsElem = DOMHelper.getFirstChildElement(qualifyingPropsElem);
DOMHelper.setIdAsXmlId(signedPropsElem, signedPropsId);
// SignedProperties reference
// XAdES 6.3.1: "In order to protect the properties with the signature,
// a ds:Reference element MUST be added to the XMLDSIG signature (...)
// composed in such a way that it uses the SignedProperties element (...)
// as the input for computing its corresponding digest. Additionally,
// (...) use the Type attribute of this particular ds:Reference element,
// with its value set to: http://uri.etsi.org/01903#SignedProperties."
String digestAlgUri = this.signatureAlgorithms.getDigestAlgorithmForDataObjectReferences();
if (StringUtils.isNullOrEmptyString(digestAlgUri)) {
throw new NullPointerException("Digest algorithm URI not provided");
}
// Use same canonicalization URI as specified in the ds:CanonicalizationMethod for Signature.
Algorithm canonAlg = this.signatureAlgorithms.getCanonicalizationAlgorithmForSignature();
try {
CanonicalizerUtils.checkC14NAlgorithm(canonAlg);
Transforms transforms = TransformUtils.createTransforms(canonAlg, this.algorithmsParametersMarshaller, signatureDocument);
signature.addDocument('#' + signedPropsId, transforms, digestAlgUri, null, QualifyingProperty.SIGNED_PROPS_TYPE_URI);
} catch (XMLSignatureException ex) {
// shouldn't be thrown now!
throw new UnsupportedAlgorithmException("Digest algorithm not supported in the XML Signature provider", digestAlgUri, ex);
}
// Apply the signature
try {
PrivateKey signingKey = keyingProvider.getSigningKey(signingCertificate);
signature.sign(signingKey);
} catch (XMLSignatureException ex) {
throw new XAdES4jXMLSigException(ex.getMessage(), ex);
}
// Set the ds:SignatureValue id.
Element sigValueElem = DOMHelper.getFirstDescendant(signature.getElement(), Constants.SignatureSpecNS, Constants._TAG_SIGNATUREVALUE);
DOMHelper.setIdAsXmlId(sigValueElem, String.format("%s-sigvalue", signatureId));
/* Marshal unsigned properties */
// Generate the unsigned properties data objects. The data objects structure
// is verifier in the process.
propsDataGenCtx.setTargetXmlSignature(signature);
SigAndDataObjsPropertiesData unsignedPropsData = this.propsDataObjectsGenerator.generateUnsignedPropertiesData(qualifProps.getUnsignedProperties(), propsDataGenCtx);
// Marshal the unsigned properties to the final QualifyingProperties node.
this.unsignedPropsMarshaller.marshal(unsignedPropsData, qualifyingPropsElem);
} catch (XAdES4jException ex) {
appendingStrategy.revert(signature.getElement(), referenceNode);
throw ex;
}
return new XadesSignatureResult(signature, qualifProps);
}
Aggregations