This commit is contained in:
skidoodle 2024-03-13 00:33:46 +01:00
commit e124a47765
19374 changed files with 9806149 additions and 0 deletions

View file

@ -0,0 +1,36 @@
using System.Security.Cryptography.X509Certificates;
namespace Kreta.EESZTInterface
{
public class CertificateHelper
{
private static readonly string binPath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "bin");
public static X509Certificate2 GetSslCertificate()
{
return new X509Certificate2($@"{binPath}\Certs\eKRETA_prod.pfx", "9e=EH!2q");
}
public static X509Certificate2 GetSTSCertificate()
{
return new X509Certificate2($@"{binPath}\Certs\p_owsm.cer");
}
public static X509Certificate2 GetUserCertificate()
{
return new X509Certificate2($@"{binPath}.\Certs\userEles.pfx", "eKretaBudafoki");
}
public static string CertToBase64String(X509Certificate2 cert)
{
return System.Convert.ToBase64String(cert.RawData);
}
public static X509Certificate2 CertFromBase64String(string base64Encoded)
{
byte[] data = System.Convert.FromBase64String(base64Encoded);
var cert = new X509Certificate2(data);
return cert;
}
}
}

Binary file not shown.

View file

@ -0,0 +1,23 @@
-----BEGIN CERTIFICATE-----
MIIDxTCCAq2gAwIBAgIBSTANBgkqhkiG9w0BAQsFADBrMSAwHgYDVQQDDBdFRVNa
VCBJbmZyYXN0cnVjdHVyZSBDQTEOMAwGA1UECgwFRUVTWlQxFzAVBgNVBAsMDklu
ZnJhc3RydWN0dXJlMREwDwYDVQQHDAhCdWRhcGVzdDELMAkGA1UEBhMCSFUwHhcN
MTUxMTAyMTAxOTQ4WhcNMjUxMTAyMTAxOTQ4WjBjMQswCQYDVQQGEwJIVTERMA8G
A1UECAwIQnVkYXBlc3QxETAPBgNVBAcMCEJ1ZGFwZXN0MQ0wCwYDVQQKDARBRUVL
MQ4wDAYDVQQLDAVFRVNaVDEPMA0GA1UEAwwGcC1vd3NtMIIBIjANBgkqhkiG9w0B
AQEFAAOCAQ8AMIIBCgKCAQEAnlgvOTpUmoiBJzEye7Ip3c54kq5lghNbkelvpSWD
eMpWbP8BhLO5/14jjG2+/1FgWPXYIApzzJ2eAdkYJrQmrkudM2aIdwK/yRiY7WNV
xxlALfE7ryo6YFVe0/xi8e+01mqCN4BGfBUt7sHMBQpDe/l4mEwBIUqKe+kvxgtm
axALc8h+pEaA3dX0e/2ROoYvJPKElcsttxF/Tic90Gly3VKnZlxuwXXRoGfmbRzM
OnMLlRg2+2E8UVt49w3+48IMm40ruIyM+X3Rv6mEM6lAu6pJ7FlM7OD9sdhrWoYq
j+zQrVHzPNxBmQDsAU8X/LQIZiLJmCHYDF9yU/CRZKbW5QIDAQABo3wwejAMBgNV
HRMBAf8EAjAAMAsGA1UdDwQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYB
BQUHAwIwHQYDVR0OBBYEFJxIm4fMv0YpIqyRN5xmx8k10VH+MB8GA1UdIwQYMBaA
FKQVW+2DkEsQkHvalJuY3dMJo4OOMA0GCSqGSIb3DQEBCwUAA4IBAQBOitD9+wpc
57Nc9QXqtbVO7OwdqowW8O6TRw47MlhpjJH6KpCzWAYo9D4flKWwGsT0HZWBSBms
Sfpwj3eGs64Rt8UYfniUU8mG50knbIiwUbUF5prClsEbV5Fqob1l+Bm6K4uBkeGr
RcBav7w5iTt1PW/9IT4kGsJVByQuOe6FFCDs9H6OU/Uj4ymKgRVueNX5nN1iHKHV
d9ZzmFm71cAq2M1xh7NCEYOdWBtq9a8/o1rWMD+kqGyfoK/qpM1Ti7zIOaw0krIA
DNKZapGj94JSeYA23Zj57CWbvq3RYOD7VCe6dKf1BG0mvRKJOxXbCOWDSet9QGi/
daCsXjjxiadL
-----END CERTIFICATE-----

Binary file not shown.

View file

@ -0,0 +1,126 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{E87A83BB-C9D9-4A4D-99C4-32B2A7CE0CFB}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Kreta.EESZTInterface</RootNamespace>
<AssemblyName>Kreta.EESZTInterface</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.IdentityModel" />
<Reference Include="System.Security" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\Tools\SharedAssemblyInfo.cs">
<Link>Properties\SharedAssemblyInfo.cs</Link>
</Compile>
<Compile Include="CertificateHelper.cs" />
<Compile Include="eFTHelper.cs" />
<Compile Include="eFT\CreateSoap.cs" />
<Compile Include="eFT\DoRequest.cs" />
<Compile Include="eFT\Model\AllomanyResz\Response\Adat.cs" />
<Compile Include="eFT\Model\IntezmenyiAllomanyLista\Response\Allomany.cs" />
<Compile Include="eFT\Model\AllomanyResz\Response\AllomanyResz.cs" />
<Compile Include="eFT\Model\AllomanyResz\Request\AllomanyReszRequest.cs" />
<Compile Include="eFT\Model\AllomanyResz\Request\AllomanyReszRequestBusinessContent.cs" />
<Compile Include="eFT\Model\AllomanyResz\Response\AllomanyReszResponse.cs" />
<Compile Include="eFT\Model\AllomanyResz\Response\AllomanyReszResponseBusinessContent.cs" />
<Compile Include="eFT\Model\IntezmenyiAllomanyLista\Response\AllomanyTipus.cs" />
<Compile Include="eFT\Model\BusinessMessageHeader.cs" />
<Compile Include="eFT\Model\EftRequest.cs" />
<Compile Include="eFT\Model\EftResponse.cs" />
<Compile Include="eFT\Model\AllomanyResz\Request\GetAllomanyResz.cs" />
<Compile Include="eFT\Model\AllomanyResz\Response\GetAllomanyReszResponse.cs" />
<Compile Include="eFT\Model\IntezmenyiAllomanyLista\Request\GetIntezmenyiAllomanyLista.cs" />
<Compile Include="eFT\Model\IntezmenyiAllomanyLista\Response\GetIntezmenyiAllomanyListaResponse.cs" />
<Compile Include="eFT\Model\AllomanyResz\Response\Include.cs" />
<Compile Include="eFT\Model\Initiator.cs" />
<Compile Include="eFT\Model\IntezmenyiAllomanyLista\Request\IntezmenyiAllomanyListaRequest.cs" />
<Compile Include="eFT\Model\IntezmenyiAllomanyLista\Request\IntezmenyiAllomanyListaRequestBusinessContent.cs" />
<Compile Include="eFT\Model\IntezmenyiAllomanyLista\Response\IntezmenyiAllomanyListaResponse.cs" />
<Compile Include="eFT\Model\IntezmenyiAllomanyLista\Response\IntezmenyiAllomanyListaResponseBusinessContent.cs" />
<Compile Include="eFT\Model\Logging.cs" />
<Compile Include="eFT\Model\RepresentedUser.cs" />
<Compile Include="eFT\Model\SikeresCimzettAllomanyLetoltes\Request\SikeresAllomanyLetoltesRequest.cs" />
<Compile Include="eFT\Model\SikeresCimzettAllomanyLetoltes\Request\SikeresAllomanyLetoltesRequestBusinessContent.cs" />
<Compile Include="eFT\Model\SikeresCimzettAllomanyLetoltes\Response\SikeresAllomanyLetoltesResponse.cs" />
<Compile Include="eFT\Model\SikeresCimzettAllomanyLetoltes\Request\SikeresCimzettAllomanyLetoltes.cs" />
<Compile Include="eFT\Model\SikeresCimzettAllomanyLetoltes\Response\SikeresCimzettAllomanyLetoltesResponse.cs" />
<Compile Include="Namespaces.cs" />
<Compile Include="Processors\TAJProcessor.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="STS\SamlAssertion.cs" />
<Compile Include="STSHelper.cs" />
<Compile Include="STS\CreateSoap.cs" />
<Compile Include="STS\DoRequest.cs" />
<Compile Include="STS\EncryptHelper.cs" />
<Compile Include="STS\PrefixedSignedXML.cs" />
<Compile Include="STS\SamlRequest.cs" />
<Compile Include="STS\SamlSchemas.cs">
<SubType>code</SubType>
</Compile>
<Compile Include="STS\SignHelper.cs" />
<Compile Include="STS\STSValues.cs" />
<Compile Include="XmlHelper.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="Certs\eKRETA_prod.pfx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Certs\p_owsm.cer">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Certs\userEles.pfx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Kreta.DataAccessManual\Kreta.DataAccessManual.csproj">
<Project>{3212f2bf-6883-48b4-9f7d-0dff4c826221}</Project>
<Name>Kreta.DataAccessManual</Name>
</ProjectReference>
<ProjectReference Include="..\Kreta.Resources\Kreta.Resources.csproj">
<Project>{dfcb4d33-b599-42b2-98c6-b60fd220db0c}</Project>
<Name>Kreta.Resources</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View file

@ -0,0 +1,20 @@
namespace Kreta.EESZTInterface
{
public class Namespaces
{
public const string soap11Ns = "http://schemas.xmlsoap.org/soap/envelope/";
public const string soap12Ns = "http://www.w3.org/2003/05/soap-envelope";
public const string wsseNs = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
public const string wsse11Ns = "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd";
public const string wsuNs = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";
public const string samlNs = "urn:oasis:names:tc:SAML:2.0:assertion";
public const string xopNS = "http://www.w3.org/2004/08/xop/include";
public const string nsNs = "http://docs.oasis-open.org/ws-sx/ws-trust/200512";
public const string dsNs = "http://www.w3.org/2000/09/xmldsig#";
public const string addressingNs = "http://www.w3.org/2005/08/addressing";
public const string c14nNs = "http://www.w3.org/2001/10/xml-exc-c14n#";
public const string xencNs = "http://www.w3.org/2001/04/xmlenc#";
public const string allomanyPublikaloServiceV1Ns = "http://eeszt.gov.hu/ns/eft/ws/AllomanyPublikaloService/v1";
}
}

View file

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Kreta.DataAccessManual.Interfaces;
using Newtonsoft.Json;
namespace Kreta.EESZTInterface.Processors
{
public class TAJProcessor
{
private readonly List<string> tajSzamok = new List<string>();
public void AddFileContent(byte[] bytes)
{
var tempTajSzamok = Encoding.ASCII.GetString(bytes).Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim("\",".ToCharArray())).ToList();
if (tempTajSzamok[0].Contains("TAJ"))
{
tempTajSzamok.RemoveAt(0);
}
tajSzamok.AddRange(tempTajSzamok);
}
public (int fertozott, int marNemFertozott) UpdateDB(IDalHandler h, int tanevId)
{
var tajszamokJson = JsonConvert.SerializeObject(tajSzamok.Distinct().ToArray());
var felhasznaloDal = h.Felhasznalo();
var ds = felhasznaloDal.UpdateFelhasznalokCovidAdatok(tanevId, tajszamokJson);
if ((ds.Tables.Count < 1)
|| (ds.Tables[0].Rows.Count < 1))
{
return (-1, -1);
}
var fertozott = ds.Tables[0].Rows[0].Field<int>("Fertozott");
var marNemFertozott = ds.Tables[0].Rows[0].Field<int>("MarNemFertozott");
return (fertozott, marNemFertozott);
}
}
}

View file

@ -0,0 +1 @@


View file

@ -0,0 +1,92 @@
using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Xml;
namespace Kreta.EESZTInterface.STS
{
partial class CreateSoap
{
public static XmlDocument CreateX509Soap(X509Certificate2 oamCert, X509Certificate2 cert)
{
XmlElement elem;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
string idBody = "Id-" + Guid.NewGuid().ToString().Replace("-", "");
string idTs = "TS-" + Guid.NewGuid().ToString().Replace("-", "");
string idX509 = "X509-" + Guid.NewGuid().ToString().Replace("-", "");
string idOamCert = "OAM-" + Guid.NewGuid().ToString().Replace("-", "");
XmlElement root = xmlDoc.CreateElement("soap", "Envelope", Namespaces.soap12Ns);
root.SetAttribute("xmlns:ns", Namespaces.nsNs);
xmlDoc.AppendChild(root);
XmlElement head = xmlDoc.CreateElement("soap", "Header", Namespaces.soap12Ns);
root.AppendChild(head);
XmlElement sec = xmlDoc.CreateElement("wsse", "Security", Namespaces.wsseNs);
sec.SetAttribute("xmlns:wsu", Namespaces.wsuNs);
head.AppendChild(sec);
XmlElement binary = xmlDoc.CreateElement("wsse", "BinarySecurityToken", Namespaces.wsseNs);
binary.SetAttribute("Id", Namespaces.wsuNs, idOamCert);
binary.SetAttribute("ValueType", STSValues.x509v3Value);
binary.SetAttribute("EncodingType", STSValues.base64BinaryValue);
binary.InnerText = CertificateHelper.CertToBase64String(oamCert);
sec.AppendChild(binary);
binary = xmlDoc.CreateElement("wsse", "BinarySecurityToken", Namespaces.wsseNs);
binary.SetAttribute("Id", Namespaces.wsuNs, idX509);
binary.SetAttribute("ValueType", STSValues.x509v3Value);
binary.SetAttribute("EncodingType", STSValues.base64BinaryValue);
binary.InnerText = CertificateHelper.CertToBase64String(cert);
sec.AppendChild(binary);
XmlElement timestamp = xmlDoc.CreateElement("wsu", "Timestamp", Namespaces.wsuNs);
timestamp.SetAttribute("Id", Namespaces.wsuNs, idTs);
sec.AppendChild(timestamp);
elem = xmlDoc.CreateElement("wsu", "Created", Namespaces.wsuNs);
elem.InnerText = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ");
timestamp.AppendChild(elem);
elem = xmlDoc.CreateElement("wsu", "Expires", Namespaces.wsuNs);
elem.InnerText = DateTime.Now.AddHours(2).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ");
timestamp.AppendChild(elem);
XmlElement body = xmlDoc.CreateElement("soap", "Body", Namespaces.soap12Ns);
body.SetAttribute("xmlns:wsu", Namespaces.wsuNs);
body.SetAttribute("Id", Namespaces.wsuNs, idBody);
xmlDoc.DocumentElement.AppendChild(body);
XmlElement secToken = xmlDoc.CreateElement("ns", "RequestSecurityToken", Namespaces.nsNs);
body.AppendChild(secToken);
elem = xmlDoc.CreateElement("ns", "RequestType", Namespaces.nsNs);
elem.InnerText = STSValues.issueValue;
secToken.AppendChild(elem);
elem = xmlDoc.CreateElement("ns", "TokenType", Namespaces.nsNs);
elem.InnerText = STSValues.samlv2Value;
secToken.AppendChild(elem);
var mem = new MemoryStream();
xmlDoc.Save(mem);
mem.Seek(0, SeekOrigin.Begin);
xmlDoc = new XmlDocument
{
PreserveWhitespace = true
};
xmlDoc.Load(mem);
xmlDoc = SignHelper.SignMessage(xmlDoc, cert, "#" + idBody, "#" + idTs, "#" + idX509);
xmlDoc = EncryptHelper.EncryptMessage(xmlDoc, oamCert, "#" + idBody, "#" + idTs, "#" + idOamCert);
return xmlDoc;
}
}
}

View file

@ -0,0 +1,131 @@
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Xml;
using Kreta.Resources;
namespace Kreta.EESZTInterface.STS
{
public class DoRequest
{
public static XmlDocument GetSoapSamlResponse(string stsUri, X509Certificate2 sslAuthCert, XmlDocument soapSamlRequest)
{
try
{
HttpWebRequest request = GetHttpWebRequest(stsUri, sslAuthCert);
var response = WriteToHttpStream(request, soapSamlRequest);
var soapResponse = ThrowIfSoapFault(response, stsUri);
return soapResponse;
}
catch (WebException wex)
{
string exMessage = wex.Message;
if (wex.Response != null)
{
using (var responseReader = new StreamReader(wex.Response.GetResponseStream()))
{
exMessage = responseReader.ReadToEnd();
ThrowIfSoapFault(exMessage, wex.Response.ResponseUri.OriginalString);
}
}
throw new Exception(exMessage, wex);
}
catch
{
throw;
}
}
private static HttpWebRequest GetHttpWebRequest(string stsUri, X509Certificate2 sslAuthCert)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(stsUri);
request.Headers.Add("SOAPAction", STSValues.soapActionValue);
request.ContentType = "application/soap+xml;charset=\"utf-8\"";
request.Accept = "application/soap+xml";
request.Method = "POST";
request.ClientCertificates.Add(sslAuthCert);
return request;
}
private static string WriteToHttpStream(HttpWebRequest request, XmlDocument samlRequest)
{
var outputStream = new MemoryStream();
samlRequest.Save(outputStream);
request.ContentLength = outputStream.Length;
outputStream.Seek(0, SeekOrigin.Begin);
var outStr = outputStream.ToArray();
outputStream.Close();
using (Stream requestStream = request.GetRequestStream())
{
using (StreamWriter stmw = new StreamWriter(requestStream))
{
requestStream.Write(outStr, 0, outStr.Length);
}
}
string responseString = string.Empty;
WebResponse response = request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
responseString = sr.ReadToEnd();
}
return responseString;
}
private static XmlDocument ThrowIfSoapFault(string response, string responseUri)
{
XmlDocument soapMessage = null;
try
{
soapMessage = ExtractDocumentFromResponse(response);
if (soapMessage == null)
{
throw new Exception();
}
}
catch (Exception ex)
{
throw new Exception(string.Format(EESZTInterfaceResource.NemMegfeleloSOAPValaszFormatum, responseUri, response), ex);
}
XmlElement fault = XmlHelper.GetElement("Fault", Namespaces.soap12Ns, soapMessage.DocumentElement);
if (fault == null)
{
return soapMessage;
}
var faultCodeNodes = XmlHelper.GetElement("Code", Namespaces.soap12Ns, fault);
var faultReasonNodes = XmlHelper.GetElement("Reason", Namespaces.soap12Ns, fault);
var exceptionDetailNodes = XmlHelper.GetElement("Detail", Namespaces.soap12Ns, fault);
throw new Exception("Hiba! Kód:" + faultCodeNodes.InnerText + " Részletek:" + faultReasonNodes.InnerText,
new Exception((exceptionDetailNodes == null) ? "" : exceptionDetailNodes.InnerText));
}
private static XmlDocument ExtractDocumentFromResponse(string response)
{
var soapResponse = new XmlDocument();
soapResponse.PreserveWhitespace = true;
soapResponse.LoadXml(response);
return soapResponse;
}
private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
}
}

View file

@ -0,0 +1,237 @@

