Ejemplo n.º 1
0
        private SOAPEnvelope <SAMLRequestBody> BuildEIDSamlRequest(string pin)
        {
            SOAPEnvelope <SAMLRequestBody> samlEnv = null;
            var orgAuthCertificate = _keyStoreManager.GetOrgAuthCertificate();

            using (var discovery = new BeIDCardDiscovery())
            {
                var readers = discovery.GetReaders();
                using (var connection = discovery.Connect(readers.First()))
                {
                    var certificate       = connection.GetAuthCertificate();
                    var idAuthCertificate = new MedikitCertificate(new X509Certificate2(connection.GetAuthCertificate().Export(X509ContentType.Cert)), null);
                    samlEnv = BuildRequest(idAuthCertificate, orgAuthCertificate, (_ =>
                    {
                        byte[] hashPayload = null;
                        using (var sha = new SHA1CryptoServiceProvider())
                        {
                            hashPayload = sha.ComputeHash(_);
                        }

                        return(connection.SignWithAuthenticationCertificate(hashPayload, BeIDDigest.Sha1, pin));
                    }));
                }
            }

            return(samlEnv);
        }
Ejemplo n.º 2
0
        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));
        }
Ejemplo n.º 3
0
        public async Task FindAmpp(DICSFindAmppRequest request)
        {
            var issueInstant = DateTime.UtcNow;

            request.IssueInstant = issueInstant;
            var orgAuthCertificate = _keyStoreManager.GetOrgAuthCertificate();
            var soapRequest        = SOAPRequestBuilder <DICSFindAmppRequestBody> .New(new DICSFindAmppRequestBody
            {
                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:findAmpp");

            var xml = await httpResult.Content.ReadAsStringAsync();

            httpResult.EnsureSuccessStatusCode();
        }
Ejemplo n.º 4
0
        public async Task <SOAPEnvelope <EHealthBoxGetInfoResponseBody> > GetBoxInfo(EHealthBoxGetInfoRequest request, SAMLAssertion assertion)
        {
            var issueInstant   = DateTime.UtcNow;
            var orgCertificate = _keyStoreManager.GetOrgAuthCertificate();
            var soapRequest    = SOAPRequestBuilder <EHealthBoxGetInfoRequestBody> .New(new EHealthBoxGetInfoRequestBody
            {
                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:getBoxInfo");

            var xml = await httpResult.Content.ReadAsStringAsync();

            httpResult.EnsureSuccessStatusCode();
            var result = SOAPEnvelope <EHealthBoxGetInfoResponseBody> .Deserialize(xml);

            return(result);
        }
Ejemplo n.º 5
0
        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>()
            });
        }
Ejemplo n.º 6
0
        public async Task <string> Handle(AddPharmaceuticalPrescriptionCommand command, CancellationToken token)
        {
            SAMLAssertion assertion;
            var           medicalfile = await _medicalfileQueryRepository.Get(command.MedicalfileId, token);

            if (medicalfile == null)
            {
                throw new UnknownPatientException(command.MedicalfileId, string.Format(Global.UnknownMedicalFile, command.MedicalfileId));
            }

            try
            {
                assertion = SAMLAssertion.Deserialize(command.AssertionToken);
            }
            catch
            {
                throw new BadAssertionTokenException(Global.BadAssertionToken);
            }

            var createDateTime = DateTime.UtcNow;

            if (command.CreateDateTime != null)
            {
                createDateTime = command.CreateDateTime.Value;
            }

            var niss       = assertion.AttributeStatement.Attribute.First(_ => _.AttributeNamespace == EHealth.Constants.AttributeStatementNamespaces.Identification).AttributeValue;
            var profession = assertion.AttributeStatement.Attribute.First(_ => _.AttributeNamespace == EHealth.Constants.AttributeStatementNamespaces.Certified).AttributeName;
            var cbe        = _keyStoreManager.GetOrgAuthCertificate().Certificate.ExtractCBE();
            var msgType    = new KmehrMessageBuilder()
                             .AddSender((_) =>
            {
                _.AddHealthCareParty((_) =>
                {
                    _.AddOrganization(cbe, "application", _options.ProductName);
                });
                _.AddHealthCareParty((_) =>
                {
                    _.AddPerson(niss, MAPPING_CLAIM_TO_HCPARTY[profession], string.Empty, string.Empty);
                });
            })
                             .AddRecipient((_) =>
            {
                _.AddHealthCareParty((s) =>
                {
                    s.AddOrganization("RECIPE", "orgpublichealth", "Recip-e");
                });
            })
                             .AddFolder("1", (_) =>
            {
                _.New(medicalfile.PatientNiss, medicalfile.PatientLastname, new string[] { medicalfile.PatientFirstname });
            }, (_) =>
            {
                _.AddTransaction((tr) =>
                {
                    tr.NewPharmaceuticalPrescriptionTransaction("1", createDateTime, true, true, command.ExpirationDateTime)
                    .AddAuthor(niss, MAPPING_CLAIM_TO_HCPARTY[profession], string.Empty, string.Empty)
                    .AddTransactionHeading((h) =>
                    {
                        h.NewPrescriptionHeading("1");
                        foreach (var pharmaPrescription in command.Medications)
                        {
                            h.AddMedicationTransactionItem((ti) =>
                            {
                                ti.SetMedicinalProduct(pharmaPrescription.PackageCode, string.Empty);
                                if (pharmaPrescription.Posology.Type.Code == PosologyTypes.FreeText.Code)
                                {
                                    var freeText = pharmaPrescription.Posology as AddPosologyFreeTextCommand;
                                    ti.SetPosologyFreeText(freeText.Content, DEFAULT_LANGUAGE);
                                }
                                else
                                {
                                    // TODO : MANAGE STRUCTURED POSOLOGY.
                                }

                                if (pharmaPrescription.BeginMoment != null)
                                {
                                    ti.SetBeginMoment(pharmaPrescription.BeginMoment.Value);
                                }

                                if (!string.IsNullOrWhiteSpace(pharmaPrescription.InstructionForPatient))
                                {
                                    ti.SetInstructionForPatient(pharmaPrescription.InstructionForPatient, DEFAULT_LANGUAGE);
                                }

                                if (!string.IsNullOrWhiteSpace(pharmaPrescription.InstructionForReimbursement))
                                {
                                    ti.SetInstructionForReimbursement(pharmaPrescription.InstructionForReimbursement, DEFAULT_LANGUAGE);
                                }
                            });
                        }
                    });
                });
            })
                             .Build(createDateTime);
            var result = await _recipeService.CreatePrescription(Enum.GetName(typeof(PrescriptionTypes), command.PrescriptionType), medicalfile.PatientNiss, command.ExpirationDateTime.Value, msgType, assertion);

            return(result.RID);
        }
Ejemplo n.º 7
0
        public Task <ETKModel> GetOrgETK()
        {
            var cbe = _keyStoreManager.GetOrgAuthCertificate().Certificate.ExtractCBE();

            return(GetETK(_options.OrgType, cbe));
        }