public async Task <KGSSGetKeyResponseContent> GetKeyFromKGSS(string keyId, SAMLAssertion assertion) { var orgAuthCertificate = _keyStoreManager.GetOrgAuthCertificate(); var orgEtk = await _etkService.GetOrgETK(); var kgssEtk = await _etkService.GetKgssETK(); var getKeyRequestContent = new KGSSGetKeyRequestContent { KeyIdentifier = keyId, ETK = orgEtk.ETK }; var contentInfoPayload = Encoding.UTF8.GetBytes(getKeyRequestContent.Serialize().ToString()); var sealedContentInfoPayload = TripleWrapper.Seal(contentInfoPayload, orgAuthCertificate, kgssEtk.Certificate); var issueInstant = DateTime.UtcNow; var soapRequest = SOAPRequestBuilder <KGSSGetKeyRequestBody> .New(new KGSSGetKeyRequestBody { Id = $"id-{Guid.NewGuid().ToString()}", Request = new KGSSGetKeyRequest { SealedKeyRequest = new KGSSSealedKeyRequest { SealedContent = Convert.ToBase64String(sealedContentInfoPayload) } } }) .AddTimestamp(issueInstant, issueInstant.AddHours(1)) .AddSAMLAssertion(assertion) .AddReferenceToSAMLAssertion() .SignWithCertificate(orgAuthCertificate) .Build(); var result = await _soapClient.Send(soapRequest, new Uri(_options.KgssUrl), null); result.EnsureSuccessStatusCode(); var xml = await result.Content.ReadAsStringAsync(); var response = SOAPEnvelope <KGSSGetKeyResponseBody> .Deserialize(xml); var certificates = new List <X509Certificate2> { orgAuthCertificate.Certificate, _keyStoreManager.GetOrgETKCertificate().Certificate }; var unsealedPayload = TripleWrapper.Unseal(Convert.FromBase64String(response.Body.GetKeyResponse.SealedKeyResponse.SealedContent), certificates.ToCertificateCollection()); return(KGSSGetKeyResponseContent.Deserialize(unsealedPayload)); }
public async Task FindCNK(CIVICSFindCNKRequest request) { var issueInstant = DateTime.UtcNow; request.IssueInstant = issueInstant; var orgAuthCertificate = _keyStoreManager.GetOrgAuthCertificate(); var soapRequest = SOAPRequestBuilder <CIVICSFindCNKRequestBody> .New(new CIVICSFindCNKRequestBody { Id = $"id-{Guid.NewGuid().ToString()}", Request = request }) .AddTimestamp(issueInstant, issueInstant.AddHours(1)) .AddBinarySecurityToken(orgAuthCertificate.Certificate) .AddReferenceToBinarySecurityToken() .SignWithCertificate(orgAuthCertificate) .Build(); var httpResult = await _soapClient.Send(soapRequest, new Uri(_options.CivicsUrl), "urn:be:fgov:ehealth:civics:protocol:v2:findCNK"); var xml = await httpResult.Content.ReadAsStringAsync(); // }
public async Task <SOAPEnvelope <EHealthBoxGetMessagesListResponseBody> > GetMessagesList(EHealthBoxGetMessagesListRequest request, SAMLAssertion assertion) { var issueInstant = DateTime.UtcNow; var orgCertificate = _keyStoreManager.GetOrgAuthCertificate(); var soapRequest = SOAPRequestBuilder <EHealthBoxGetMessagesListRequestBody> .New(new EHealthBoxGetMessagesListRequestBody { Id = $"id-{Guid.NewGuid().ToString()}", Request = request }) .AddTimestamp(issueInstant, issueInstant.AddHours(1)) .AddSAMLAssertion(assertion) .AddReferenceToSAMLAssertion() .SignWithCertificate(orgCertificate) .Build(); var httpResult = await _soapClient.Send(soapRequest, new Uri(_options.EHealthboxConsultation), "urn:be:fgov:ehealth:ehbox:consultation:protocol:v3:getMessagesList"); var xml = await httpResult.Content.ReadAsStringAsync(); httpResult.EnsureSuccessStatusCode(); var result = SOAPEnvelope <EHealthBoxGetMessagesListResponseBody> .Deserialize(xml); return(result); }
public async Task <SOAPEnvelope <DICSFindAmpResponseBody> > FindAmp(DICSFindAmpRequest request) { var issueInstant = DateTime.UtcNow; request.IssueInstant = issueInstant; var orgAuthCertificate = _keyStoreManager.GetOrgAuthCertificate(); var soapRequest = SOAPRequestBuilder <DICSFindAmpRequestBody> .New(new DICSFindAmpRequestBody { Id = $"id-{Guid.NewGuid().ToString()}", Request = request }) .AddTimestamp(issueInstant, issueInstant.AddHours(1)) .AddBinarySecurityToken(orgAuthCertificate.Certificate) .AddReferenceToBinarySecurityToken() .SignWithCertificate(orgAuthCertificate) .Build(); var httpResult = await _soapClient.Send(soapRequest, new Uri(_options.DicsUrl), "urn:be:fgov:ehealth:dics:protocol:v5:findAmp"); var xml = await httpResult.Content.ReadAsStringAsync(); httpResult.EnsureSuccessStatusCode(); return(SOAPEnvelope <DICSFindAmpResponseBody> .Deserialize(xml)); }
public async Task <GetPrescriptionResult> GetPrescription(string rid, SAMLAssertion assertion) { var orgCertificate = _keyStoreManager.GetOrgAuthCertificate(); var issueInstant = DateTime.UtcNow; var recipeETK = await _etkService.GetRecipeETK(); var symKey = new TripleDESCryptoServiceProvider { Padding = PaddingMode.None, Mode = CipherMode.ECB }; var getPrescriptionParameter = new GetPrescriptionForPrescriberParameter { Rid = rid, SymmKey = Convert.ToBase64String(symKey.Key) }; var serializedPrescriptionParameter = Encoding.UTF8.GetBytes(getPrescriptionParameter.Serialize().SerializeToString(false, true)); byte[] sealedContent = TripleWrapper.Seal(serializedPrescriptionParameter, orgCertificate, recipeETK.Certificate); var getPrescriptionRequest = new GetPrescriptionRequest { Id = $"id{Guid.NewGuid().ToString()}", IssueInstant = issueInstant, ProgramId = _options.ProductName, SecuredGetPrescriptionRequest = new SecuredContentType { SecuredContent = Convert.ToBase64String(sealedContent) } }; var soapRequest = SOAPRequestBuilder <GetPrescriptionRequestBody> .New(new GetPrescriptionRequestBody { Id = $"id-{Guid.NewGuid().ToString()}", Request = getPrescriptionRequest }) .AddTimestamp(issueInstant, issueInstant.AddHours(1)) .AddSAMLAssertion(assertion) .AddReferenceToSAMLAssertion() .SignWithCertificate(orgCertificate) .Build(); var result = await _soapClient.Send(soapRequest, new Uri(_options.PrescriberUrl), "urn:be:fgov:ehealth:recipe:protocol:v4:getPrescription"); var xml = await result.Content.ReadAsStringAsync(); result.EnsureSuccessStatusCode(); var response = SOAPEnvelope <GetPrescriptionResponseBody> .Deserialize(xml); var securedContent = response.Body.GetPrescriptionResponse.SecuredGetPrescriptionResponse.SecuredContent; byte[] decrypted; using (var decryptor = symKey.CreateDecryptor()) { var payload = Convert.FromBase64String(securedContent); decrypted = decryptor.TransformFinalBlock(payload, 0, payload.Length); } xml = Encoding.UTF8.GetString(decrypted).ClearBadFormat(); var prescriptionResult = GetPrescriptionForPrescriberResult.Deserialize(xml); var kgssResponse = await _kgssService.GetKeyFromKGSS(prescriptionResult.EncryptionKeyId, assertion); var unsealed = TripleWrapper.Unseal(Convert.FromBase64String(prescriptionResult.Prescription), Convert.FromBase64String(kgssResponse.NewKey)); var decompressed = Decompress(unsealed); return(new GetPrescriptionResult { Status = prescriptionResult.Status.Code, CreationDate = prescriptionResult.CreationDate, FeedbackAllowed = prescriptionResult.FeedbackAllowed, PatientId = prescriptionResult.PatientId, ExpirationDate = prescriptionResult.ExpirationDate, Rid = prescriptionResult.Rid, KmehrmessageType = Encoding.UTF8.GetString(decompressed).Deserialize <kmehrmessageType>() }); }
public async Task <ListRidsHistoryResult> GetHistoryPrescriptions(string patientId, Page page, SAMLAssertion assertion) { var orgCertificate = _keyStoreManager.GetOrgAuthCertificate(); var issueInstant = DateTime.UtcNow; var recipeETK = await _etkService.GetRecipeETK(); var symKey = new TripleDESCryptoServiceProvider(); symKey.Padding = PaddingMode.None; symKey.Mode = CipherMode.ECB; var listPrescriptionHistoryParameter = new ListPrescriptionHistoryParameter { PatientId = patientId, Page = page, SymmKey = Convert.ToBase64String(symKey.Key) }; var serializedPrescriptionParameter = Encoding.UTF8.GetBytes(listPrescriptionHistoryParameter.Serialize().SerializeToString(false, true)); byte[] sealedContent = TripleWrapper.Seal(serializedPrescriptionParameter, orgCertificate, recipeETK.Certificate); var listPrescriptionHistoryRequest = new ListPrescriptionHistoryRequest { Id = $"id{Guid.NewGuid().ToString()}", IssueInstant = issueInstant, ProgramId = _options.ProductName, SecuredListRidsHistoryRequest = new SecuredContentType { SecuredContent = Convert.ToBase64String(sealedContent) } }; var soapRequest = SOAPRequestBuilder <ListPrescriptionHistoryRequestBody> .New(new ListPrescriptionHistoryRequestBody { Id = $"id-{Guid.NewGuid().ToString()}", Request = listPrescriptionHistoryRequest }) .AddTimestamp(issueInstant, issueInstant.AddHours(1)) .AddSAMLAssertion(assertion) .AddReferenceToSAMLAssertion() .SignWithCertificate(orgCertificate) .Build(); var result = await _soapClient.Send(soapRequest, new Uri(_options.PrescriberUrl), "urn:be:fgov:ehealth:recipe:protocol:v4:listRidsHistory"); result.EnsureSuccessStatusCode(); var xml = await result.Content.ReadAsStringAsync(); var response = SOAPEnvelope <ListPrescriptionHistoryResponseBody> .Deserialize(xml); var securedContent = response.Body.ListPrescriptionHistoryResponse.SecuredListRidsHistoryResponse.SecuredContent; byte[] decrypted; using (var decryptor = symKey.CreateDecryptor()) { var payload = Convert.FromBase64String(securedContent); decrypted = decryptor.TransformFinalBlock(payload, 0, payload.Length); } xml = Encoding.UTF8.GetString(decrypted); xml = xml.ClearBadFormat(); var res = ListRidsHistoryResult.Deserialize(xml); return(res); }
public async Task <CreatePrescriptionResult> CreatePrescription(string prescriptionType, string patientId, DateTime expirationDateTime, kmehrmessageType msgType, SAMLAssertion assertion) { var orgCertificate = _keyStoreManager.GetOrgAuthCertificate(); var recipeETK = await _etkService.GetRecipeETK(); var kgssResponse = await _kgssService.GetKGSS(new System.Collections.Generic.List <CredentialType> { new CredentialType { Namespace = Constants.AttributeStatementNamespaces.Identification, Name = Constants.AttributeStatementNames.PersonSSIN, Value = assertion.AttributeStatement.Attribute.First(_ => _.AttributeNamespace == EHealth.Constants.AttributeStatementNamespaces.Identification).AttributeValue }, new CredentialType { Namespace = Constants.AttributeStatementNamespaces.Certified, Name = assertion.AttributeStatement.Attribute.First(_ => _.AttributeNamespace == EHealth.Constants.AttributeStatementNamespaces.Certified).AttributeName } }); var prescriptionPayload = msgType.SerializeToByte(false, true); var compressedPayload = Compress(prescriptionPayload); byte[] encryptedPayload; using (var aes = Aes.Create()) { aes.Padding = PaddingMode.PKCS7; aes.Mode = CipherMode.CBC; aes.KeySize = 128; aes.Key = Convert.FromBase64String(kgssResponse.NewKey); encryptedPayload = TripleWrapper.Seal(compressedPayload, orgCertificate, kgssResponse.NewKeyIdentifier, aes); } var symKey = new TripleDESCryptoServiceProvider { Padding = PaddingMode.None, Mode = CipherMode.ECB }; var prescriptionParameter = new CreatePrescriptionParameter { Prescription = Convert.ToBase64String(encryptedPayload), PrescriptionType = prescriptionType, FeedbackRequested = false, KeyId = kgssResponse.NewKeyIdentifier, SymmKey = Convert.ToBase64String(symKey.Key), PatientId = patientId, ExpirationDate = expirationDateTime.ToString("yyyy-MM-dd"), Vision = "" }; var serializedPrescriptionParameter = Encoding.UTF8.GetBytes(prescriptionParameter.Serialize().SerializeToString(false, true)); byte[] sealedContent = TripleWrapper.Seal(serializedPrescriptionParameter, orgCertificate, recipeETK.Certificate); var issueInstant = DateTime.UtcNow; var createPrescriptionRequest = new CreatePrescriptionRequest { IssueInstant = issueInstant, Id = $"id{Guid.NewGuid().ToString()}", ProgramId = "Medikit", AdministrativeInformation = new CreatePrescriptionAdministrativeInformationType { KeyIdentifier = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(kgssResponse.NewKeyIdentifier)), PrescriptionVersion = "kmehr_1.29", ReferenceSourceVersion = "samv2:ABCDE999999999999", PrescriptionType = prescriptionType }, SecuredCreatePrescriptionRequest = new SecuredContentType { SecuredContent = Convert.ToBase64String(sealedContent) } }; var soapRequest = SOAPRequestBuilder <CreatePrescriptionRequestBody> .New(new CreatePrescriptionRequestBody { Id = $"id-{Guid.NewGuid().ToString()}", Request = createPrescriptionRequest }) .AddTimestamp(issueInstant, issueInstant.AddHours(1)) .AddSAMLAssertion(assertion) .AddReferenceToSAMLAssertion() .SignWithCertificate(orgCertificate) .Build(); var result = await _soapClient.Send(soapRequest, new Uri(_options.PrescriberUrl), "urn:be:fgov:ehealth:recipe:protocol:v4:createPrescription"); var xml = await result.Content.ReadAsStringAsync(); result.EnsureSuccessStatusCode(); var response = SOAPEnvelope <CreatePrescriptionResponseBody> .Deserialize(xml); var securedContent = response.Body.CreatePrescriptionResponse.SecuredGetPrescriptionResponse.SecuredContent; byte[] decrypted; using (var decryptor = symKey.CreateDecryptor()) { var payload = Convert.FromBase64String(securedContent); decrypted = decryptor.TransformFinalBlock(payload, 0, payload.Length); } xml = Encoding.UTF8.GetString(decrypted); xml = xml.ClearBadFormat(); return(CreatePrescriptionResult.Deserialize(xml)); }
private SOAPEnvelope <SAMLRequestBody> BuildRequest(MedikitCertificate idAuthCertificate, MedikitCertificate orgAuthCertificate, Func <byte[], byte[]> signCallback) { var samlAttributes = new List <SAMLAttribute> { new SAMLAttribute { AttributeName = Constants.AttributeStatementNames.CertificateHolderPersonSSIN, AttributeNamespace = Constants.AttributeStatementNamespaces.Identification, AttributeValue = idAuthCertificate.Certificate.ExtractSSIN() }, new SAMLAttribute { AttributeName = Constants.AttributeStatementNames.PersonSSIN, AttributeNamespace = Constants.AttributeStatementNamespaces.Identification, AttributeValue = idAuthCertificate.Certificate.ExtractSSIN() }, new SAMLAttribute { AttributeName = _options.IdentityProfession.Code, AttributeNamespace = Constants.AttributeStatementNamespaces.Certified }, new SAMLAttribute { AttributeName = _options.IdentityProfession.CertificationAttribute, AttributeNamespace = Constants.AttributeStatementNamespaces.Certified } }; var issueInstant = DateTime.UtcNow; var majorVersion = 1; var minorVersion = 1; var bodyId = $"id-{Guid.NewGuid().ToString()}"; var requestId = $"request-{Guid.NewGuid().ToString()}"; var assertionId = $"assertion-{Guid.NewGuid().ToString()}"; var userSubject = FormatSubject(idAuthCertificate.Certificate.Subject); var issuerSubject = FormatSubject(idAuthCertificate.Certificate.Issuer); var nameIdentifier = new SAMLNameIdentifier { Format = "urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName", NameQualifier = issuerSubject, Content = userSubject }; var samlRequest = new SAMLRequest { MajorVersion = majorVersion, MinorVersion = minorVersion, RequestId = requestId, IssueInstant = issueInstant, AttributeQuery = new SAMLAttributeQuery { Subject = new SAMLSubject { NameIdentifier = nameIdentifier, SubjectConfirmation = new SAMLSubjectConfirmation { ConfirmationMethod = "urn:oasis:names:tc:SAML:1.0:cm:holder-of-key", SubjectConfirmationData = new SAMLSubjectConfirmationData { Assertion = new SAMLAssertion { IssueInstant = issueInstant, AssertionId = assertionId, Issuer = userSubject, MajorVersion = majorVersion, MinorVersion = minorVersion, Conditions = new SAMLConditions { NotBefore = issueInstant, NotOnOrAfter = issueInstant.AddDays(1) }, AttributeStatement = new SAMLAttributeStatement { Subject = new SAMLSubject { NameIdentifier = nameIdentifier }, Attribute = samlAttributes.Where(_ => !string.IsNullOrWhiteSpace(_.AttributeValue)).ToList() } } }, KeyInfo = new SOAPKeyInfo { X509Data = new SOAPX509Data { X509Certificate = Convert.ToBase64String(orgAuthCertificate.Certificate.Export(X509ContentType.Cert)) } } } }, AttributeDesignator = samlAttributes.Select(a => new SAMLAttributeDesignator { AttributeName = a.AttributeName, AttributeNamespace = a.AttributeNamespace }).ToList() } }; var samlRequestBody = new SAMLRequestBody { Id = bodyId, Request = samlRequest }; var signedInfo = CanonicalizeHelper.Canonicalize(samlRequestBody.Serialize().SerializeToString(), new List <string> { samlRequest.RequestId }, new List <Transform> { new XmlDsigEnvelopedSignatureTransform(), new XmlDsigExcC14NTransform() }); var payload = signedInfo.ComputeSignature(); var privateKey = (RSA)orgAuthCertificate.PrivateKey; var signaturePayload = privateKey.SignData(payload, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); var signatureStr = Convert.ToBase64String(signaturePayload); samlRequest.Signature = new SOAPSignature { KeyInfo = new SOAPKeyInfo { X509Data = new SOAPX509Data { X509Certificate = Convert.ToBase64String(orgAuthCertificate.Certificate.Export(X509ContentType.Cert)) } }, SignatureValue = signatureStr, SignedInfo = signedInfo }; return(SOAPRequestBuilder <SAMLRequestBody> .New(samlRequestBody) .AddTimestamp(issueInstant) .AddBinarySecurityToken(idAuthCertificate.Certificate) .AddReferenceToBinarySecurityToken() .SignWithCertificate(signCallback) .Build()); }