using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Xml;
using Kreta.Resources;
namespace Kreta.EESZTInterface.STS
{
class EncryptHelper
{
public static RSA TransportKey { get; set; }
private static SymmetricAlgorithm _sessionKey;
private static string _sessionKeyAlgorithm = EncryptedXml.XmlEncAES128Url;
private static SymmetricAlgorithm SessionKey
{
get
{
if (_sessionKey == null)
{
_sessionKey = GetKeyInstance(_sessionKeyAlgorithm);
_sessionKey.GenerateKey();
}
return _sessionKey;
}
}
public static string SessionKeyAlgorithm
{
get { return _sessionKeyAlgorithm; }
set
{
// Validate that the URI used to identify the algorithm of the session key is probably correct. Not a complete validation, but should catch most obvious mistakes.
if (!value.StartsWith(Namespaces.xencNs))
{
throw new ArgumentException(EESZTInterfaceResource.SessionKeyAlgorithmMustBeSpecified);
}
_sessionKeyAlgorithm = value;
}
}
public static XmlDocument EncryptMessage(XmlDocument mySoap, X509Certificate2 oamcert, string IdBody, string IdTs,
string idOamCert)
{
string encKId = "EK-" + Guid.NewGuid().ToString().Replace("-", "");
string encDId = "ED-" + Guid.NewGuid().ToString().Replace("-", "");
// Create a symmetric key.
SessionKeyAlgorithm = EncryptedXml.XmlEncAES128Url;
TransportKey = (RSA)oamcert.PublicKey.Key;
var encryptedData = new EncryptedData
{
Type = EncryptedXml.XmlEncElementContentUrl,
EncryptionMethod = new EncryptionMethod(_sessionKeyAlgorithm),
Id = encDId
};
var body = XmlHelper.GetElement(XmlHelper.BodyElementName, Namespaces.soap12Ns, mySoap.DocumentElement);
var requestSecurityToken = XmlHelper.GetElement(XmlHelper.RequestSecurityTokenElementName, Namespaces.nsNs, body);
var encryptedXml = new EncryptedXml();
var encryptedElement = encryptedXml.EncryptData(requestSecurityToken, SessionKey, false);
encryptedData.CipherData.CipherValue = encryptedElement;
encryptedData.KeyInfo = new KeyInfo();
var encryptedKey = new EncryptedKey
{
EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSAOAEPUrl),
CipherData = new CipherData(EncryptedXml.EncryptKey(SessionKey.Key, TransportKey, true)),
Id = encKId
};
var kInfo = new KeyInfo();
kInfo.Id = "KI-" + Guid.NewGuid().ToString().Replace("-", "");
XmlElement securityTokenReference = mySoap.CreateElement("wsse", "SecurityTokenReference", Namespaces.wsseNs);
securityTokenReference.SetAttribute("Id", Namespaces.wsuNs, "STR-" + Guid.NewGuid().ToString().Replace("-", ""));
XmlElement reference = mySoap.CreateElement("wsse", "Reference", Namespaces.wsseNs);
reference.SetAttribute("ValueType", STSValues.x509v3Value);
reference.SetAttribute("URI", idOamCert);
securityTokenReference.AppendChild(reference);
KeyInfoNode kInfoNode = new KeyInfoNode();
kInfoNode.Value = securityTokenReference;
kInfo.AddClause(kInfoNode);
encryptedKey.KeyInfo = kInfo;
DataReference dRef = new DataReference();
dRef.Uri = "#" + encDId;
encryptedKey.AddReference(dRef);
var headerSec = XmlHelper.GetElement(XmlHelper.SecurityElementName, Namespaces.wsseNs, mySoap.DocumentElement);
var enc = encryptedKey.GetXml();
XmlElement encKeyElement = headerSec.OwnerDocument.ImportNode(encryptedKey.GetXml(), true) as XmlElement;
SetEncPrefix(encKeyElement);
headerSec.InsertAfter(encKeyElement, XmlHelper.GetElementId(mySoap, idOamCert.Replace("#", "")));
kInfo = new KeyInfo();
securityTokenReference = mySoap.CreateElement("wsse", "SecurityTokenReference", Namespaces.wsseNs);
securityTokenReference.SetAttribute("xmlns:wsse11", Namespaces.wsse11Ns);
securityTokenReference.SetAttribute("TokenType", Namespaces.wsse11Ns, STSValues.encryptedKeyValue);
reference = mySoap.CreateElement("wsse", "Reference", Namespaces.wsseNs);
reference.SetAttribute("URI", "#" + encKId);
securityTokenReference.AppendChild(reference);
kInfoNode = new KeyInfoNode();
kInfoNode.Value = securityTokenReference;
kInfo.AddClause(kInfoNode);
encryptedData.KeyInfo = kInfo;
EncryptedXml.ReplaceElement(body, encryptedData, true);
SetEncPrefix(body);
return mySoap;
}
public static XmlDocument DecryptMessageAll(XmlDocument mySoap, X509Certificate2 userCert)
{
RSA publicKeyRSA = userCert.PrivateKey as RSA;
TransportKey = publicKeyRSA;
var bodyElement = XmlHelper.GetElement(XmlHelper.BodyElementName, Namespaces.soap12Ns, mySoap.DocumentElement);
var encryptedDataElement = XmlHelper.GetElement(XmlHelper.EncryptedDataElementName, Namespaces.xencNs, bodyElement);
var securityElement = XmlHelper.GetElement(XmlHelper.SecurityElementName, Namespaces.wsseNs, mySoap.DocumentElement);
var encryptedData = new EncryptedData();
encryptedData.LoadXml(encryptedDataElement);
string _sessionKeyAlgorithm;
SymmetricAlgorithm sessionKey;
if (encryptedData.EncryptionMethod != null)
{
_sessionKeyAlgorithm = encryptedData.EncryptionMethod.KeyAlgorithm;
sessionKey = ExtractSessionKey(securityElement, encryptedDataElement, _sessionKeyAlgorithm);
}
else
{
sessionKey = ExtractSessionKey(securityElement, encryptedDataElement, string.Empty);
}
var encryptedXml = new EncryptedXml(mySoap);
encryptedXml.ReplaceData(encryptedDataElement, encryptedXml.DecryptData(encryptedData, sessionKey));
return mySoap;
}
private static SymmetricAlgorithm ExtractSessionKey(XmlElement securityElement, XmlElement encryptedData, string keyAlgorithm)
{
// Check if there are any <EncryptedKey> elements immediately below the EncryptedAssertion element.
foreach (XmlNode node in securityElement.ChildNodes)
{
if (node.LocalName == XmlHelper.EncryptedKeyElementName && node.NamespaceURI == Namespaces.xencNs)
{
return ToSymmetricKey((XmlElement)node, keyAlgorithm);
}
}
// Check if the key is embedded in the <EncryptedData> element.
if (encryptedData != null)
{
var encryptedKeyElement = XmlHelper.GetElement(XmlHelper.EncryptedKeyElementName, Namespaces.xencNs, encryptedData);
if (encryptedKeyElement != null)
{
return ToSymmetricKey(encryptedKeyElement, keyAlgorithm);
}
}
throw new Exception(EESZTInterfaceResource.EncryptedKeyNemTalalhato);
}
private static SymmetricAlgorithm ToSymmetricKey(XmlElement encryptedKeyElement, string keyAlgorithm)
{
var encryptedKey = new EncryptedKey();
encryptedKey.LoadXml(encryptedKeyElement);
var useOaep = true;
if (encryptedKey.EncryptionMethod != null)
{
useOaep = encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl;
}
if (encryptedKey.CipherData.CipherValue != null)
{
var key = GetKeyInstance(keyAlgorithm);
key.Key = EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, TransportKey, useOaep);
return key;
}
throw new NotImplementedException(EESZTInterfaceResource.UnableToDecodeCipherData);
}
private static SymmetricAlgorithm GetKeyInstance(string algorithm)
{
SymmetricAlgorithm result;
switch (algorithm)
{
case EncryptedXml.XmlEncTripleDESUrl:
result = TripleDES.Create();
break;
case EncryptedXml.XmlEncAES128Url:
result = new RijndaelManaged { KeySize = 128 };
break;
case EncryptedXml.XmlEncAES192Url:
result = new RijndaelManaged { KeySize = 192 };
break;
case EncryptedXml.XmlEncAES256Url:
default:
result = new RijndaelManaged { KeySize = 256 };
break;
}
return result;
}
private static void SetEncPrefix(XmlElement encKeyElement)
{
foreach (XmlNode xnode in encKeyElement.SelectNodes($"descendant-or-self::*[namespace-uri()='{Namespaces.dsNs}']"))
{
xnode.Prefix = "ds";
}
foreach (XmlNode xnode in encKeyElement.SelectNodes($"descendant-or-self::*[namespace-uri()='{Namespaces.xencNs}']"))
{
xnode.Prefix = "xenc";
}
}
}
}

View file

