Code development platform for open source projects from the European Union institutions :large_blue_circle: EU Login authentication by SMS will be completely phased out by mid-2025. To see alternatives please check here

Skip to content
Snippets Groups Projects
Commit 06410a2e authored by Markus Quaritsch's avatar Markus Quaritsch
Browse files

extending tests

parent 436dd5bd
No related branches found
No related tags found
No related merge requests found
......@@ -17,7 +17,7 @@ namespace TUGraz.VectoHashing.Impl
DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"
};
reference.AddTransform(new XmlDsigVectoTransform());
reference.AddTransform(new XmlDsigC14NTransform());
reference.AddTransform(new XmlDsigExcC14NTransform());
signedXml.AddReference(reference);
......
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using TUGraz.VectoCommon.Models;
using TUGraz.VectoCommon.Utils;
using TUGraz.VectoCore.Resources;
using TUGraz.VectoCore.Utils;
using TUGraz.VectoHashing.Impl;
using TUGraz.VectoHashing.Util;
......@@ -18,10 +13,8 @@ namespace TUGraz.VectoHashing
{
public class VectoHash : IVectoHash
{
protected XmlDocument document;
private XPathNavigator Navigator;
protected XmlDocument Document;
private XmlNamespaceManager Manager;
private XPathHelper Helper;
public static VectoHash Load(string filename)
{
......@@ -44,18 +37,16 @@ namespace TUGraz.VectoHashing
protected VectoHash(XmlDocument doc)
{
document = doc;
Navigator = doc.CreateNavigator();
Manager = new XmlNamespaceManager(Navigator.NameTable);
Helper = new XPathHelper(ExecutionMode.Declaration);
Helper.AddNamespaces(Manager);
Document = doc;
Manager = new XmlNamespaceManager(doc.NameTable);
}
public IList<VectoComponents> GetContainigComponents()
{
var retVal = new List<VectoComponents>();
foreach (var component in EnumHelper.GetValues<VectoComponents>()) {
var count = Navigator.Select(string.Format("//*[local-name()='{0}']", component.XMLElementName()), Manager).Count;
var count =
Document.SelectNodes(string.Format("//*[local-name()='{0}']", component.XMLElementName()), Manager).Count;
for (var i = 0; i < count; i++) {
retVal.Add(component);
}
......@@ -66,14 +57,14 @@ namespace TUGraz.VectoHashing
public string ComputeHash()
{
var toSign = GetIdForElement(GetComponentQueryString());
var hash = XMLHashProvider.ComputeHash(document, toSign);
var hash = XMLHashProvider.ComputeHash(Document, toSign);
return GetHashValue(hash, toSign);
}
public string ComputeHash(VectoComponents component, int index = 0)
{
var toSign = GetIdForElement(GetComponentQueryString(component), index);
var hash = XMLHashProvider.ComputeHash(document, toSign);
var hash = XMLHashProvider.ComputeHash(Document, toSign);
return GetHashValue(hash, toSign);
}
......@@ -87,12 +78,12 @@ namespace TUGraz.VectoHashing
throw new Exception("input must not contain multiple components!");
}
var query = string.Format("//*[local-name()='{0}']/*[local-name()='Data']", components[0]);
var node = document.SelectSingleNode(query);
var node = Document.SelectSingleNode(query);
if (node == null) {
throw new Exception(string.Format("'Data' element for component '{0}' not found!", components[0]));
}
query = string.Format("//*[local-name()='{0}']/*[local-name()='Signature']", components[0]);
var sigNodes = document.SelectNodes(query);
var sigNodes = Document.SelectNodes(query);
if (sigNodes != null && sigNodes.Count > 0) {
throw new Exception("input data already contains a signature element");
}
......@@ -105,7 +96,7 @@ namespace TUGraz.VectoHashing
idSet = true;
}
if (!idSet) {
var attr = document.CreateAttribute(XMLNames.Component_ID_Attr);
var attr = Document.CreateAttribute(XMLNames.Component_ID_Attr);
attr.Value = id;
if (node.Attributes == null) {
throw new Exception("failed to add 'id' attribute");
......@@ -113,27 +104,27 @@ namespace TUGraz.VectoHashing
node.Attributes.Append(attr);
}
var hash = XMLHashProvider.ComputeHash(document, id);
var sig = document.CreateElement(XMLNames.DI_Signature, node.NamespaceURI);
var hash = XMLHashProvider.ComputeHash(Document, id);
var sig = Document.CreateElement(XMLNames.DI_Signature, node.NamespaceURI);
if (node.ParentNode == null || hash.DocumentElement == null) {
throw new Exception("Invalid format of document and/or created hash");
}
sig.AppendChild(document.ImportNode(hash.DocumentElement, true));
sig.AppendChild(Document.ImportNode(hash.DocumentElement, true));
node.ParentNode.AppendChild(sig);
return document.ToXDocument();
return Document.ToXDocument();
}
public string ReadHash()
{
var toRead = GetIdForElement(GetComponentQueryString());
return GetHashValue(document, toRead);
return GetHashValue(Document, toRead);
}
public string ReadHash(VectoComponents component, int index = 0)
{
var toRead = GetIdForElement(GetComponentQueryString(component), index);
return GetHashValue(document, toRead);
return GetHashValue(Document, toRead);
}
public bool ValidateHash()
......@@ -159,7 +150,7 @@ namespace TUGraz.VectoHashing
private string GetIdForElement(string query, int index = 0)
{
var node = document.SelectNodes(query);
var node = Document.SelectNodes(query);
if (node == null) {
return null;
}
......
......@@ -19,9 +19,8 @@ namespace VectoHashingTest
public const string UnorderedXMLVehicle = @"Testdata\XML\Variations\vecto_vehicle-sample_FULL_Entry_Order.xml";
public const string HashSimpleXML = "U2zic7KOnKw60rzh+KKQ1lwZL6NmXju+DXG7cYYmlxo=";
public const string HashEngineXML = "rZHmuuC5m7cD/O/2eJ3rikBlJDVe6mNoLksbWauJfrI=";
public const string HashVehicleXML = "EMVWU3nhpMX5g6KGWLaQiRjNnz3WhJS/2TIlyiiV9wE=";
public const string HashEngineXML = "cfPKB2LkHIbznFA9aQwCNfNLSj9V7qNnSskyOxaXB+o=";
public const string HashVehicleXML = "yZCH9sF1GUdawVOa1fKQ2zvuUHg5ZthmitTOcWg/s1Y=";
[TestMethod]
public void HashSimpleXml()
......
Source diff could not be displayed: it is too large. Options to address this: view the blob.
using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.XPath;
using NUnit.Framework;
using TUGraz.VectoCore.Utils;
using TUGraz.VectoHashing;
using VectoHashingTest.Utils;
using Assert = NUnit.Framework.Assert;
......@@ -171,5 +177,92 @@ namespace VectoHashingTest
var h = VectoHash.Load(file);
AssertHelper.Exception<Exception>(() => { var r = h.AddHash(); }, expectedExceptionMsg);
}
[TestCase()]
public void TestLoadFromStream()
{
var fs = new FileStream(BasicHasingTests.ReferenceXMLVehicle, FileMode.Open);
var h = VectoHash.Load(fs);
var hash = h.ComputeHash();
Assert.AreEqual(BasicHasingTests.HashVehicleXML, hash);
fs.Close();
}
[TestCase(WhitespaceHandling.All),
TestCase(WhitespaceHandling.None),
TestCase(WhitespaceHandling.Significant)]
public void TestLoadXmlDocument(WhitespaceHandling whitespace)
{
var xml = new XmlDocument();
var reader = new XmlTextReader(BasicHasingTests.ReferenceXMLVehicle);
reader.WhitespaceHandling = whitespace;
xml.Load(reader);
var h = VectoHash.Load(xml);
var hash = h.ComputeHash();
Assert.AreEqual(BasicHasingTests.HashVehicleXML, hash);
}
[TestCase(@"Testdata\XML\ToHash\vecto_engine-input.xml"),
TestCase(@"Testdata\XML\ToHash\vecto_engine_withid-input.xml"),
TestCase(@"Testdata\XML\ToHash\vecto_gearbox-input.xml")]
public void TestHashedComponentIsValid(string file)
{
var destination = Path.GetFileNameWithoutExtension(file) + "_hashed.xml";
var h = VectoHash.Load(file);
var r = h.AddHash();
var writer = new XmlTextWriter(destination, Encoding.UTF8);
r.WriteTo(writer);
writer.Flush();
writer.Close();
var h2 = VectoHash.Load(destination);
Assert.IsTrue(h2.ValidateHash());
// re-load generated XML and perform XSD validation
var settings = new XmlReaderSettings() {
ValidationType = ValidationType.Schema,
ValidationFlags = XmlSchemaValidationFlags.ProcessInlineSchema |
//XmlSchemaValidationFlags.ProcessSchemaLocation |
XmlSchemaValidationFlags.ReportValidationWarnings
};
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
settings.Schemas.Add(GetXMLSchema(false));
var xmlValidator = XmlReader.Create(destination, settings);
var xmlDoc = XDocument.Load(xmlValidator);
}
[TestCase("vecto_vehicle-namespace_prefix.xml", BasicHasingTests.HashVehicleXML)]
public void TestNamespacePrefixVariations(string file, string expectedHash)
{
var h = VectoHash.Load(@"Testdata\XML\Variations\" + file);
var hash = h.ComputeHash();
Assert.AreEqual(expectedHash, hash);
}
private static XmlSchemaSet GetXMLSchema(bool job)
{
var resource = RessourceHelper.LoadResourceAsStream(RessourceHelper.ResourceType.XMLSchema,
job ? "VectoInput.xsd" : "VectoComponent.xsd");
var xset = new XmlSchemaSet() { XmlResolver = new XmlResourceResolver() };
var reader = XmlReader.Create(resource, new XmlReaderSettings(), "schema://");
xset.Add(XmlSchema.Read(reader, null));
xset.Compile();
return xset;
}
private static void ValidationCallBack(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Error) {
throw new Exception(string.Format("Validation error: {0}" + Environment.NewLine +
"Line: {1}", args.Message, args.Exception.LineNumber));
}
}
}
}
\ No newline at end of file
......@@ -39,6 +39,7 @@
<HintPath>..\..\packages\NUnit.2.6.3\lib\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Security" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
</ItemGroup>
......@@ -133,6 +134,9 @@
<Content Include="Testdata\XML\Variations\vecto_engine-sample_Whitespaces.xml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="Testdata\XML\Variations\vecto_vehicle-namespace_prefix.xml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="Testdata\XML\Variations\vecto_vehicle-sample_FULL_Comments.xml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
......@@ -150,6 +154,10 @@
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\VectoCore\VectoCore\VectoCore.csproj">
<Project>{CD36938A-ADD9-4C65-96DA-B397CDEEA90A}</Project>
<Name>VectoCore</Name>
</ProjectReference>
<ProjectReference Include="..\VectoHashing\VectoHashing.csproj">
<Project>{B673E12F-D323-4C4C-8805-9915B2C72D3D}</Project>
<Name>VectoHashing</Name>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment