use of javax.xml.crypto.dsig.spec.TransformParameterSpec in project cas by apereo.
the class AbstractSamlObjectBuilder method signSamlElement.
/**
* Sign SAML element.
*
* @param element the element
* @param privKey the priv key
* @param pubKey the pub key
* @return the element
*/
private static org.jdom.Element signSamlElement(final org.jdom.Element element, final PrivateKey privKey, final PublicKey pubKey) {
try {
final String providerName = System.getProperty("jsr105Provider", SIGNATURE_FACTORY_PROVIDER_CLASS);
final Class<?> clazz = Class.forName(providerName);
final XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance("DOM", (Provider) clazz.getDeclaredConstructor().newInstance());
final List<Transform> envelopedTransform = CollectionUtils.wrap(sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
final Reference ref = sigFactory.newReference(StringUtils.EMPTY, sigFactory.newDigestMethod(DigestMethod.SHA1, null), envelopedTransform, null, null);
// Create the SignatureMethod based on the type of key
final SignatureMethod signatureMethod;
final String algorithm = pubKey.getAlgorithm();
switch(algorithm) {
case "DSA":
signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null);
break;
case "RSA":
signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
break;
default:
throw new IllegalArgumentException("Error signing SAML element: Unsupported type of key");
}
final CanonicalizationMethod canonicalizationMethod = sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null);
// Create the SignedInfo
final SignedInfo signedInfo = sigFactory.newSignedInfo(canonicalizationMethod, signatureMethod, CollectionUtils.wrap(ref));
// Create a KeyValue containing the DSA or RSA PublicKey
final KeyInfoFactory keyInfoFactory = sigFactory.getKeyInfoFactory();
final KeyValue keyValuePair = keyInfoFactory.newKeyValue(pubKey);
// Create a KeyInfo and add the KeyValue to it
final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(CollectionUtils.wrap(keyValuePair));
// Convert the JDOM document to w3c (Java XML signature API requires w3c representation)
final Element w3cElement = toDom(element);
// Create a DOMSignContext and specify the DSA/RSA PrivateKey and
// location of the resulting XMLSignature's parent element
final DOMSignContext dsc = new DOMSignContext(privKey, w3cElement);
final Node xmlSigInsertionPoint = getXmlSignatureInsertLocation(w3cElement);
dsc.setNextSibling(xmlSigInsertionPoint);
// Marshal, generate (and sign) the enveloped signature
final XMLSignature signature = sigFactory.newXMLSignature(signedInfo, keyInfo);
signature.sign(dsc);
return toJdom(w3cElement);
} catch (final Exception e) {
throw new IllegalArgumentException("Error signing SAML element: " + e.getMessage(), e);
}
}
use of javax.xml.crypto.dsig.spec.TransformParameterSpec in project santuario-java by apache.
the class TransformTest method testisFeatureSupported.
@org.junit.Test
public void testisFeatureSupported() throws Exception {
Transform tm;
for (int i = 0; i < TRANSFORM_ALGOS.length; i++) {
String algo = TRANSFORM_ALGOS[i];
TransformParameterSpec params = null;
if (algo.equals(Transform.XPATH)) {
params = new XPathFilterParameterSpec("xPath");
} else if (algo.equals(Transform.XPATH2)) {
params = new XPathFilter2ParameterSpec(Collections.singletonList(new XPathType("xPath2", XPathType.Filter.INTERSECT)));
} else if (algo.equals(Transform.XSLT)) {
params = new XSLTTransformParameterSpec(new XSLTStructure());
}
tm = factory.newTransform(algo, params);
try {
tm.isFeatureSupported(null);
fail(TRANSFORM_ALGOS[i] + ": Should raise a NPE for null feature");
} catch (NullPointerException npe) {
}
assertTrue(!tm.isFeatureSupported("not supported"));
}
}
use of javax.xml.crypto.dsig.spec.TransformParameterSpec in project cxf by apache.
the class MetadataWriter method signMetaInfo.
private static Document signMetaInfo(X509Certificate signingCert, Key signingKey, Document doc, String referenceID) throws Exception {
final String signatureMethod;
if ("SHA1withDSA".equals(signingCert.getSigAlgName())) {
signatureMethod = SignatureMethod.DSA_SHA1;
} else if ("SHA1withRSA".equals(signingCert.getSigAlgName())) {
signatureMethod = SignatureMethod.RSA_SHA1;
} else if ("SHA256withRSA".equals(signingCert.getSigAlgName())) {
signatureMethod = SignatureMethod.RSA_SHA1;
} else {
LOG.error("Unsupported signature method: " + signingCert.getSigAlgName());
throw new RuntimeException("Unsupported signature method: " + signingCert.getSigAlgName());
}
List<Transform> transformList = Arrays.asList(XML_SIGNATURE_FACTORY.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null), XML_SIGNATURE_FACTORY.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null));
// Create a Reference to the enveloped document (in this case,
// you are signing the whole document, so a URI of "" signifies
// that, and also specify the SHA1 digest algorithm and
// the ENVELOPED Transform.
Reference ref = XML_SIGNATURE_FACTORY.newReference("#" + referenceID, XML_SIGNATURE_FACTORY.newDigestMethod(DigestMethod.SHA1, null), transformList, null, null);
// Create the SignedInfo.
SignedInfo si = XML_SIGNATURE_FACTORY.newSignedInfo(XML_SIGNATURE_FACTORY.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), XML_SIGNATURE_FACTORY.newSignatureMethod(signatureMethod, null), Collections.singletonList(ref));
// Create the KeyInfo containing the X509Data.
KeyInfoFactory kif = XML_SIGNATURE_FACTORY.getKeyInfoFactory();
List<Object> x509Content = Arrays.asList(signingCert.getSubjectX500Principal().getName(), signingCert);
X509Data xd = kif.newX509Data(x509Content);
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
// Create a DOMSignContext and specify the RSA PrivateKey and
// location of the resulting XMLSignature's parent element.
// DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement());
DOMSignContext dsc = new DOMSignContext(signingKey, doc.getDocumentElement());
dsc.setIdAttributeNS(doc.getDocumentElement(), null, "ID");
dsc.setNextSibling(doc.getDocumentElement().getFirstChild());
// Create the XMLSignature, but don't sign it yet.
XMLSignature signature = XML_SIGNATURE_FACTORY.newXMLSignature(si, ki);
// Marshal, generate, and sign the enveloped signature.
signature.sign(dsc);
// Output the resulting document.
return doc;
}
use of javax.xml.crypto.dsig.spec.TransformParameterSpec 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.spec.TransformParameterSpec in project santuario-java by apache.
the class TransformTest method testConstructor.
@org.junit.Test
public void testConstructor() throws Exception {
// test newTransform(String algorithm,
// AlgorithmParameterSpec params)
// for generating Transform objects
Transform tm;
for (int i = 0; i < TRANSFORM_ALGOS.length; i++) {
String algo = TRANSFORM_ALGOS[i];
TransformParameterSpec params = null;
if (algo.equals(Transform.XPATH)) {
params = new XPathFilterParameterSpec("xPath");
} else if (algo.equals(Transform.XPATH2)) {
params = new XPathFilter2ParameterSpec(Collections.singletonList(new XPathType("xPath2", XPathType.Filter.INTERSECT)));
} else if (algo.equals(Transform.XSLT)) {
params = new XSLTTransformParameterSpec(new XSLTStructure());
}
try {
tm = factory.newTransform(algo, params);
assertNotNull(tm);
assertEquals(tm.getAlgorithm(), algo);
assertEquals(tm.getParameterSpec(), params);
} catch (Exception ex) {
fail(TRANSFORM_ALGOS[i] + ": Unexpected exception " + ex);
}
try {
tm = factory.newTransform(algo, new TestUtils.MyOwnC14nParameterSpec());
fail(TRANSFORM_ALGOS[i] + ": Should raise an IAPE for invalid parameters");
} catch (InvalidAlgorithmParameterException iape) {
} catch (Exception ex) {
fail(TRANSFORM_ALGOS[i] + ": Should raise a IAPE instead of " + ex);
}
}
try {
tm = factory.newTransform(null, (TransformParameterSpec) null);
fail("Should raise a NPE for null algo");
} catch (NullPointerException npe) {
} catch (Exception ex) {
fail("Should raise a NPE instead of " + ex);
}
try {
tm = factory.newTransform("non-existent", (TransformParameterSpec) null);
fail("Should raise an NSAE for non-existent algos");
} catch (NoSuchAlgorithmException nsae) {
} catch (Exception ex) {
fail("Should raise an NSAE instead of " + ex);
}
}
Aggregations