use of javax.xml.crypto.URIDereferencer in project santuario-java by apache.
the class XMLSignContextTest method testsetngetURIDereferencer.
@org.junit.Test
public void testsetngetURIDereferencer() throws Exception {
assertNull(defContext.getURIDereferencer());
byte[] data = "simpleDereferencer".getBytes();
URIDereferencer deref = new TestUtils.OctetStreamURIDereferencer(data);
defContext.setURIDereferencer(deref);
assertEquals(defContext.getURIDereferencer(), deref);
defContext.setURIDereferencer(null);
assertNull(defContext.getURIDereferencer());
}
use of javax.xml.crypto.URIDereferencer in project santuario-java by apache.
the class ReferenceTest method testvalidate.
private void testvalidate(boolean cache) throws Exception {
Reference ref = null;
String type = "http://www.w3.org/2000/09/xmldsig#Object";
byte[] in = new byte[200];
Random rand = new Random();
// Test XMLSignContext
XMLSignContext signContext;
XMLValidateContext validateContext;
for (int i = 0; i < CRYPTO_ALGS.length; i++) {
rand.nextBytes(in);
URIDereferencer dereferrer = new TestUtils.OctetStreamURIDereferencer(in);
Document doc = TestUtils.newDocument();
signContext = new DOMSignContext(TestUtils.getPrivateKey(CRYPTO_ALGS[i]), doc);
signContext.setURIDereferencer(dereferrer);
if (cache) {
signContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
}
ref = fac.newReference(null, dmSHA1, null, type, null);
XMLSignature sig = fac.newXMLSignature(fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SIG_ALGS[i], null), Collections.singletonList(ref)), kifac.newKeyInfo(Collections.singletonList(kifac.newKeyValue(TestUtils.getPublicKey(CRYPTO_ALGS[i])))));
try {
sig.sign(signContext);
TestUtils.validateSecurityOrEncryptionElement(doc.getDocumentElement());
if (!cache) {
assertNull(ref.getDereferencedData());
assertNull(ref.getDigestInputStream());
} else {
assertNotNull(ref.getDereferencedData());
assertNotNull(ref.getDigestInputStream());
assertTrue(digestInputEqual(ref));
}
validateContext = new DOMValidateContext(TestUtils.getPublicKey(CRYPTO_ALGS[i]), doc.getDocumentElement());
validateContext.setURIDereferencer(dereferrer);
if (cache) {
validateContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
}
boolean result = sig.validate(validateContext);
assertTrue(result);
@SuppressWarnings("unchecked") Iterator<Reference> iter = sig.getSignedInfo().getReferences().iterator();
while (iter.hasNext()) {
Reference validated_ref = iter.next();
if (!cache) {
assertNull(validated_ref.getDereferencedData());
assertNull(validated_ref.getDigestInputStream());
} else {
assertNotNull(validated_ref.getDereferencedData());
assertNotNull(validated_ref.getDigestInputStream());
assertTrue(digestInputEqual(validated_ref));
}
byte[] dv = validated_ref.getDigestValue();
byte[] cdv = validated_ref.getCalculatedDigestValue();
assertTrue(Arrays.equals(dv, cdv));
boolean valid = validated_ref.validate(validateContext);
assertTrue(valid);
}
} catch (XMLSignatureException xse) {
fail("Unexpected Exception: " + xse);
}
}
}
use of javax.xml.crypto.URIDereferencer in project santuario-java by apache.
the class DetachedTest method test.
@org.junit.Test
public void test() {
try {
//
// PART 1 : Creating the detached signature
//
// Create a factory that will be used to generate the signature
// structures
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI());
// Create a Reference to an external URI that will be digested
Reference ref = fac.newReference("http://www.w3.org/TR/xml-stylesheet", fac.newDigestMethod(DigestMethod.SHA1, null));
// Create a DSA KeyPair
KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
kpg.initialize(1024, new SecureRandom("not so random bytes".getBytes()));
KeyPair kp = kpg.generateKeyPair();
// Create a KeyValue containing the generated DSA PublicKey
KeyInfoFactory kif = fac.getKeyInfoFactory();
KeyValue kv = kif.newKeyValue(kp.getPublic());
// Create a KeyInfo and add the KeyValue to it
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
// Create SignedInfo
SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));
// Create XMLSignature
XMLSignature signature = fac.newXMLSignature(si, ki, null, null, null);
// Create an XMLSignContext and set the
// DSA PrivateKey for signing
Document doc = XMLUtils.createDocumentBuilder(false).newDocument();
DOMSignContext signContext = new DOMSignContext(kp.getPrivate(), doc);
signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");
URIDereferencer ud = new LocalHttpCacheURIDereferencer();
signContext.setURIDereferencer(ud);
// Generate (and sign) the XMLSignature
signature.sign(signContext);
TestUtils.validateSecurityOrEncryptionElement(doc.getDocumentElement());
//
// PART 2 : Validating the detached signature
//
// Create a XMLValidateContext & set the DSAPublicKey for validating
XMLValidateContext vc = new DOMValidateContext(kp.getPublic(), doc.getDocumentElement());
vc.setURIDereferencer(ud);
// Validate the Signature (generated above)
boolean coreValidity = signature.validate(vc);
// Check core validation status
if (coreValidity == false) {
// check the validation status of each Reference
@SuppressWarnings("unchecked") Iterator<Reference> i = signature.getSignedInfo().getReferences().iterator();
while (i.hasNext()) {
Reference reference = i.next();
reference.validate(vc);
}
fail("Signature failed core validation");
}
// You can also validate an XML Signature which is in XML format.
// Unmarshal and validate an XMLSignature from a DOMValidateContext
signature = fac.unmarshalXMLSignature(vc);
coreValidity = signature.validate(vc);
assertTrue("Core validity of unmarshalled XMLSignature is false", coreValidity);
} catch (Exception ex) {
fail("Exception: " + ex);
}
}
use of javax.xml.crypto.URIDereferencer in project poi by apache.
the class SignatureInfo method preSign.
/**
* Helper method for adding informations before the signing.
* Normally {@link #confirmSignature()} is sufficient to be used.
*/
@SuppressWarnings("unchecked")
public DigestInfo preSign(Document document, List<DigestInfo> digestInfos) throws XMLSignatureException, MarshalException {
signatureConfig.init(false);
// it's necessary to explicitly set the mdssi namespace, but the sign() method has no
// normal way to interfere with, so we need to add the namespace under the hand ...
EventTarget target = (EventTarget) document;
EventListener creationListener = signatureConfig.getSignatureMarshalListener();
if (creationListener != null) {
if (creationListener instanceof SignatureMarshalListener) {
((SignatureMarshalListener) creationListener).setEventTarget(target);
}
SignatureMarshalListener.setListener(target, creationListener, true);
}
/*
* Signature context construction.
*/
XMLSignContext xmlSignContext = new DOMSignContext(signatureConfig.getKey(), document);
URIDereferencer uriDereferencer = signatureConfig.getUriDereferencer();
if (null != uriDereferencer) {
xmlSignContext.setURIDereferencer(uriDereferencer);
}
for (Map.Entry<String, String> me : signatureConfig.getNamespacePrefixes().entrySet()) {
xmlSignContext.putNamespacePrefix(me.getKey(), me.getValue());
}
xmlSignContext.setDefaultNamespacePrefix("");
// signatureConfig.getNamespacePrefixes().get(XML_DIGSIG_NS));
brokenJvmWorkaround(xmlSignContext);
XMLSignatureFactory signatureFactory = signatureConfig.getSignatureFactory();
/*
* Add ds:References that come from signing client local files.
*/
List<Reference> references = new ArrayList<Reference>();
for (DigestInfo digestInfo : safe(digestInfos)) {
byte[] documentDigestValue = digestInfo.digestValue;
String uri = new File(digestInfo.description).getName();
Reference reference = SignatureFacet.newReference(uri, null, null, null, documentDigestValue, signatureConfig);
references.add(reference);
}
/*
* Invoke the signature facets.
*/
List<XMLObject> objects = new ArrayList<XMLObject>();
for (SignatureFacet signatureFacet : signatureConfig.getSignatureFacets()) {
LOG.log(POILogger.DEBUG, "invoking signature facet: " + signatureFacet.getClass().getSimpleName());
signatureFacet.preSign(document, references, objects);
}
/*
* ds:SignedInfo
*/
SignedInfo signedInfo;
try {
SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(signatureConfig.getSignatureMethodUri(), null);
CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod(signatureConfig.getCanonicalizationMethod(), (C14NMethodParameterSpec) null);
signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, references);
} catch (GeneralSecurityException e) {
throw new XMLSignatureException(e);
}
/*
* JSR105 ds:Signature creation
*/
String signatureValueId = signatureConfig.getPackageSignatureId() + "-signature-value";
javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, null, objects, signatureConfig.getPackageSignatureId(), signatureValueId);
/*
* ds:Signature Marshalling.
*/
xmlSignature.sign(xmlSignContext);
/*
* Completion of undigested ds:References in the ds:Manifests.
*/
for (XMLObject object : objects) {
LOG.log(POILogger.DEBUG, "object java type: " + object.getClass().getName());
List<XMLStructure> objectContentList = object.getContent();
for (XMLStructure objectContent : objectContentList) {
LOG.log(POILogger.DEBUG, "object content java type: " + objectContent.getClass().getName());
if (!(objectContent instanceof Manifest))
continue;
Manifest manifest = (Manifest) objectContent;
List<Reference> manifestReferences = manifest.getReferences();
for (Reference manifestReference : manifestReferences) {
if (manifestReference.getDigestValue() != null)
continue;
DOMReference manifestDOMReference = (DOMReference) manifestReference;
manifestDOMReference.digest(xmlSignContext);
}
}
}
/*
* Completion of undigested ds:References.
*/
List<Reference> signedInfoReferences = signedInfo.getReferences();
for (Reference signedInfoReference : signedInfoReferences) {
DOMReference domReference = (DOMReference) signedInfoReference;
// ds:Reference with external digest value
if (domReference.getDigestValue() != null)
continue;
domReference.digest(xmlSignContext);
}
/*
* Calculation of XML signature digest value.
*/
DOMSignedInfo domSignedInfo = (DOMSignedInfo) signedInfo;
ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
domSignedInfo.canonicalize(xmlSignContext, dataStream);
byte[] octets = dataStream.toByteArray();
/*
* TODO: we could be using DigestOutputStream here to optimize memory
* usage.
*/
MessageDigest md = CryptoFunctions.getMessageDigest(signatureConfig.getDigestAlgo());
byte[] digestValue = md.digest(octets);
String description = signatureConfig.getSignatureDescription();
return new DigestInfo(digestValue, signatureConfig.getDigestAlgo(), description);
}
use of javax.xml.crypto.URIDereferencer in project santuario-java by apache.
the class DOMRetrievalMethod method dereference.
@Override
public Data dereference(XMLCryptoContext context) throws URIReferenceException {
if (context == null) {
throw new NullPointerException("context cannot be null");
}
/*
* If URIDereferencer is specified in context; use it, otherwise use
* built-in.
*/
URIDereferencer deref = context.getURIDereferencer();
if (deref == null) {
deref = DOMURIDereferencer.INSTANCE;
}
Data data = deref.dereference(this, context);
// pass dereferenced data through Transforms
try {
for (Transform transform : transforms) {
data = transform.transform(data, context);
}
} catch (Exception e) {
throw new URIReferenceException(e);
}
// guard against RetrievalMethod loops
if (data instanceof NodeSetData && Utils.secureValidation(context)) {
NodeSetData nsd = (NodeSetData) data;
Iterator<?> i = nsd.iterator();
if (i.hasNext()) {
Node root = (Node) i.next();
if ("RetrievalMethod".equals(root.getLocalName())) {
throw new URIReferenceException("It is forbidden to have one RetrievalMethod point " + "to another when secure validation is enabled");
}
}
}
return data;
}
Aggregations