@ -0,0 +1,320 @@
using System;
using System.Collections;
using System.Reflection;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Xml;
using Kreta.Resources;
namespace Kreta.EESZTInterface.STS
{
class PrefixedSignedXML : SignedXml
{
private string signatureValueId;
public PrefixedSignedXML(XmlDocument document)
: base(document)
{ }
public PrefixedSignedXML(XmlElement element)
: base(element)
{ }
public PrefixedSignedXML()
: base()
{ }
/// <summary>
/// Setting this property will add an ID attribute to the SignatureValue element.
/// This is required when constructing a XAdES-T signature.
/// </summary>
public string SignatureValueId
{
get
{
return this.signatureValueId;
}
set
{
this.signatureValueId = value;
}
}
public override XmlElement GetIdElement(XmlDocument doc, string id)
{
// check to see if it's a standard ID reference
XmlElement idElem = base.GetIdElement(doc, id);
if (idElem == null)
{
XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
nsManager.AddNamespace("wsu", Namespaces.wsuNs);
idElem = doc.SelectSingleNode("//*[@wsu:Id=\"" + id + "\"]", nsManager) as XmlElement;
}
return idElem;
}
/// <summary>
/// Copy of System.Security.Cryptography.Xml.SignedXml.ComputeSignature() which will end up calling
/// our own GetC14NDigest with a namespace prefix for all XmlDsig nodes
/// </summary>
public new void ComputeSignature()
{
this.BuildDigestedReferences();
AsymmetricAlgorithm signingKey = this.SigningKey;
if (signingKey == null)
{
throw new CryptographicException(EESZTInterfaceResource.CryptographyXmlLoadKeyFailed);
}
if (this.SignedInfo.SignatureMethod == null)
{
if (!(signingKey is DSA))
{
if (!(signingKey is RSA))
{
throw new CryptographicException(EESZTInterfaceResource.CryptographyXmlCreatedKeyFailed);
}
if (this.SignedInfo.SignatureMethod == null)
{
this.SignedInfo.SignatureMethod = STSValues.signatureMethodRSAValue;
}
}
else
{
this.SignedInfo.SignatureMethod = STSValues.signatureMethodDSAValue;
}
}
SignatureDescription description = CryptoConfig.CreateFromName(this.SignedInfo.SignatureMethod) as SignatureDescription;
if (description == null)
{
throw new CryptographicException(EESZTInterfaceResource.CryptographyXmlSignatureDescriptionNotCreated);
}
HashAlgorithm hash = description.CreateDigest();
if (hash == null)
{
throw new CryptographicException(EESZTInterfaceResource.CryptographyXmlCreateHashAlgorithmFailed);
}
//this.GetC14NDigest(hash);
this.GetC14NDigest(hash, "ds");
//
this.m_signature.SignatureValue = description.CreateFormatter(signingKey).CreateSignature(hash);
}
/// <summary>
/// Returns the XML representation of the this object
/// </summary>
/// <returns>XML element containing the state of this object</returns>
public new XmlElement GetXml()
{
XmlElement retVal;
XmlNodeList xmlNodeList;
XmlNamespaceManager xmlNamespaceManager;
retVal = base.GetXml();
if (this.signatureValueId != null && this.signatureValueId != "")
{ //Id on Signature value is needed for XAdES-T. We inject it here.
xmlNamespaceManager = new XmlNamespaceManager(retVal.OwnerDocument.NameTable);
xmlNamespaceManager.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
xmlNodeList = retVal.SelectNodes("ds:SignatureValue", xmlNamespaceManager);
if (xmlNodeList.Count > 0)
{
((XmlElement)xmlNodeList[0]).SetAttribute("Id", this.signatureValueId);
}
}
// Add "ds" namespace prefix to all XmlDsig nodes in the signature
SetPrefix("ds", retVal);
return retVal;
}
/// <summary>
/// Copy of System.Security.Cryptography.Xml.SignedXml.BuildDigestedReferences() which will add a "ds"
/// namespace prefix to all XmlDsig nodes
/// </summary>
private void BuildDigestedReferences()
{
ArrayList references = this.SignedInfo.References;
//this.m_refProcessed = new bool[references.Count];
Type SignedXml_Type = typeof(SignedXml);
FieldInfo SignedXml_m_refProcessed = SignedXml_Type.GetField("m_refProcessed", BindingFlags.NonPublic | BindingFlags.Instance);
SignedXml_m_refProcessed.SetValue(this, new bool[references.Count]);
//
//this.m_refLevelCache = new int[references.Count];
FieldInfo SignedXml_m_refLevelCache = SignedXml_Type.GetField("m_refLevelCache", BindingFlags.NonPublic | BindingFlags.Instance);
SignedXml_m_refLevelCache.SetValue(this, new int[references.Count]);
//
//ReferenceLevelSortOrder comparer = new ReferenceLevelSortOrder();
Assembly System_Security_Assembly = Assembly.Load("System.Security, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
Type ReferenceLevelSortOrder_Type = System_Security_Assembly.GetType("System.Security.Cryptography.Xml.SignedXml+ReferenceLevelSortOrder");
ConstructorInfo ReferenceLevelSortOrder_Constructor = ReferenceLevelSortOrder_Type.GetConstructor(new Type[] { });
Object comparer = ReferenceLevelSortOrder_Constructor.Invoke(null);
//
//comparer.References = references;
PropertyInfo ReferenceLevelSortOrder_References = ReferenceLevelSortOrder_Type.GetProperty("References", BindingFlags.Public | BindingFlags.Instance);
ReferenceLevelSortOrder_References.SetValue(comparer, references, null);
//
ArrayList list2 = new ArrayList();
foreach (Reference reference in references)
{
list2.Add(reference);
}
list2.Sort((IComparer)comparer);
//CanonicalXmlNodeList refList = new CanonicalXmlNodeList();
Type CanonicalXmlNodeList_Type = System_Security_Assembly.GetType("System.Security.Cryptography.Xml.CanonicalXmlNodeList");
ConstructorInfo CanonicalXmlNodeList_Constructor = CanonicalXmlNodeList_Type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { }, null);
Object refList = CanonicalXmlNodeList_Constructor.Invoke(null);
//
//
MethodInfo CanonicalXmlNodeList_Add = CanonicalXmlNodeList_Type.GetMethod("Add", BindingFlags.Public | BindingFlags.Instance);
//
foreach (DataObject obj2 in this.m_signature.ObjectList)
{
//refList.Add(obj2.GetXml());
XmlElement xml = obj2.GetXml();
SetPrefix("ds", xml); // <---
CanonicalXmlNodeList_Add.Invoke(refList, new object[] { xml });
//
}
//
FieldInfo SignedXml_m_containingDocument = SignedXml_Type.GetField("m_containingDocument", BindingFlags.NonPublic | BindingFlags.Instance);
Type Reference_Type = typeof(Reference);
MethodInfo Reference_UpdateHashValue = Reference_Type.GetMethod("UpdateHashValue", BindingFlags.NonPublic | BindingFlags.Instance);
//
foreach (Reference reference2 in list2)
{
if (reference2.DigestMethod == null)
{
reference2.DigestMethod = STSValues.digestMethodSHA1Value;
}
//reference2.UpdateHashValue(this.m_containingDocument, refList);
object m_containingDocument = SignedXml_m_containingDocument.GetValue(this);
Reference_UpdateHashValue.Invoke(reference2, new object[] { m_containingDocument, refList });
//
if (reference2.Id != null)
{
//refList.Add(reference2.GetXml());
XmlElement xml = reference2.GetXml();
SetPrefix("ds", xml); // <---
CanonicalXmlNodeList_Add.Invoke(refList, new object[] { xml });
//
}
}
}
/// <summary>
/// Copy of System.Security.Cryptography.Xml.SignedXml.GetC14NDigest() which will add a
/// namespace prefix to all XmlDsig nodes
/// </summary>
private byte[] GetC14NDigest(HashAlgorithm hash, string prefix)
{
//if (!this.bCacheValid || !this.SignedInfo.CacheValid)
//{
Type SignedXml_Type = typeof(SignedXml);
FieldInfo SignedXml_bCacheValid = SignedXml_Type.GetField("bCacheValid", BindingFlags.NonPublic | BindingFlags.Instance);
bool bCacheValid = (bool)SignedXml_bCacheValid.GetValue(this);
Type SignedInfo_Type = typeof(SignedInfo);
PropertyInfo SignedInfo_CacheValid = SignedInfo_Type.GetProperty("CacheValid", BindingFlags.NonPublic | BindingFlags.Instance);
bool CacheValid = (bool)SignedInfo_CacheValid.GetValue(this.SignedInfo, null);
FieldInfo SignedXml__digestedSignedInfo = SignedXml_Type.GetField("_digestedSignedInfo", BindingFlags.NonPublic | BindingFlags.Instance);
if (!bCacheValid || !CacheValid)
{
//
//string securityUrl = (this.m_containingDocument == null) ? null : this.m_containingDocument.BaseURI;
FieldInfo SignedXml_m_containingDocument = SignedXml_Type.GetField("m_containingDocument", BindingFlags.NonPublic | BindingFlags.Instance);
XmlDocument m_containingDocument = (XmlDocument)SignedXml_m_containingDocument.GetValue(this);
string securityUrl = m_containingDocument?.BaseURI;
//
//XmlResolver xmlResolver = this.m_bResolverSet ? this.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl);
FieldInfo SignedXml_m_bResolverSet = SignedXml_Type.GetField("m_bResolverSet", BindingFlags.NonPublic | BindingFlags.Instance);
bool m_bResolverSet = (bool)SignedXml_m_bResolverSet.GetValue(this);
FieldInfo SignedXml_m_xmlResolver = SignedXml_Type.GetField("m_xmlResolver", BindingFlags.NonPublic | BindingFlags.Instance);
XmlResolver m_xmlResolver = (XmlResolver)SignedXml_m_xmlResolver.GetValue(this);
XmlResolver xmlResolver = m_bResolverSet ? m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl);
//
//XmlDocument document = Utils.PreProcessElementInput(this.SignedInfo.GetXml(), xmlResolver, securityUrl);
Assembly System_Security_Assembly = Assembly.Load("System.Security, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
Type Utils_Type = System_Security_Assembly.GetType("System.Security.Cryptography.Xml.Utils");
MethodInfo Utils_PreProcessElementInput = Utils_Type.GetMethod("PreProcessElementInput", BindingFlags.NonPublic | BindingFlags.Static);
XmlElement xml = this.SignedInfo.GetXml();
SetPrefix(prefix, xml); // <---
XmlDocument document = (XmlDocument)Utils_PreProcessElementInput.Invoke(null, new object[] { xml, xmlResolver, securityUrl });
//
//CanonicalXmlNodeList namespaces = (this.m_context == null) ? null : Utils.GetPropagatedAttributes(this.m_context);
FieldInfo SignedXml_m_context = SignedXml_Type.GetField("m_context", BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo Utils_GetPropagatedAttributes = Utils_Type.GetMethod("GetPropagatedAttributes", BindingFlags.NonPublic | BindingFlags.Static);
object m_context = SignedXml_m_context.GetValue(this);
object namespaces = (m_context == null) ? null : Utils_GetPropagatedAttributes.Invoke(null, new object[] { m_context });
//
// Utils.AddNamespaces(document.DocumentElement, namespaces);
Type CanonicalXmlNodeList_Type = System_Security_Assembly.GetType("System.Security.Cryptography.Xml.CanonicalXmlNodeList");
MethodInfo Utils_AddNamespaces = Utils_Type.GetMethod("AddNamespaces", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeof(XmlElement), CanonicalXmlNodeList_Type }, null);
Utils_AddNamespaces.Invoke(null, new object[] { document.DocumentElement, namespaces });
//
//Transform canonicalizationMethodObject = this.SignedInfo.CanonicalizationMethodObject;
System.Security.Cryptography.Xml.Transform canonicalizationMethodObject = this.SignedInfo.CanonicalizationMethodObject;
//
canonicalizationMethodObject.Resolver = xmlResolver;
//canonicalizationMethodObject.BaseURI = securityUrl;
Type Transform_Type = typeof(System.Security.Cryptography.Xml.Transform);
PropertyInfo Transform_BaseURI = Transform_Type.GetProperty("BaseURI", BindingFlags.NonPublic | BindingFlags.Instance);
Transform_BaseURI.SetValue(canonicalizationMethodObject, securityUrl, null);
//
canonicalizationMethodObject.LoadInput(document);
//this._digestedSignedInfo = canonicalizationMethodObject.GetDigestedOutput(hash);
SignedXml__digestedSignedInfo.SetValue(this, canonicalizationMethodObject.GetDigestedOutput(hash));
//
//this.bCacheValid = true;
SignedXml_bCacheValid.SetValue(this, true);
//
}
//return this._digestedSignedInfo;
byte[] _digestedSignedInfo = (byte[])SignedXml__digestedSignedInfo.GetValue(this);
return _digestedSignedInfo;
//
}
private void SetPrefix(string prefix, XmlNode node)
{
foreach (XmlNode n in node.ChildNodes)
SetPrefix(prefix, n);
if (node.NamespaceURI == Namespaces.dsNs)
{
node.Prefix = prefix;
}
else if (node.NamespaceURI == Namespaces.c14nNs)
{
node.Prefix = "ec";
}
}
}
}

