use of javax.xml.crypto.dsig.Transform in project poi by apache.
the class EnvelopedSignatureFacet method preSign.
@Override
public void preSign(Document document, List<Reference> references, List<XMLObject> objects) throws XMLSignatureException {
List<Transform> transforms = new ArrayList<Transform>();
Transform envelopedTransform = newTransform(CanonicalizationMethod.ENVELOPED);
transforms.add(envelopedTransform);
Transform exclusiveTransform = newTransform(CanonicalizationMethod.EXCLUSIVE);
transforms.add(exclusiveTransform);
Reference reference = newReference("", transforms, null, null, null);
references.add(reference);
}
use of javax.xml.crypto.dsig.Transform in project poi by apache.
the class OOXMLSignatureFacet method addManifestReferences.
@SuppressWarnings("resource")
protected void addManifestReferences(List<Reference> manifestReferences) throws XMLSignatureException {
OPCPackage ooxml = signatureConfig.getOpcPackage();
List<PackagePart> relsEntryNames = ooxml.getPartsByContentType(ContentTypes.RELATIONSHIPS_PART);
Set<String> digestedPartNames = new HashSet<String>();
for (PackagePart pp : relsEntryNames) {
String baseUri = pp.getPartName().getName().replaceFirst("(.*)/_rels/.*", "$1");
PackageRelationshipCollection prc;
try {
prc = new PackageRelationshipCollection(ooxml);
prc.parseRelationshipsPart(pp);
} catch (InvalidFormatException e) {
throw new XMLSignatureException("Invalid relationship descriptor: " + pp.getPartName().getName(), e);
}
RelationshipTransformParameterSpec parameterSpec = new RelationshipTransformParameterSpec();
for (PackageRelationship relationship : prc) {
String relationshipType = relationship.getRelationshipType();
/*
* ECMA-376 Part 2 - 3rd edition
* 13.2.4.16 Manifest Element
* "The producer shall not create a Manifest element that references any data outside of the package."
*/
if (TargetMode.EXTERNAL == relationship.getTargetMode()) {
continue;
}
if (!isSignedRelationship(relationshipType))
continue;
parameterSpec.addRelationshipReference(relationship.getId());
// TODO: find a better way ...
String partName = relationship.getTargetURI().toString();
if (!partName.startsWith(baseUri)) {
partName = baseUri + partName;
}
try {
partName = new URI(partName).normalize().getPath().replace('\\', '/');
LOG.log(POILogger.DEBUG, "part name: " + partName);
} catch (URISyntaxException e) {
throw new XMLSignatureException(e);
}
String contentType;
try {
PackagePartName relName = PackagingURIHelper.createPartName(partName);
PackagePart pp2 = ooxml.getPart(relName);
contentType = pp2.getContentType();
} catch (InvalidFormatException e) {
throw new XMLSignatureException(e);
}
if (relationshipType.endsWith("customXml") && !(contentType.equals("inkml+xml") || contentType.equals("text/xml"))) {
LOG.log(POILogger.DEBUG, "skipping customXml with content type: " + contentType);
continue;
}
if (!digestedPartNames.contains(partName)) {
// We only digest a part once.
String uri = partName + "?ContentType=" + contentType;
Reference reference = newReference(uri, null, null, null, null);
manifestReferences.add(reference);
digestedPartNames.add(partName);
}
}
if (parameterSpec.hasSourceIds()) {
List<Transform> transforms = new ArrayList<Transform>();
transforms.add(newTransform(RelationshipTransformService.TRANSFORM_URI, parameterSpec));
transforms.add(newTransform(CanonicalizationMethod.INCLUSIVE));
String uri = pp.getPartName().getName() + "?ContentType=application/vnd.openxmlformats-package.relationships+xml";
Reference reference = newReference(uri, transforms, null, null, null);
manifestReferences.add(reference);
}
}
}
use of javax.xml.crypto.dsig.Transform in project poi by apache.
the class XAdESSignatureFacet method preSign.
@Override
public void preSign(Document document, List<Reference> references, List<XMLObject> objects) throws XMLSignatureException {
LOG.log(POILogger.DEBUG, "preSign");
// QualifyingProperties
QualifyingPropertiesDocument qualDoc = QualifyingPropertiesDocument.Factory.newInstance();
QualifyingPropertiesType qualifyingProperties = qualDoc.addNewQualifyingProperties();
qualifyingProperties.setTarget("#" + signatureConfig.getPackageSignatureId());
// SignedProperties
SignedPropertiesType signedProperties = qualifyingProperties.addNewSignedProperties();
signedProperties.setId(signatureConfig.getXadesSignatureId());
// SignedSignatureProperties
SignedSignaturePropertiesType signedSignatureProperties = signedProperties.addNewSignedSignatureProperties();
// SigningTime
Calendar xmlGregorianCalendar = Calendar.getInstance(TimeZone.getTimeZone("Z"), Locale.ROOT);
xmlGregorianCalendar.setTime(signatureConfig.getExecutionTime());
xmlGregorianCalendar.clear(Calendar.MILLISECOND);
signedSignatureProperties.setSigningTime(xmlGregorianCalendar);
// SigningCertificate
if (signatureConfig.getSigningCertificateChain() == null || signatureConfig.getSigningCertificateChain().isEmpty()) {
throw new RuntimeException("no signing certificate chain available");
}
CertIDListType signingCertificates = signedSignatureProperties.addNewSigningCertificate();
CertIDType certId = signingCertificates.addNewCert();
X509Certificate certificate = signatureConfig.getSigningCertificateChain().get(0);
setCertID(certId, signatureConfig, signatureConfig.isXadesIssuerNameNoReverseOrder(), certificate);
// ClaimedRole
String role = signatureConfig.getXadesRole();
if (role != null && !role.isEmpty()) {
SignerRoleType signerRole = signedSignatureProperties.addNewSignerRole();
signedSignatureProperties.setSignerRole(signerRole);
ClaimedRolesListType claimedRolesList = signerRole.addNewClaimedRoles();
AnyType claimedRole = claimedRolesList.addNewClaimedRole();
XmlString roleString = XmlString.Factory.newInstance();
roleString.setStringValue(role);
insertXChild(claimedRole, roleString);
}
// XAdES-EPES
SignaturePolicyService policyService = signatureConfig.getSignaturePolicyService();
if (policyService != null) {
SignaturePolicyIdentifierType signaturePolicyIdentifier = signedSignatureProperties.addNewSignaturePolicyIdentifier();
SignaturePolicyIdType signaturePolicyId = signaturePolicyIdentifier.addNewSignaturePolicyId();
ObjectIdentifierType objectIdentifier = signaturePolicyId.addNewSigPolicyId();
objectIdentifier.setDescription(policyService.getSignaturePolicyDescription());
IdentifierType identifier = objectIdentifier.addNewIdentifier();
identifier.setStringValue(policyService.getSignaturePolicyIdentifier());
byte[] signaturePolicyDocumentData = policyService.getSignaturePolicyDocument();
DigestAlgAndValueType sigPolicyHash = signaturePolicyId.addNewSigPolicyHash();
setDigestAlgAndValue(sigPolicyHash, signaturePolicyDocumentData, signatureConfig.getDigestAlgo());
String signaturePolicyDownloadUrl = policyService.getSignaturePolicyDownloadUrl();
if (null != signaturePolicyDownloadUrl) {
SigPolicyQualifiersListType sigPolicyQualifiers = signaturePolicyId.addNewSigPolicyQualifiers();
AnyType sigPolicyQualifier = sigPolicyQualifiers.addNewSigPolicyQualifier();
XmlString spUriElement = XmlString.Factory.newInstance();
spUriElement.setStringValue(signaturePolicyDownloadUrl);
insertXChild(sigPolicyQualifier, spUriElement);
}
} else if (signatureConfig.isXadesSignaturePolicyImplied()) {
SignaturePolicyIdentifierType signaturePolicyIdentifier = signedSignatureProperties.addNewSignaturePolicyIdentifier();
signaturePolicyIdentifier.addNewSignaturePolicyImplied();
}
// DataObjectFormat
if (!dataObjectFormatMimeTypes.isEmpty()) {
SignedDataObjectPropertiesType signedDataObjectProperties = signedProperties.addNewSignedDataObjectProperties();
List<DataObjectFormatType> dataObjectFormats = signedDataObjectProperties.getDataObjectFormatList();
for (Map.Entry<String, String> dataObjectFormatMimeType : this.dataObjectFormatMimeTypes.entrySet()) {
DataObjectFormatType dataObjectFormat = DataObjectFormatType.Factory.newInstance();
dataObjectFormat.setObjectReference("#" + dataObjectFormatMimeType.getKey());
dataObjectFormat.setMimeType(dataObjectFormatMimeType.getValue());
dataObjectFormats.add(dataObjectFormat);
}
}
// add XAdES ds:Object
List<XMLStructure> xadesObjectContent = new ArrayList<XMLStructure>();
Element qualDocElSrc = (Element) qualifyingProperties.getDomNode();
Element qualDocEl = (Element) document.importNode(qualDocElSrc, true);
xadesObjectContent.add(new DOMStructure(qualDocEl));
XMLObject xadesObject = getSignatureFactory().newXMLObject(xadesObjectContent, null, null, null);
objects.add(xadesObject);
// add XAdES ds:Reference
List<Transform> transforms = new ArrayList<Transform>();
Transform exclusiveTransform = newTransform(CanonicalizationMethod.INCLUSIVE);
transforms.add(exclusiveTransform);
Reference reference = newReference("#" + signatureConfig.getXadesSignatureId(), transforms, XADES_TYPE, null, null);
references.add(reference);
}
use of javax.xml.crypto.dsig.Transform in project testcases by coheigea.
the class SignatureJSR105EnvelopedTest method testSignatureUsingJSR105.
// Sign + Verify an XML Document using the JSR-105 API
@org.junit.Test
public void testSignatureUsingJSR105() throws Exception {
// Read in plaintext document
InputStream sourceDocument = this.getClass().getClassLoader().getResourceAsStream("plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(this.getClass().getClassLoader().getResource("clientstore.jks").openStream(), "cspass".toCharArray());
Key key = keyStore.getKey("myclientkey", "ckpass".toCharArray());
X509Certificate cert = (X509Certificate) keyStore.getCertificate("myclientkey");
String signatureId = "_" + UUID.randomUUID().toString();
String signaturePropertyId = "_" + UUID.randomUUID().toString();
// Sign using DOM
XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");
CanonicalizationMethod c14nMethod = signatureFactory.newCanonicalizationMethod("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec) null);
KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory();
X509Data x509Data = keyInfoFactory.newX509Data(Collections.singletonList(cert));
javax.xml.crypto.dsig.keyinfo.KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data));
SignatureMethod signatureMethod = signatureFactory.newSignatureMethod("http://www.w3.org/2000/09/xmldsig#rsa-sha1", null);
Transform transform = signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
DigestMethod digestMethod = signatureFactory.newDigestMethod("http://www.w3.org/2000/09/xmldsig#sha1", null);
Reference reference = signatureFactory.newReference("", digestMethod, Collections.singletonList(transform), null, null);
Transform objectTransform = signatureFactory.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", (TransformParameterSpec) null);
Reference objectReference = signatureFactory.newReference("#" + signaturePropertyId, digestMethod, Collections.singletonList(objectTransform), "http://www.w3.org/2000/09/xmldsig#SignatureProperties", null);
List<Reference> references = new ArrayList<>();
references.add(reference);
references.add(objectReference);
SignedInfo signedInfo = signatureFactory.newSignedInfo(c14nMethod, signatureMethod, references);
// Add a SignatureProperty containing a Timestamp
Element timestamp = document.createElementNS(null, "Timestamp");
timestamp.setTextContent(new Date().toString());
XMLStructure content = new DOMStructure(timestamp);
SignatureProperty signatureProperty = signatureFactory.newSignatureProperty(Collections.singletonList(content), "#" + signatureId, signaturePropertyId);
SignatureProperties signatureProperties = signatureFactory.newSignatureProperties(Collections.singletonList(signatureProperty), null);
XMLObject object = signatureFactory.newXMLObject(Collections.singletonList(signatureProperties), null, null, null);
XMLSignature sig = signatureFactory.newXMLSignature(signedInfo, keyInfo, Collections.singletonList(object), signatureId, null);
XMLSignContext signContext = new DOMSignContext(key, document.getDocumentElement());
sig.sign(signContext);
// XMLUtils.outputDOM(document, System.out);
// Verify using JSR-105
// Find the Signature Element
Element sigElement = SignatureUtils.getSignatureElement(document);
Assert.assertNotNull(sigElement);
XMLValidateContext context = new DOMValidateContext(cert.getPublicKey(), sigElement);
context.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
context.setProperty("org.apache.jcp.xml.dsig.secureValidation", Boolean.TRUE);
context.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.TRUE);
signatureFactory = XMLSignatureFactory.getInstance("DOM");
XMLSignature xmlSignature = signatureFactory.unmarshalXMLSignature(context);
// Check the Signature value
Assert.assertTrue(xmlSignature.validate(context));
// First find the Timestamp
SignatureProperty timestampSignatureProperty = getTimestampSignatureProperty(xmlSignature);
assertNotNull(timestampSignatureProperty);
// Check that what was signed is what we expected to be signed.
boolean foundEnvelopedSig = false;
boolean foundSignedTimestamp = false;
for (Object refObject : signedInfo.getReferences()) {
Reference ref = (Reference) refObject;
if ("".equals(ref.getURI())) {
List<Transform> transforms = (List<Transform>) ref.getTransforms();
if (transforms != null && transforms.stream().anyMatch(t -> t.getAlgorithm().equals(Transform.ENVELOPED))) {
foundEnvelopedSig = true;
}
} else if ("http://www.w3.org/2000/09/xmldsig#SignatureProperties".equals(ref.getType()) && ref.getURI().equals("#" + timestampSignatureProperty.getId())) {
// Found matching SignatureProperties Object
// Now validate Timestamp
validateTimestamp(signatureProperty, cert);
foundSignedTimestamp = true;
}
}
assertEquals(sigElement.getParentNode(), document.getDocumentElement());
assertTrue(foundEnvelopedSig);
assertTrue(foundSignedTimestamp);
}
use of javax.xml.crypto.dsig.Transform in project OpenOLAT by OpenOLAT.
the class XMLDigitalSignatureUtil method signDetached.
/**
* Create a separate XML file with the XML Digital Signature.
*
* of the specified XML file.
* @param xmlFile The XML File to sign
* @param outputSignatureFile Where the Digital Signature is saved
* @param signatureDoc A DOM which hold the signature (optional but if you give one, the root element must exists)
* @throws ParserConfigurationException
* @throws GeneralSecurityException
* @throws NoSuchAlgorithmException
* @throws XMLSignatureException
* @throws MarshalException
* @throws TransformerException
*/
public static void signDetached(String uri, File xmlFile, File outputSignatureFile, Document signatureDoc, String keyName, X509Certificate x509Cert, PrivateKey privateKey) throws IOException, SAXException, ParserConfigurationException, NoSuchAlgorithmException, GeneralSecurityException, MarshalException, XMLSignatureException, TransformerException {
Document doc = getDocument(xmlFile);
// Create the signature factory for creating the signature.
XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance("DOM");
List<Transform> transforms = new ArrayList<Transform>();
// Transform envelopped = sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
// transforms.add(envelopped);
// Create the canonicalization transform to be applied after the XSLT.
CanonicalizationMethod c14n = sigFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
transforms.add(c14n);
// Create the Reference to the XML to be signed specifying the hash algorithm to be used
// and the list of transforms to apply. Also specify the XML to be signed as the current
// document (specified by the first parameter being an empty string).
Reference reference = sigFactory.newReference(uri, sigFactory.newDigestMethod(DigestMethod.SHA256, null), transforms, null, null);
// Create the Signed Info node of the signature by specifying the canonicalization method
// to use (INCLUSIVE), the signing method (RSA_SHA1), and the Reference node to be signed.
SignedInfo si = sigFactory.newSignedInfo(c14n, sigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference));
// Create the KeyInfo node containing the public key information to include in the signature.
KeyInfoFactory kif = sigFactory.getKeyInfoFactory();
X509Data xd = kif.newX509Data(Collections.singletonList(x509Cert));
List<Object> keyInfoList = new ArrayList<>();
if (StringHelper.containsNonWhitespace(keyName)) {
keyInfoList.add(kif.newKeyName(keyName));
}
keyInfoList.add(xd);
KeyInfo ki = kif.newKeyInfo(keyInfoList);
// Get the node to attach the signature.
Node signatureInfoNode = doc.getDocumentElement();
// Create a signing context using the private key.
DOMSignContext dsc = new DOMSignContext(privateKey, signatureInfoNode);
dsc.setBaseURI(uri);
dsc.setURIDereferencer(new FileURIDereferencer(uri, xmlFile));
// Create the signature from the signing context and key info
XMLSignature signature = sigFactory.newXMLSignature(si, ki);
signature.sign(dsc);
NodeList nl = doc.getElementsByTagName("Signature");
if (nl.getLength() == 1) {
if (signatureDoc != null && signatureDoc.getDocumentElement() != null) {
Element rootEl = signatureDoc.getDocumentElement();
rootEl.appendChild(signatureDoc.importNode(nl.item(0), true));
write(rootEl, outputSignatureFile);
} else {
write(nl.item(0), outputSignatureFile);
}
}
}
Aggregations