View file

@ -0,0 +1,16 @@
namespace Kreta.EESZTInterface.STS
{
public class STSValues
{
public const string x509v3Value = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3";
public const string base64BinaryValue = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary";
public const string issueValue = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue";
public const string samlv2Value = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0";
public const string finalActionValue = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTRC/IssueFinal";
public const string signatureMethodRSAValue = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
public const string signatureMethodDSAValue = "http://www.w3.org/2000/09/xmldsig#dsa-sha1";
public const string digestMethodSHA1Value = "http://www.w3.org/2000/09/xmldsig#sha1";
public const string encryptedKeyValue = "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey";
public const string soapActionValue = "\"http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue\"";
}
}

View file

@ -0,0 +1,39 @@
using System;
using System.Xml;
namespace Kreta.EESZTInterface.STS
{
public class SamlAssertion
{
public const string LocalName = "Assertion";
public string Id { get; }
public string Issuer { get; }
public string UserId { get; }
public string UserName { get; }
public DateTime NotBefore { get; }
public DateTime NotOnOrAfter { get; }
public XmlElement SamlAssertionElement { get; }
public string Original { get; }
public SamlAssertion(string content)
{
Original = content;
var xDoc = new XmlDocument();
xDoc.LoadXml(content);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xDoc.NameTable);
nsmgr.AddNamespace("saml", Namespaces.samlNs);
SamlAssertionElement = xDoc.DocumentElement;
Id = SamlAssertionElement.Attributes["ID"].Value;
Issuer = SamlAssertionElement.SelectSingleNode("descendant::saml:Issuer", nsmgr).InnerText;
UserId = SamlAssertionElement.SelectSingleNode("descendant::saml:NameID", nsmgr).InnerText;
UserName = SamlAssertionElement.SelectSingleNode("descendant::saml:Attribute[@Name=\"displayName\"]", nsmgr).InnerText;
var authStatementNode = SamlAssertionElement.SelectSingleNode("descendant::saml:Conditions", nsmgr);
NotBefore = DateTime.Parse(authStatementNode.Attributes["NotBefore"].Value).ToUniversalTime();
NotOnOrAfter = DateTime.Parse(authStatementNode.Attributes["NotOnOrAfter"].Value).ToUniversalTime();
}
}
}

View file

@ -0,0 +1,129 @@
using System;
using System.IO;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Xml;
using System.Xml.Serialization;
using Kreta.EESZTInterface.STS.Saml20;
using Kreta.Resources;
namespace Kreta.EESZTInterface.STS
{
public class SamlRequest
{
private readonly X509Certificate2 sslCert;
private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
public SamlRequest(X509Certificate2 sslCerrtificate)
{
sslCert = sslCerrtificate;
}
public string GetX509Saml(string interfaceUrl, X509Certificate2 stsCert, X509Certificate2 userCert)
{
var rst = CreateSoap.CreateX509Soap(stsCert, userCert);
rst = DoRequest.GetSoapSamlResponse($"{interfaceUrl}/STS_x509", sslCert, rst);
rst = DecryptFromRSTResponse(rst, stsCert, userCert);
return XmlToString(GetSamlFromRSTR(rst));
}
private string XmlToString(XmlDocument xmlDoc)
{
if (xmlDoc.FirstChild is XmlDeclaration)
{
xmlDoc.RemoveChild(xmlDoc.FirstChild);
}
return xmlDoc.OuterXml;
}
private XmlDocument GetSamlFromRSTR(XmlDocument rstResponse)
{
var actionElement = XmlHelper.GetElement("Action", Namespaces.addressingNs, rstResponse.DocumentElement);
if (!actionElement.InnerText.ToLower().Equals(STSValues.finalActionValue.ToLower()))
throw new Exception(EESZTInterfaceResource.NemMegfeleloActionErtek);
var deserializer = new XmlSerializer(typeof(AssertionType));
AssertionType assetion;
var body = XmlHelper.GetElement("Body", Namespaces.soap12Ns, rstResponse.DocumentElement);
var assertionElement = XmlHelper.GetElement("Assertion", Namespaces.samlNs, body);
if (assertionElement == null)
throw new Exception(EESZTInterfaceResource.AssertionElementNemTalalhato);
var saml = new XmlDocument
{
PreserveWhitespace = true
};
saml.LoadXml(assertionElement.OuterXml);
using (TextReader xmlreader = new StringReader(assertionElement.OuterXml))
{
try
{
assetion = (AssertionType)deserializer.Deserialize(xmlreader);
}
catch (Exception ex)
{
throw new Exception(EESZTInterfaceResource.AssertionElementNemMegfelelo, ex);
}
}
X509DataType x509dt;
X509Certificate2 samlCert = null;
foreach (var item in assetion.Signature.KeyInfo.Items)
{
if (item.GetType().Equals(typeof(X509DataType)))
{
x509dt = (X509DataType)item;
for (int i1 = 0; i1 < x509dt.ItemsElementName.Length; i1++)
{
if (x509dt.ItemsElementName[i1].Equals(ItemsChoiceType.X509Certificate))
{
samlCert = new X509Certificate2((byte[])x509dt.Items[i1]);
break;
}
}
}
if (samlCert != null)
{
break;
}
}
if (samlCert == null)
throw new Exception(EESZTInterfaceResource.SamlTanusitvanyNemTalalhato);
var samlXml = new XmlDocument
{
PreserveWhitespace = true
};
samlXml.LoadXml(assertionElement.OuterXml);
var valid = SignHelper.CheckSignature(samlXml, samlCert);
if (valid)
{
return saml;
}
throw new Exception(EESZTInterfaceResource.SamlAlairasaErvenytelen);
}
private XmlDocument DecryptFromRSTResponse(XmlDocument rstResponse, X509Certificate2 stsCert, X509Certificate2 userCert)
{
rstResponse = EncryptHelper.DecryptMessageAll(rstResponse, userCert);
if (SignHelper.CheckSignature(rstResponse, stsCert))
{
return rstResponse;
}
throw new Exception(EESZTInterfaceResource.RSTRalairasaErvenytelen);
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,81 @@
using System;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Xml;
namespace Kreta.EESZTInterface.STS
{
class SignHelper
{
public static XmlDocument SignMessage(XmlDocument mySoap, X509Certificate2 cert, string IdBody, string IdTs, string idX509)
{
PrefixedSignedXML signedXml = new PrefixedSignedXML(mySoap);
signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
signedXml.SigningKey = cert.GetRSAPrivateKey();
signedXml.Signature.Id = "SIG-" + Guid.NewGuid().ToString().Replace("-", "");
var kInfo = new KeyInfo();
kInfo.Id = "KI-" + Guid.NewGuid().ToString().Replace("-", "");
XmlElement securityTokenReference = mySoap.CreateElement("wsse", "SecurityTokenReference", Namespaces.wsseNs);
securityTokenReference.SetAttribute("Id", Namespaces.wsuNs, "STR-" + Guid.NewGuid().ToString().Replace("-", ""));
XmlElement reference = mySoap.CreateElement("wsse", "Reference", Namespaces.wsseNs);
reference.SetAttribute("ValueType", STSValues.x509v3Value);
reference.SetAttribute("URI", idX509);
securityTokenReference.AppendChild(reference);
KeyInfoNode kInfoNode = new KeyInfoNode();
kInfoNode.Value = securityTokenReference;
kInfo.AddClause(kInfoNode);
signedXml.Signature.KeyInfo = kInfo;
XmlDsigExcC14NTransform canMethod = (XmlDsigExcC14NTransform)signedXml.SignedInfo.CanonicalizationMethodObject;
canMethod.InclusiveNamespacesPrefixList = "ns soap";
Reference tRef = new Reference() { DigestMethod = STSValues.digestMethodSHA1Value };
tRef.Uri = IdBody;
XmlDsigExcC14NTransform c14n = new XmlDsigExcC14NTransform("ns");
tRef.AddTransform(c14n);
signedXml.AddReference(tRef);
tRef = new Reference() { DigestMethod = STSValues.digestMethodSHA1Value };
tRef.Uri = IdTs;
c14n = new XmlDsigExcC14NTransform("wsse ns soap");
tRef.AddTransform(c14n);
signedXml.AddReference(tRef);
tRef = new Reference() { DigestMethod = STSValues.digestMethodSHA1Value };
tRef.Uri = idX509;
c14n = new XmlDsigExcC14NTransform("");
tRef.AddTransform(c14n);
signedXml.AddReference(tRef);
signedXml.ComputeSignature();
var ret = signedXml.CheckSignature(cert, true);
var xmlDsig = signedXml.GetXml();
XmlElement SecElement = XmlHelper.GetElement(XmlHelper.SecurityElementName, Namespaces.wsseNs, mySoap.DocumentElement);
SecElement.InsertAfter(mySoap.ImportNode(xmlDsig, true), XmlHelper.GetElementId(mySoap, idX509.Replace("#", "")));
if (mySoap.FirstChild is XmlDeclaration)
{
mySoap.RemoveChild(mySoap.FirstChild);
}
return mySoap;
}
public static bool CheckSignature(XmlDocument mySoap, X509Certificate2 cert)
{
var signedXml = new PrefixedSignedXML(mySoap);
var nodeList = XmlHelper.GetElement(XmlHelper.SignatureElementName, Namespaces.dsNs, mySoap.DocumentElement);
signedXml.LoadXml(nodeList);
return signedXml.CheckSignature(cert, true);
}
}
}

View file

@ -0,0 +1,18 @@
using Kreta.EESZTInterface.STS;
namespace Kreta.EESZTInterface
{
public class STSHelper
{
public SamlAssertion GetSamlAssertion(string interfaceUrl)
{
var sslCert = CertificateHelper.GetSslCertificate();
var samlRequest = new SamlRequest(sslCert);
var stsCert = CertificateHelper.GetSTSCertificate();
var userCert = CertificateHelper.GetUserCertificate();
var result = samlRequest.GetX509Saml(interfaceUrl, stsCert, userCert);
return new SamlAssertion(result);
}
}
}

View file

@ -0,0 +1,36 @@
using System.Xml;
namespace Kreta.EESZTInterface
{
public class XmlHelper
{
public const string EncryptedDataElementName = "EncryptedData";
public const string EncryptedKeyElementName = "EncryptedKey";
public const string SecurityElementName = "Security";
public const string RequestSecurityTokenElementName = "RequestSecurityToken";
public const string HeaderElementName = "Header";
public const string BodyElementName = "Body";
public const string SignatureElementName = "Signature";
public static XmlElement GetElement(string element, string elementNS, XmlElement doc)
{
var list = doc.GetElementsByTagName(element, elementNS);
return list.Count == 0 ? null : (XmlElement)list[0];
}
public static XmlElement GetElementId(XmlDocument doc, string id)
{
XmlElement idElem = null;
if (idElem == null)
{
XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
nsManager.AddNamespace("wsu", Namespaces.wsuNs);
idElem = doc.SelectSingleNode("//*[@wsu:Id=\"" + id + "\"]", nsManager) as XmlElement;
}
return idElem;
}
}
}

View file

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.6.0" newVersion="5.2.6.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

View file

@ -0,0 +1,162 @@
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using Kreta.EESZTInterface.eFT.Model;
using Kreta.EESZTInterface.eFT.Model.AllomanyResz.Request;
using Kreta.EESZTInterface.eFT.Model.IntezmenyiAllomanyLista.Request;
using Kreta.EESZTInterface.eFT.Model.SikeresCimzettAllomanyLetoltes.Request;
using Kreta.EESZTInterface.STS;
namespace Kreta.EESZTInterface.eFT
{
public class CreateSoap
{
private static string CreateSoapRequest<T>(string samlContent, T bo)
{
string idTs = "TS-" + Guid.NewGuid().ToString().Replace("-", "");
var xDoc = new XmlDocument();
XmlElement root = xDoc.CreateElement("soap", "Envelope", Namespaces.soap11Ns);
root.SetAttribute("xmlns:v1", Namespaces.allomanyPublikaloServiceV1Ns);
xDoc.AppendChild(root);
XmlElement head = xDoc.CreateElement("soap", "Header", Namespaces.soap11Ns);
root.AppendChild(head);
XmlElement sec = xDoc.CreateElement("wsse", "Security", Namespaces.wsseNs);
sec.SetAttribute("xmlns:wsu", Namespaces.wsuNs);
sec.SetAttribute("soap:mustUnderstand", "1");
head.AppendChild(sec);
XmlElement timestamp = xDoc.CreateElement("wsu", "Timestamp", Namespaces.wsuNs);
timestamp.SetAttribute("Id", Namespaces.wsuNs, idTs);
sec.AppendChild(timestamp);
XmlElement created = xDoc.CreateElement("wsu", "Created", Namespaces.wsuNs);
var now = DateTime.Now;
created.InnerText = now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ");
timestamp.AppendChild(created);
XmlElement expires = xDoc.CreateElement("wsu", "Expires", Namespaces.wsuNs);
expires.InnerText = now.ToUniversalTime().AddMinutes(5).ToString("yyyy-MM-ddTHH:mm:ssZ");
timestamp.AppendChild(expires);
sec.InnerXml += "{saml}";
XmlElement body = xDoc.CreateElement("soap", "Body", Namespaces.soap11Ns);
var ns = new XmlSerializerNamespaces();
ns.Add("v1", Namespaces.allomanyPublikaloServiceV1Ns);
var serializer = new XmlSerializer(typeof(T));
var sb = new StringBuilder();
var writer = new StringWriter(sb);
serializer.Serialize(writer, bo, ns);
writer.Close();
XmlDocument b = new XmlDocument();
b.LoadXml(sb.Replace(typeof(T).Name, $"v1:{typeof(T).Name}").ToString());
XmlElement boXml = (XmlElement)xDoc.ImportNode(b.DocumentElement, true);
boXml.Attributes.RemoveNamedItem("xmlns:v1");
body.AppendChild(boXml);
xDoc.DocumentElement.AppendChild(body);
return xDoc.DocumentElement.OuterXml.Replace("{saml}", samlContent);
}
public static string CreateGetIntezmenyiAllomanyLista(string samlContent, GetIntezmenyiAllomanyLista bo)
{
return CreateSoapRequest(samlContent, bo);
}
public static string CreateGetAllomanyresz(string samlContent, GetAllomanyResz bo)
{
return CreateSoapRequest(samlContent, bo);
}
public static string CreateSikeresLetoltes(string samlContent, SikeresCimzettAllomanyLetoltes bo)
{
return CreateSoapRequest(samlContent, bo);
}
private static BusinessMessageHeader GetBusinessMessageHeader(SamlAssertion samlAssertion, string clientUserId, string organizationId)
{
var applicationVersion = "1.0";
var applicationName = "eKreta";
return new BusinessMessageHeader
{
Initiator = new Initiator
{
UserId = samlAssertion.UserId,
UserName = samlAssertion.UserName,
ClientUserId = clientUserId,
ApplicationName = applicationName,
ApplicationId = $"{applicationName}:{applicationVersion}",
ApplicationFunction = "teszt",
OrganizationId = organizationId,
},
RepresentedUser = new RepresentedUser
{
ClientUserId = clientUserId,
UserId = samlAssertion.UserId,
UserName = samlAssertion.UserName,
},
Logging = new Logging
{
SubmittedAt = DateTime.Now,
}
};
}
public static GetIntezmenyiAllomanyLista GetIntezmenyiAllomanyListaBusinessObject(SamlAssertion samlAssertion, string clientUserId, string organizationId)
{
return new GetIntezmenyiAllomanyLista
{
IntezmenyiAllomanyListaRequest = new IntezmenyiAllomanyListaRequest
{
BusinessMessageHeader = GetBusinessMessageHeader(samlAssertion, clientUserId, organizationId),
IntezmenyiAllomanyListaRequestBusinessContent = new IntezmenyiAllomanyListaRequestBusinessContent
{
CimzettId = organizationId,
}
}
};
}
public static GetAllomanyResz GetAllomanyReszBusinessObject(SamlAssertion samlAssertion, string clientUserId, string organizationId, Guid publikusId, int sorszam)
{
return new GetAllomanyResz
{
AllomanyReszRequest = new AllomanyReszRequest
{
BusinessMessageHeader = GetBusinessMessageHeader(samlAssertion, clientUserId, organizationId),
AllomanyReszRequestBusinessContent = new AllomanyReszRequestBusinessContent
{
AllomanyPublikusId = publikusId,
AllomanyReszSorszam = sorszam,
CimzettId = organizationId,
}
}
};
}
public static SikeresCimzettAllomanyLetoltes GetSikeresCimzettAllomanyLetoltesBO(SamlAssertion samlAssertion, string clientUserId, string organizationId, Guid publikusId)
{
return new SikeresCimzettAllomanyLetoltes
{
SikeresAllomanyLetoltesRequest = new SikeresAllomanyLetoltesRequest
{
BusinessMessageHeader = GetBusinessMessageHeader(samlAssertion, clientUserId, organizationId),
SikeresAllomanyLetoltesRequestBusinessContent = new SikeresAllomanyLetoltesRequestBusinessContent
{
AllomanyPublikusId = publikusId,
CimzettId = organizationId,
}
}
};
}
}
}

View file

@ -0,0 +1,187 @@
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
using Kreta.EESZTInterface.STS;
using Kreta.Resources;
namespace Kreta.EESZTInterface.eFT
{
public class DoRequest
{
public static (XmlDocument soapResponse, byte[] mTOMAttachment) GetSoapSamlResponse(string eftUri, X509Certificate2 sslAuthCert, string soapRequest, SamlAssertion samlAssertion)
{
try
{
HttpWebRequest request = GetHttpWebRequest(eftUri, sslAuthCert, samlAssertion);
var (data, hasAttachment) = WriteToHttpStream(request, soapRequest);
var msResp = new MemoryStream(data);
StreamReader sr = new StreamReader(msResp);
var responseString = sr.ReadToEnd();
if (!hasAttachment)
{
var soapResponse = ThrowIfSoapFault(responseString);
return (soapResponse, null);
}
else
{
var xmlEleje = responseString.IndexOf("<?xml");
var xmlVege = responseString.IndexOf("\r\n--MIME_Boundary");
responseString = responseString.Substring(xmlEleje, xmlVege - xmlEleje);
var soapResponse = ThrowIfSoapFault(responseString);
byte[] boundary1 = Encoding.UTF8.GetBytes("org>" + "\r\n\r\n");
byte[] boundary2 = Encoding.UTF8.GetBytes("\r\n--" + "MIME_Boundary" + "--\r\n");
var attachment = GetAttachmentData(data, boundary1, boundary2);
return (soapResponse, attachment);
}
}
catch (WebException wex)
{
string exMessage = wex.Message;
if (wex.Response != null)
{
using (var responseReader = new StreamReader(wex.Response.GetResponseStream()))
{
exMessage = responseReader.ReadToEnd();
ThrowIfSoapFault(exMessage);
}
}
throw new Exception(exMessage, wex);
}
catch
{
throw;
}
}
private static HttpWebRequest GetHttpWebRequest(string stsUri, X509Certificate2 sslAuthCert, SamlAssertion samlAssertion = null)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(stsUri);
request.Headers.Add("SOAPAction", "");
request.ContentType = "application/soap+xml;charset=\"utf-8\"";
request.Accept = "application/soap+xml";
request.Method = "POST";
request.ClientCertificates.Add(sslAuthCert);
return request;
}
private static (byte[] data, bool hasAttachment) WriteToHttpStream(HttpWebRequest request, string soapRequest)
{
using (Stream stream = request.GetRequestStream())
{
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(soapRequest));
ms.WriteTo(stream);
}
WebResponse response = request.GetResponse();
MemoryStream msResp = new MemoryStream();
int read;
byte[] buffer = new byte[1024];
while ((read = response.GetResponseStream().Read(buffer, 0, buffer.Length)) > 0)
{
msResp.Write(buffer, 0, read);
}
return (data: msResp.ToArray(), hasAttachment: response.ContentType.Contains("multipart"));
}
private static byte[] GetAttachmentData(byte[] data, byte[] boundary1, byte[] boundary2)
{
if (data == null || boundary1 == null || boundary2 == null)
return null;
if (boundary1.LongLength > data.LongLength)
return null;
long i, j, startIndex;
bool match;
int boundary1Pos = 0;
for (i = 0; i < data.LongLength; i++)
{
startIndex = i;
match = true;
for (j = 0; j < boundary1.LongLength; j++)
{
if (data[startIndex] != boundary1[j])
{
match = false;
break;
}
if (startIndex < data.LongLength)
{
startIndex++;
}
}
if (match)
boundary1Pos = Convert.ToInt32(startIndex - boundary1.LongLength);
}
int pos1 = boundary1Pos + boundary1.Length;
int pos2 = data.Length - boundary2.Length;
int length = pos2 - pos1;
try
{
byte[] output = new byte[length];
Array.Copy(data, pos1, output, 0, length);
return output;
}
catch { }
return null;
}
private static XmlDocument ThrowIfSoapFault(string response)
{
XmlDocument soapMessage;
try
{
soapMessage = ExtractDocumentFromResponse(response);
if (soapMessage == null)
{
throw new Exception();
}
}
catch (Exception ex)
{
throw new Exception(EESZTInterfaceResource.NemMegfeleloSOAPValaszFormatum, ex);
}
XmlElement fault = XmlHelper.GetElement("Fault", Namespaces.soap11Ns, soapMessage.DocumentElement);
if (fault == null)
{
return soapMessage;
}
var faultCodeNodes = XmlHelper.GetElement("faultcode", "", fault);
var faultReasonNodes = XmlHelper.GetElement("faultstring", "", fault);
var exceptionDetailNodes = XmlHelper.GetElement("detail", "", fault);
throw new Exception("Hiba! Kód:" + faultCodeNodes.InnerText + " Részletek:" + faultReasonNodes.InnerText,
new Exception((exceptionDetailNodes == null) ? "" : exceptionDetailNodes.InnerText));
}
private static XmlDocument ExtractDocumentFromResponse(string response)
{
var soapResponse = new XmlDocument();
soapResponse.PreserveWhitespace = true;
soapResponse.LoadXml(response);
return soapResponse;
}
private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
}
}

View file

@ -0,0 +1,10 @@
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.AllomanyResz.Request
{
public class AllomanyReszRequest : EftRequest
{
[XmlElement(ElementName = "allomanyReszRequestBusinessContent", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public AllomanyReszRequestBusinessContent AllomanyReszRequestBusinessContent { get; set; }
}
}

View file

@ -0,0 +1,15 @@
using System;
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.AllomanyResz.Request
{
public class AllomanyReszRequestBusinessContent
{
[XmlElement(ElementName = "allomanyPublikusId", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public Guid AllomanyPublikusId { get; set; }
[XmlElement(ElementName = "cimzettId", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string CimzettId { get; set; }
[XmlElement(ElementName = "allomanyReszSorszam", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public int AllomanyReszSorszam { get; set; }
}
}

View file

@ -0,0 +1,13 @@
using System;
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.AllomanyResz.Request
{
[Serializable]
[XmlRoot(ElementName = "getAllomanyResz", Namespace = Namespaces.allomanyPublikaloServiceV1Ns)]
public class GetAllomanyResz
{
[XmlElement(ElementName = "allomanyReszRequest", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public AllomanyReszRequest AllomanyReszRequest { get; set; }
}
}

View file

@ -0,0 +1,10 @@
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.AllomanyResz.Response
{
public class Adat
{
[XmlElement(ElementName = "Include", Namespace = Namespaces.xopNS)]
public Include Include { get; set; }
}
}

View file

@ -0,0 +1,20 @@
using System;
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.AllomanyResz.Response
{
public class AllomanyResz
{
[XmlElement(ElementName = "publikusId", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public Guid PublikusId { get; set; }
[XmlElement(ElementName = "sorszam", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public int Sorszam { get; set; }
[XmlElement(ElementName = "adat", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public Adat Adat { get; set; }
[XmlElement(ElementName = "hash", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Hash { get; set; }
[XmlElement(ElementName = "meretByte", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public int MeretByte { get; set; }
}
}

View file

@ -0,0 +1,11 @@
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.AllomanyResz.Response
{
public class AllomanyReszResponse : EftResponse
{
[XmlElement(ElementName = "allomanyReszResponseBusinessContent", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public AllomanyReszResponseBusinessContent AllomanyReszResponseBusinessContent { get; set; }
}
}

View file

@ -0,0 +1,10 @@
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.AllomanyResz.Response
{
public class AllomanyReszResponseBusinessContent
{
[XmlElement(ElementName = "allomanyResz", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public AllomanyResz AllomanyResz { get; set; }
}
}

View file

@ -0,0 +1,14 @@
using System;
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.AllomanyResz.Response
{
[Serializable]
[XmlRoot(ElementName = "getAllomanyReszResponse", Namespace = Namespaces.allomanyPublikaloServiceV1Ns)]
public class GetAllomanyReszResponse
{
[XmlElement(ElementName = "allomanyReszResponse", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public AllomanyReszResponse AllomanyReszResponse { get; set; }
}
}

View file

@ -0,0 +1,12 @@
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.AllomanyResz.Response
{
[XmlType(TypeName = "Include", Namespace = Namespaces.xopNS)]
public class Include
{
[XmlAttribute(AttributeName = "href", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Href { get; set; }
}
}

View file

@ -0,0 +1,14 @@
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model
{
public class BusinessMessageHeader
{
[XmlElement(ElementName = "initiator", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public Initiator Initiator { get; set; }
[XmlElement(ElementName = "representedUser", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public RepresentedUser RepresentedUser { get; set; }
[XmlElement(ElementName = "logging", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public Logging Logging { get; set; }
}
}

View file

@ -0,0 +1,10 @@
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model
{
public abstract class EftRequest
{
[XmlElement(ElementName = "businessMessageHeader", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public BusinessMessageHeader BusinessMessageHeader { get; set; }
}
}

View file

@ -0,0 +1,12 @@
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model
{
public abstract class EftResponse
{
[XmlElement(ElementName = "businessMessageHeader", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public BusinessMessageHeader BusinessMessageHeader { get; set; }
[XmlElement(ElementName = "status", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Status { get; set; }
}
}

View file

@ -0,0 +1,24 @@
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model
{
public class Initiator
{
[XmlElement(ElementName = "userId", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string UserId { get; set; }
[XmlElement(ElementName = "userName", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string UserName { get; set; }
[XmlElement(ElementName = "clientUserId", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string ClientUserId { get; set; }
[XmlElement(ElementName = "applicationId", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string ApplicationId { get; set; }
[XmlElement(ElementName = "applicationName", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string ApplicationName { get; set; }
[XmlElement(ElementName = "applicationFunction", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string ApplicationFunction { get; set; }
[XmlElement(ElementName = "organizationId", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string OrganizationId { get; set; }
[XmlElement(ElementName = "organizationUnitId", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string OrganizationUnitId { get; set; }
}
}

View file

@ -0,0 +1,13 @@
using System;
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.IntezmenyiAllomanyLista.Request
{
[Serializable]
[XmlRoot(ElementName = "getIntezmenyiAllomanyLista", Namespace = Namespaces.allomanyPublikaloServiceV1Ns)]
public class GetIntezmenyiAllomanyLista
{
[XmlElement(ElementName = "intezmenyiAllomanyListaRequest", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public IntezmenyiAllomanyListaRequest IntezmenyiAllomanyListaRequest { get; set; }
}
}

View file

@ -0,0 +1,10 @@
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.IntezmenyiAllomanyLista.Request
{
public class IntezmenyiAllomanyListaRequest : EftRequest
{
[XmlElement(ElementName = "intezmenyiAllomanyListaRequestBusinessContent", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public IntezmenyiAllomanyListaRequestBusinessContent IntezmenyiAllomanyListaRequestBusinessContent { get; set; }
}
}

View file

@ -0,0 +1,10 @@
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.IntezmenyiAllomanyLista.Request
{
public class IntezmenyiAllomanyListaRequestBusinessContent
{
[XmlElement(ElementName = "cimzettId", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string CimzettId { get; set; }
}
}

View file

@ -0,0 +1,39 @@
using System;
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.IntezmenyiAllomanyLista.Response
{
public class Allomany
{
[XmlElement(ElementName = "id", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public int Id { get; set; }
[XmlElement(ElementName = "publikusId", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public Guid PublikusId { get; set; }
[XmlElement(ElementName = "allomanyTipus", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public AllomanyTipus AllomanyTipus { get; set; }
[XmlElement(ElementName = "nev", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Nev { get; set; }
[XmlElement(ElementName = "kiterjesztes", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Kiterjesztes { get; set; }
[XmlElement(ElementName = "bekuldoModulUser", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string BekuldoModulUser { get; set; }
[XmlElement(ElementName = "datum", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public DateTime Datum { get; set; }
[XmlElement(ElementName = "meretMb", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public int MeretMb { get; set; }
[XmlElement(ElementName = "leiras", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Leiras { get; set; }
[XmlElement(ElementName = "tomoritett", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public bool Tomoritett { get; set; }
[XmlElement(ElementName = "binaris", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public bool Binaris { get; set; }
[XmlElement(ElementName = "statusz", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Statusz { get; set; }
[XmlElement(ElementName = "darabszam", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public int Darabszam { get; set; }
[XmlElement(ElementName = "ervenyesseg", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public DateTime Ervenyesseg { get; set; }
[XmlElement(ElementName = "hash", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Hash { get; set; }
}
}

View file

@ -0,0 +1,14 @@
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.IntezmenyiAllomanyLista.Response
{
public class AllomanyTipus
{
[XmlElement(ElementName = "id", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public int Id { get; set; }
[XmlElement(ElementName = "nev", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Nev { get; set; }
[XmlElement(ElementName = "leiras", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Leiras { get; set; }
}
}

View file

@ -0,0 +1,13 @@
using System;
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.IntezmenyiAllomanyLista.Response
{
[Serializable]
[XmlRoot(ElementName = "getIntezmenyiAllomanyListaResponse", Namespace = Namespaces.allomanyPublikaloServiceV1Ns)]
public class GetIntezmenyiAllomanyListaResponse
{
[XmlElement(ElementName = "intezmenyiAllomanyListaResponse", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public IntezmenyiAllomanyListaResponse IntezmenyiAllomanyListaResponse { get; set; }
}
}

View file

@ -0,0 +1,10 @@
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.IntezmenyiAllomanyLista.Response
{
public class IntezmenyiAllomanyListaResponse : EftResponse
{
[XmlElement(ElementName = "intezmenyiAllomanyListaResponseBusinessContent", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public IntezmenyiAllomanyListaResponseBusinessContent IntezmenyiAllomanyListaResponseBusinessContent { get; set; }
}
}

View file

@ -0,0 +1,12 @@
using System.Collections.Generic;
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.IntezmenyiAllomanyLista.Response
{
public class IntezmenyiAllomanyListaResponseBusinessContent
{
[XmlArray(ElementName = "allomanyok", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
[XmlArrayItem(ElementName = "allomany", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public List<Allomany> Allomanyok { get; set; }
}
}

View file

@ -0,0 +1,24 @@
using System;
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model
{
public class Logging
{
[XmlIgnore]
public DateTime SubmittedAt { get; set; }
[XmlElement(ElementName = "submittedAt", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string SubmittedAtStr
{
get
{
return SubmittedAt.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ");
}
set
{
SubmittedAt = DateTime.Parse(value);
}
}
}
}

View file

@ -0,0 +1,14 @@
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model
{
public class RepresentedUser
{
[XmlElement(ElementName = "userId", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string UserId { get; set; }
[XmlElement(ElementName = "userName", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string UserName { get; set; }
[XmlElement(ElementName = "clientUserId", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string ClientUserId { get; set; }
}
}

View file

@ -0,0 +1,11 @@
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.SikeresCimzettAllomanyLetoltes.Request
{
public class SikeresAllomanyLetoltesRequest : EftRequest
{
[XmlElement(ElementName = "sikeresAllomanyLetoltesRequestBusinessContent", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public SikeresAllomanyLetoltesRequestBusinessContent SikeresAllomanyLetoltesRequestBusinessContent { get; set; }
}
}

View file

@ -0,0 +1,14 @@
using System;
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.SikeresCimzettAllomanyLetoltes.Request
{
public class SikeresAllomanyLetoltesRequestBusinessContent
{
[XmlElement(ElementName = "allomanyPublikusId", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public Guid AllomanyPublikusId { get; set; }
[XmlElement(ElementName = "cimzettId", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string CimzettId { get; set; }
}
}

View file

@ -0,0 +1,13 @@
using System;
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.SikeresCimzettAllomanyLetoltes.Request
{
[Serializable]
[XmlRoot(ElementName = "sikeresCimzettAllomanyLetoltes", Namespace = Namespaces.allomanyPublikaloServiceV1Ns)]
public class SikeresCimzettAllomanyLetoltes
{
[XmlElement(ElementName = "sikeresAllomanyLetoltesRequest", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public SikeresAllomanyLetoltesRequest SikeresAllomanyLetoltesRequest { get; set; }
}
}

View file

@ -0,0 +1,10 @@
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.SikeresCimzettAllomanyLetoltes.Response
{
public class SikeresAllomanyLetoltesResponse : EftResponse
{
[XmlElement(ElementName = "sikeresAllomanyLetoltesResponseBusinessContent", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string SikeresAllomanyLetoltesResponseBusinessContent { get; set; } = null;
}
}

View file

@ -0,0 +1,13 @@
using System;
using System.Xml.Serialization;
namespace Kreta.EESZTInterface.eFT.Model.SikeresCimzettAllomanyLetoltes.Response
{
[Serializable]
[XmlRoot(ElementName = "sikeresCimzettAllomanyLetoltesResponse", Namespace = Namespaces.allomanyPublikaloServiceV1Ns)]
public class SikeresCimzettAllomanyLetoltesResponse
{
[XmlElement(ElementName = "sikeresAllomanyLetoltesResponse", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public SikeresAllomanyLetoltesResponse SikeresAllomanyLetoltesResponse { get; set; }
}
}

View file

@ -0,0 +1,90 @@
using System;
using System.IO;
using System.IO.Compression;
using System.Security.Cryptography;
using System.Xml;
using System.Xml.Serialization;
using Kreta.EESZTInterface.eFT.Model.AllomanyResz.Response;
using Kreta.EESZTInterface.eFT.Model.IntezmenyiAllomanyLista.Response;
using Kreta.EESZTInterface.eFT.Model.SikeresCimzettAllomanyLetoltes.Response;
using Kreta.EESZTInterface.STS;
namespace Kreta.EESZTInterface
{
public class EFTHelper
{
private readonly string eftUrl;
public EFTHelper(string eftUrl)
{
this.eftUrl = $"{eftUrl}/EFT/AllomanyPublikalo";
}
public GetIntezmenyiAllomanyListaResponse CallIntezmenyAllomanyLista(SamlAssertion samlAssertion, string clientUserId, string organizationId)
{
var bo = eFT.CreateSoap.GetIntezmenyiAllomanyListaBusinessObject(samlAssertion, clientUserId, organizationId);
var xDoc = eFT.CreateSoap.CreateGetIntezmenyiAllomanyLista(samlAssertion.Original, bo);
var (soapResponse, _) = eFT.DoRequest.GetSoapSamlResponse(eftUrl, CertificateHelper.GetSslCertificate(), xDoc, samlAssertion);
var resp = (XmlElement)(soapResponse.GetElementsByTagName("getIntezmenyiAllomanyListaResponse", Namespaces.allomanyPublikaloServiceV1Ns).Item(0));
return SerializeResponseContent<GetIntezmenyiAllomanyListaResponse>(resp);
}
public (GetAllomanyReszResponse response, byte[] attachment) CallAllomanyResz(SamlAssertion samlAssertion, string clientUserId, string organizationId, Guid publikusId, int sorszam)
{
var bo = eFT.CreateSoap.GetAllomanyReszBusinessObject(samlAssertion, clientUserId, organizationId, publikusId, sorszam);
var xDoc = eFT.CreateSoap.CreateGetAllomanyresz(samlAssertion.Original, bo);
var (soapResponse, mTOMAttachment) = eFT.DoRequest.GetSoapSamlResponse(eftUrl, CertificateHelper.GetSslCertificate(), xDoc, samlAssertion);
var resp = (XmlElement)(soapResponse.GetElementsByTagName("getAllomanyReszResponse", Namespaces.allomanyPublikaloServiceV1Ns).Item(0));
return (SerializeResponseContent<GetAllomanyReszResponse>(resp), mTOMAttachment);
}
public SikeresCimzettAllomanyLetoltesResponse CallSikeresAllomanyLetoltes(SamlAssertion samlAssertion, string clientUserId, string organizationId, Guid publikusId)
{
var bo = eFT.CreateSoap.GetSikeresCimzettAllomanyLetoltesBO(samlAssertion, clientUserId, organizationId, publikusId);
var xDoc = eFT.CreateSoap.CreateSikeresLetoltes(samlAssertion.Original, bo);
var (soapResponse, _) = eFT.DoRequest.GetSoapSamlResponse(eftUrl, CertificateHelper.GetSslCertificate(), xDoc, samlAssertion);
var resp = (XmlElement)(soapResponse.GetElementsByTagName("sikeresCimzettAllomanyLetoltesResponse", Namespaces.allomanyPublikaloServiceV1Ns).Item(0));
return SerializeResponseContent<SikeresCimzettAllomanyLetoltesResponse>(resp);
}
private T SerializeResponseContent<T>(XmlElement element)
{
var serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StringReader(element.OuterXml))
{
return (T)serializer.Deserialize(reader);
}
}
public static byte[] ComputeSha256Hash(byte[] reszadat)
{
using (var sha256Hash = SHA256.Create())
{
return sha256Hash.ComputeHash(reszadat);
}
}
public static byte[] Decompress(byte[] input)
{
using (var source = new MemoryStream(input))
{
byte[] lengthBytes = new byte[4];
source.Read(lengthBytes, 0, 4);
var length = BitConverter.ToInt32(lengthBytes, 0);
using (var decompressionStream = new GZipStream(source,
CompressionMode.Decompress))
{
var result = new byte[length];
decompressionStream.Read(result, 0, length);
return result;
}
}
}
}
}

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Meziantou.Analyzer" version="1.0.688" targetFramework="net48" developmentDependency="true" />
<package id="Newtonsoft.Json" version="12.0.3" targetFramework="net48" />
</packages>