' Copyright (C) 2025  P4pillon.org
'
' This program is free software: you can redistribute it and/or modify
' it under the terms of the GNU Affero General Public License as
' published by the Free Software Foundation, either version 3 of the
' License, or (at your option) any later version.
'
' This program is distributed in the hope that it will be useful,
' but WITHOUT ANY WARRANTY; without even the implied warranty of
' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
' GNU Affero General Public License for more details.
'
' You should have received a copy of the GNU Affero General Public License
' along with this program.  If not, see <https://www.gnu.org/licenses/>.
Imports System.Xml
'Imports System.Security.Cryptography.Xml
Imports System.Security.Cryptography.X509Certificates
Imports System.Security.Cryptography
Imports System.IO
Imports System.Net.Sockets
Imports System.Net.Mime
Imports System.Net.Mail
Imports System.Text
Imports System.Security.Cryptography.Pkcs


Public Class LOI
#Region "Demande LOI"

    Public Function get_certif() As X509Certificate2
        Dim store As New X509Store(StoreLocation.CurrentUser)
        store.Open(OpenFlags.ReadOnly)
        Dim certCollection As X509Certificate2Collection = store.Certificates
        Dim certificate As X509Certificate2 = Nothing
        Dim c As X509Certificate2
        For Each c In certCollection
            'If c.HasPrivateKey Then
            If c.SerialNumber.ToString = Config.LOI_cert_nums Then
                certificate = c
                Exit For
            End If
            'End If
        Next c
        store.Close()
        Return certificate
    End Function

    Public Sub Demande_dLoi(ByVal Confirm_Message As Boolean)
        Try
            Dim enteteMIME As String = "Content-Type: text/plain" + Chr(10) + "Content-Transfer-Encoding: 7bit" + Chr(10) + Chr(10)

            Dim stringXML = "<?xml version=" + Chr(34) + "1.0" + Chr(34) + " encoding=" + Chr(34) + "UTF-8" + Chr(34) + "?>" + Chr(10) + _
            "<demande_dLOI>" + Chr(10) + _
            "<date_envoi>" + Format(Now, "dd/MM/yyyy") + "</date_envoi>" + Chr(10) + _
            "<heure_envoi>" + Format(Now, "hh:mm") + "</heure_envoi>" + Chr(10) + _
            "<ref_LOI>" + Config.LOI_Ref + "</ref_LOI>" + Chr(10) + _
            "<bal_LOI>" + Config.LOI_Pop3_BAL + "</bal_LOI>" + Chr(10) + _
            "<code_resultat_incr_prec>" + Config.LOI_code_resultat_incr_prec + "</code_resultat_incr_prec>" + Chr(10) + _
            "</demande_dLOI>"


            Dim stringXML_byte = Encoding.Default.GetBytes(stringXML)
            Dim base64stringXML = System.Convert.ToBase64String(stringXML_byte, Base64FormattingOptions.InsertLineBreaks)
            Dim entitéMIME As String = enteteMIME + base64stringXML
            Dim entitéMIME_byte = Encoding.ASCII.GetBytes(entitéMIME)

            Dim content = New ContentInfo(entitéMIME_byte)
            Dim signedCms = New SignedCms(content, False)
            Dim signer = New CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, get_certif)
            signedCms.ComputeSignature(signer)
            Dim signedbytes = signedCms.Encode()

            Dim msg = New MailMessage
            msg.From = New MailAddress(Config.LOI_Pop3_BAL)
            'msg.To.Add(New MailAddress("centre-de-service@sesam-vitale.fr"))
            'msg.To.Add(New MailAddress("542025291@resopharma.fr"))
            'msg.To.Add(New MailAddress("oppo-loi-fictive@pour-anr.fr"))
            If Config.OCT_UtilisationOCT = False Then
                msg.To.Add(New MailAddress(Config.LOI_Distr_horsOCT))
            Else
                msg.To.Add(New MailAddress(Config.LOI_Distr_OCT))
            End If

            msg.Subject = "dLOI/" + Format(Now, "yyyyMMddhhmmss") + "00001"
            msg.Headers.Add("Content-Description", "DEMANDE/dLOI")

            Dim ms = New MemoryStream(signedbytes)
            Dim av2 = New AlternateView(ms, "application/pkcs7-mime; smime-type=signed-data;name=smime.p7m")
            msg.AlternateViews.Add(av2)

            msg.Body.Remove(0, 0)

            Dim client As New SmtpClient
            client.Host = Config.LOI_smtp_serveur
            client.Port = Config.LOI_smtp_serveur_port
            client.Send(msg)

            My.Computer.FileSystem.WriteAllText(Application.StartupPath + "\traces\LOI_log.txt", Chr(10) + "----------" + Chr(10) + "dLOI  " + Format(Now, "dd/MM/yyyy  hh:mm:ss") + Chr(10) + stringXML, True)

            Me.LOI_DemandeTableAdapter.Insert(Format(Now, "dd/MM/yyyy"), Format(Now, "hh:mm"), Config.LOI_Ref, Config.LOI_code_resultat_incr_prec, msg.Subject.ToString)
            If Confirm_Message = True Then
                MsgBox("Demande LOI transmise", MsgBoxStyle.Information)
            End If
        Catch ex As Exception
            If Confirm_Message = True Then
                MsgBox("Demande LOI non transmise, voire fichier log", MsgBoxStyle.Exclamation)
            End If
            My.Computer.FileSystem.WriteAllText(Application.StartupPath + "\traces\LOI_log.txt", Chr(10) + "----------" + Chr(10) + "ERREUR  " + Format(Now, "dd/MM/yyyy  hh:mm:ss") + Chr(10) + ex.ToString, True)
        End Try
    End Sub

    Private Sub Demande_LOI_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Demande_LOI_Button.Click
        Getmail_LOI()
        Demande_dLoi(True)

    End Sub

    Public Sub Demande_Auto_Loi()
        If Config.LOI_Demande_Auto = True Then
            Demande_dLoi(False)
        End If
    End Sub

#End Region

#Region "Alerte"
    Public Sub Alerte_Non_Reception()

        'non reception>LOI_NB_JOUR_Max
        If Config.LOI_Activer = True Then
            If DateDiff(DateInterval.Day, Date.ParseExact(Mid(Config.LOI_Ref, 1, 8), "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture), Now) > Val(Config.LOI_NB_JOUR_Max) Then
                MsgBox("nombre de jours sans réception de dLOI: " + DateDiff(DateInterval.Day, Date.ParseExact(Mid(Config.LOI_Ref, 1, 8), "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture), Now).ToString, MsgBoxStyle.Exclamation)
                Exit Sub
            End If
        End If

        'non reception mensuelle

        If Config.LOI_Activer = True And Config.LOI_Controle_MAJ_mensuel = True Then
            Dim DateRef As Date = Date.ParseExact(Mid(Config.LOI_Ref, 1, 8), "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture)
            If DateDiff(DateInterval.Month, DateRef, Now) > 1 Then
                MsgBox("La liste LOI active n’est pas à jour." + Chr(10) + "Prenez contact avec votre Opérateur de diffusion LOI.", MsgBoxStyle.Exclamation)
            ElseIf DateDiff(DateInterval.Month, DateRef, Now) = 1 Then
                If Val(Mid(Config.LOI_Ref, 7, 2)) <= 18 Then
                    MsgBox("La liste LOI active n’est pas à jour." + Chr(10) + "Prenez contact avec votre Opérateur de diffusion LOI.", MsgBoxStyle.Exclamation)
                End If

            End If
        End If
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Alerte_non_reception_Button.Click
        Alerte_Non_Reception()
    End Sub
#End Region

#Region "BAL"

    Public Sub Getmail_LOI()
        Try

            Dim Server As TcpClient
            Dim NetStrm As System.Net.Sockets.NetworkStream
            Dim RdStrm As System.IO.StreamReader
            Dim Data As String
            Dim szData As Byte()
            Dim retour As String

            'create server POP3 with port 110
            Me.RichTextBox_connection.AppendText("CONNECTION")
            Server = New TcpClient(Config.LOI_Pop3_Serveur, Config.LOI_Pop3_Port)
            NetStrm = Server.GetStream()
            RdStrm = New StreamReader(NetStrm)
            retour = RdStrm.ReadLine()
            Me.RichTextBox_connection.AppendText(retour + vbCrLf)
            If InStr(retour, "OK") = 0 Then
                Me.RichTextBox_connection.AppendText("ERREUR DE CONNECTION BAL" + vbCrLf)
            End If
            retour = "connected:" + Server.Connected.ToString
            Me.RichTextBox_connection.AppendText(retour + Chr(10))

            'Login Process
            Data = "USER " + Config.LOI_Pop3_User & vbCrLf
            szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
            NetStrm.Write(szData, 0, szData.Length)
            retour = RdStrm.ReadLine
            Me.RichTextBox_connection.AppendText(retour + Chr(10))
            If InStr(retour, "OK") = 0 Then
                Me.RichTextBox_connection.AppendText("ERREUR DE CONNECTION" + Chr(10))
            End If

            Data = "PASS " + Config.LOI_Pop3_Password & vbCrLf
            szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
            NetStrm.Write(szData, 0, szData.Length)
            retour = RdStrm.ReadLine
            Me.RichTextBox_connection.AppendText(retour + Chr(10))
            If InStr(retour, "OK") = 0 Then
                Me.RichTextBox_connection.AppendText("ERREUR DE CONNECTION" + Chr(10))
            End If

            'Send STAT command to get information ie: number of mail
            Data = "STAT" & vbCrLf
            szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
            NetStrm.Write(szData, 0, szData.Length)
            retour = RdStrm.ReadLine
            Me.RichTextBox_connection.AppendText("STAT:" + retour + Chr(10))
            Dim NumberOfMail As Integer = Val(Trim(Mid(retour, 5, 2)))
            Me.RichTextBox_connection.AppendText("Nombre de Message:" + NumberOfMail.ToString + Chr(10))

            If NumberOfMail <> 0 Then
                For i = 1 To NumberOfMail
                    Me.RichTextBox_connection.AppendText("--------------------------------------------------" + Chr(10) + "Telechargement message " + i.ToString + Chr(10))
                    Dim MessageId As String = ""
                    Dim InReplyTo As String = ""
                    Dim Subject As String = ""
                    Dim From_ As String = ""
                    Dim To_ As String = ""
                    Dim Content_Description As String = ""
                    Dim Content_Type As String = ""
                    Data = "retr " + i.ToString & vbCrLf
                    szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
                    NetStrm.Write(szData, 0, szData.Length)
                    Dim line As String = RdStrm.ReadLine
                    Dim multipart As Boolean = False
                    Dim délimiteur As String = ""
                    Dim Pièce_jointe_téléchargée As Boolean = False
                    Dim Fichier_Pièce_Jointe As String = Config.POP3_RepBAL + Format(Now, "yyyyMMddHHmmss") + ".temp"
                    Dim message_valide As Boolean
                    message_valide = True
                    '------------------------------------------------------------------------------------------------
                    While line <> "." And Pièce_jointe_téléchargée = False
                        '------------------------------------------------------------------------------------------------
                        If InStr(line, "Message-Id:") = 1 Then
                            MessageId = Trim(Mid(line, "Message-Id:".Length + 1))
                            Me.RichTextBox_connection.AppendText("MessageId: " + MessageId + Chr(10))
                        ElseIf InStr(line, "In-Reply-To:") = 1 Then
                            InReplyTo = Trim(Mid(line, "In-Reply-To:".Length + 1))
                            Me.RichTextBox_connection.AppendText("InReplyTo: " + InReplyTo + Chr(10))
                        ElseIf InStr(line, "Subject:") = 1 Then
                            Subject = Trim(Mid(line, "Subject:".Length + 1))
                            Me.RichTextBox_connection.AppendText("Subject: " + Subject + Chr(10))
                        ElseIf InStr(line, "From:") = 1 Then
                            From_ = Trim(Mid(line, "From:".Length + 1))
                            If InStr(From_, "<") = 1 And InStr(From_, ">") = From_.Length Then
                                From_ = Mid(From_, 2, From_.Length - 2)
                            End If
                            Me.RichTextBox_connection.AppendText("From: " + From_ + Chr(10))
                        ElseIf InStr(line, "To:") = 1 Then
                            To_ = Trim(Mid(line, "To:".Length + 1))
                            Me.RichTextBox_connection.AppendText("To: " + To_ + Chr(10))
                        ElseIf InStr(line, "Content-Type:") = 1 Then
                            Content_Type = Trim(Mid(line, "Content-Type:".Length + 1))
                            Me.RichTextBox_connection.AppendText("Content-Type: " + Content_Type + Chr(10))
                            If InStr(Content_Type, "multipart") <> 0 Then
                                délimiteur = Mid(Content_Type, InStr(Content_Type, "boundary=") + 9)
                                multipart = True
                            End If
                        ElseIf InStr(line, "Content-Description:") = 1 Then
                            Content_Description = Trim(Mid(line, "Content-Description:".Length + 1))
                            Me.RichTextBox_connection.AppendText("Content-Description: " + Content_Description + Chr(10))
                        End If

                        '------------------------------------------------------------------------------------------------
                        'NON REMISE
                        If From_ = Config.SMTP_Postmaster Then
                            MsgBox("Une demande précédente de LOI n' a pas été transmise.(POSTMASTER)", MsgBoxStyle.Information)
                            Dim MyFile As String = Config.POP3_RepBAL + Format(Now, "yyyyMMddHHmmss") + ".Postmaster"
                            While Dir(Config.LOI_Pop3_RepBAL + MyFile) <> ""
                                MyFile = Config.LOI_Pop3_RepBAL + Format(Now, "yyyyMMddHHmmss") + ".Postmaster"
                            End While
                            My.Computer.FileSystem.WriteAllText(MyFile, Chr(10) + "------------------------------------------------------------------------------------------------" + Chr(10), True)
                            line = RdStrm.ReadLine
                            Do
                                Me.RichTextBox_connection.AppendText(line + Chr(10))
                                My.Computer.FileSystem.WriteAllText(MyFile, line + Chr(10), True)
                                line = RdStrm.ReadLine
                            Loop Until line = "." Or line Is Nothing
                            My.Computer.FileSystem.WriteAllText(MyFile, "------------------------------------------------------------------------------------------------" + Chr(10), True)
                            Pièce_jointe_téléchargée = True
                            message_valide = False

                            'mauvais expéditeur
                        ElseIf (Config.OCT_UtilisationOCT = False Or From_ <> Config.LOI_Distr_OCT) And _
                            (Config.OCT_UtilisationOCT = True Or From_ <> Config.LOI_Distr_horsOCT) And From_ <> "" Then
                            MsgBox("expediteur inconnu dans bal LOI:" + From_, MsgBoxStyle.Exclamation)
                            message_valide = False
                            Do
                                line = RdStrm.ReadLine
                            Loop Until line = "." Or line Is Nothing
                        End If
                        '------------------------------------------------------------------------------------------------
                        If multipart = False And Content_Description <> "" And Pièce_jointe_téléchargée = False Then
                            While line <> "" 'avance jusqu'à ligne blanche(juste avant pièce jointe)
                                line = RdStrm.ReadLine
                            End While
                            'sauvegarde pièce jointe dans fichier temp
                            line = RdStrm.ReadLine 'debut pièce jointe
                            While line <> ""
                                My.Computer.FileSystem.WriteAllText(Fichier_Pièce_Jointe, line, True)
                                line = RdStrm.ReadLine
                            End While
                            Pièce_jointe_téléchargée = True
                        End If
                        '------------------------------------------------------------------------------------------------
                        If multipart = True And délimiteur <> "" And Pièce_jointe_téléchargée = False Then
                            If InStr(line, "Content-Description") <> 0 Then
                                While line <> "" 'avance jusqu'à ligne blanche(juste avant pièce jointe)
                                    line = RdStrm.ReadLine
                                End While
                                'sauvegarde pièce jointe dans fichier temp
                                line = RdStrm.ReadLine 'debut pièce jointe
                                While InStr(line, délimiteur) = 0
                                    My.Computer.FileSystem.WriteAllText(Fichier_Pièce_Jointe, line, True)
                                    line = RdStrm.ReadLine
                                End While
                            End If
                            Pièce_jointe_téléchargée = True
                        End If
                        '------------------------------------------------------------------------------------------------
                        If Pièce_jointe_téléchargée = False Then line = RdStrm.ReadLine
                        '------------------------------------------------------------------------------------------------
                    End While
                    While line <> "."
                        line = RdStrm.ReadLine()
                    End While

                    '------------------------------------------------------------------------------------------------
                    If InStr(Content_Description, "REPONSE/dLOI") = 1 And From_ = Config.LOI_Distr_horsOCT And From_ = Config.LOI_Distr_OCT And message_valide = True Then  'Message SMTP contenant le fichier d’incrément dLOI signé

                        If Me.LOI_DemandeTableAdapter.Select_Count_By_Subject(InReplyTo) > 0 Or Config.LOI_Controle_Correspondance = False Then
                            '-------------------
                            'suppr doublons
                            If My.Computer.FileSystem.FileExists(Config.LOI_Pop3_RepBAL + "dLOI\" + Mid(Subject, InStr(Subject, "/") + 1) + ".dloi") Then
                                My.Computer.FileSystem.DeleteFile(Config.LOI_Pop3_RepBAL + "dLOI\" + Mid(Subject, InStr(Subject, "/") + 1) + ".dloi")
                            End If
                            '-------------------
                            If InStr(Content_Description, "/Z") <> 0 Then
                                convert_base64file_to_another_file(Fichier_Pièce_Jointe, Config.LOI_Pop3_RepBAL + "dLOI\temp.gz", True)
                                Teletransmission_MAIN.ShellandWait("c:\gzip", "gzip.exe", "-d -q " + Config.LOI_Pop3_RepBAL + "dLOI\temp.gz")
                            Else
                                convert_base64file_to_another_file(Fichier_Pièce_Jointe, Config.LOI_Pop3_RepBAL + "dLOI\temp", True)
                            End If
                            Dim name_string As String
                            Dim fs As FileStream
                            fs = File.Open(Config.LOI_Pop3_RepBAL + "dLOI\temp", FileMode.Open)
                            Using be As New BinaryReader(fs)
                                be.ReadChars(42)
                                name_string = be.ReadChars(12)
                                name_string = name_string + "_" + be.ReadChars(12)
                            End Using
                            fs.Close()
                            If My.Computer.FileSystem.FileExists(Config.LOI_Pop3_RepBAL + "dLOI\" + name_string + ".dloi") Then
                                My.Computer.FileSystem.DeleteFile(Config.LOI_Pop3_RepBAL + "dLOI\" + name_string + ".dloi")
                            End If
                            My.Computer.FileSystem.RenameFile(Config.LOI_Pop3_RepBAL + "dLOI\temp", name_string + ".dloi")
                            RichTextBox_BAL.AppendText("reçu dLOI " + Mid(Subject, InStr(Subject, "/") + 1) + Chr(10))
                        Else
                            MsgBox("Réception d'un retour dLOI ne correspondant à aucune demande envoyée!" + Chr(10) + "Incrémént rejeté", MsgBoxStyle.Exclamation)
                        End If
                        'End If



                    ElseIf InStr(Content_Description, "REPONSE/ARAN") = 1 And message_valide = True Then 'impossibilité fonctionnelle (ARAN)
                        Using sw As New StreamWriter(Config.LOI_Pop3_RepBAL + "ARAN" + Format(Now, "yyyyMMddHHmmss") + ".txt", True)
                            sw.WriteLine("From: " + From_)
                            sw.WriteLine("To: " + To_)
                            sw.WriteLine("In-Reply-To: " + InReplyTo)
                            sw.WriteLine("Subject: " + Subject)
                            sw.WriteLine("Content-Type: " + Content_Type)
                            sw.WriteLine("Content-Description: " + Content_Description)
                        End Using
                        If Me.LOI_DemandeTableAdapter.Select_Count_By_Subject(InReplyTo) > 0 Then
                            Dim code As String
                            code = Mid(Subject, InStrRev(Subject, "/") + 1)
                            Select Case code
                                Case "0100"
                                    MsgBox("ARAN:    code " + code + Chr(10) + "Le délai est dépassé (nb de dLOI à envoyer trop important)" _
                                           + Chr(10) + "la LOI active n’est pas à jour." + Chr(10) + "prenez contact avec votre opérateur de diffusion LOI (Editeur et ou OCT)", MsgBoxStyle.Exclamation)

                                Case Else
                                    MsgBox("ARAN:    code " + code + Chr(10) + "Code Inconnu)", MsgBoxStyle.Exclamation)
                            End Select

                        Else
                            MsgBox("ARAN INCONNU" + Chr(10) + "In Reply To:" + InReplyTo)
                        End If
                    End If
                    'suppression message
                    Data = "DELE " + i.ToString & vbCrLf
                    szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
                    NetStrm.Write(szData, 0, szData.Length)
                    Me.RichTextBox_connection.AppendText("MESSAGE " + i.ToString + " SUPPRIMÉ" + Chr(10))

                Next

            End If

            'Send QUIT command to close session from POP server
            Data = "QUIT" & vbCrLf
            szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
            NetStrm.Write(szData, 0, szData.Length)
            Me.RichTextBox_connection.AppendText("SESSION FERMEE" + Chr(10))

        Catch ex As Exception
            MsgBox(ex.ToString)

        End Try

    End Sub

    Private Sub Bal_LOI_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Bal_LOI_Button.Click
        Getmail_LOI()
    End Sub

#End Region

#Region "INCREMENTE"
    Public Sub traitement_dLOI()
        '---------------------------------------------------------------------------------------
        'tableau avec les noms de fichiers
        Dim tab_fichier() As String
        ReDim tab_fichier(0)
        Dim compteur_fichier As Integer = 0
        Dim fichier As String
        fichier = Dir(Config.LOI_Pop3_RepBAL + "dLOI\*.dLOI")
        While fichier <> ""
            ReDim Preserve tab_fichier(compteur_fichier)
            tab_fichier(compteur_fichier) = Mid(fichier, 1, InStr(fichier, ".") - 1)
            compteur_fichier = compteur_fichier + 1
            fichier = Dir()
        End While

        '---------------------------------------------------------------------------------------
        'tri du tableau du plus petit au plus grand
        Dim tampon As String
        Dim TriFini, PasFini As Boolean
        Do While TriFini = False
            PasFini = False
            For i = 0 To tab_fichier.Length - 2
                If tab_fichier(i) > tab_fichier(i + 1) Then
                    tampon = tab_fichier(i)
                    tab_fichier(i) = tab_fichier(i + 1)
                    tab_fichier(i + 1) = tampon
                    PasFini = True
                End If
            Next
            If PasFini = False Then
                TriFini = True
                Exit Do
            End If
        Loop

        '---------------------------------------------------------------------------------------
        For i = 0 To tab_fichier.Length - 1
            Incremente_LOI(Config.LOI_Pop3_RepBAL + "loi.loi", Config.LOI_Pop3_RepBAL + "dLOI\" + tab_fichier(i))
        Next


    End Sub
    Private Sub Incremente_LOI(ByVal Fichier_LOI As String, ByVal Fichier_Increment As String)
        If Security_Verify_dLOI(Fichier_Increment + ".dloi") = False Then
            MsgBox("ERREUR CERTIFICAT INCREMENT  " + Mid(Fichier_Increment, InStrRev(Fichier_Increment, "\") + 1), MsgBoxStyle.Critical)
            Exit Sub
        End If
        Dim fs_LOI As FileStream
        Dim fs_Increment As FileStream
        Dim XorResult As Byte()
        Dim RefLOI_Active, Ref_increment_n_1, Ref_increment_obtenu, Taille_Signature, Taille_Certificat As String
        Dim Signature(), Certificat() As Byte
        fs_LOI = File.Open(Fichier_LOI, FileMode.Open)
        fs_Increment = File.Open(Fichier_Increment + ".dloi", FileMode.Open)
        Dim taille_bitmap_LOI As String = ""
        Dim taille_bitmap_Increment As String = ""

        Using br_LOI As New BinaryReader(fs_LOI)
            Using br_Increment As New BinaryReader(fs_Increment)
                '--------------------------------------------------------------------
                '4premiers caractères taille en-tête
                Dim taille_entete_LOI As String = ""
                Dim taille_entete_Increment As String = ""

                taille_entete_LOI = br_LOI.ReadChars(4)
                taille_entete_Increment = br_Increment.ReadChars(4)
                '--------------------------------------------------------------------
                'avance jusqu'à debut taille bitmap + recup some values
                br_LOI.ReadChars(22)
                RefLOI_Active = br_LOI.ReadChars(12)
                br_LOI.ReadChars(4)

                br_Increment.ReadChars(38)
                Ref_increment_n_1 = br_Increment.ReadChars(12)
                Ref_increment_obtenu = br_Increment.ReadChars(12)
                Taille_Signature = br_Increment.ReadChars(4)
                ReDim Signature(Val(Taille_Signature))
                Signature = br_Increment.ReadBytes(Val(Taille_Signature))

                '--------------------------------------------------------------------
                'verif increment s'applique sur loi
                If Ref_increment_n_1 <> RefLOI_Active Then
                    MsgBox("increment ne s'applique pas sur loi active" + Chr(10) + "INCREMENT " + Ref_increment_n_1 + "_" + Ref_increment_obtenu + Chr(10) + _
                           "LOI " + RefLOI_Active, MsgBoxStyle.Exclamation)
                    If My.Computer.FileSystem.FileExists(Fichier_Increment + ".old") Then
                        My.Computer.FileSystem.DeleteFile(Fichier_Increment + ".old")
                    End If
                    br_Increment.Close()
                    fs_Increment.Close()
                    My.Computer.FileSystem.RenameFile(Fichier_Increment + ".dloi", Mid(Fichier_Increment, InStrRev(Fichier_Increment, "\") + 1) + ".old")
                    Exit Sub
                End If
                '--------------------------------------------------------------------
                'taille bitmap (en octet, 8bits par octet) 
                taille_bitmap_LOI = br_LOI.ReadChars(8)
                taille_bitmap_Increment = br_Increment.ReadChars(8)

                If taille_bitmap_LOI <> taille_bitmap_Increment Then
                    MsgBox("taille bitmap LOI <> taille bitmap incerment", MsgBoxStyle.Critical)
                    Exit Sub
                End If
                '--------------------------------------------------------------------
                'XOR
                ReDim XorResult(Val(taille_bitmap_LOI) - 1)
                Try
                    Dim Byte_LOI, Byte_Increment As Byte
                    For i = 0 To Val(taille_bitmap_LOI) - 1
                        Byte_LOI = br_LOI.ReadByte()
                        Byte_Increment = br_Increment.ReadByte
                        XorResult(i) = Byte_LOI Xor Byte_Increment
                    Next
                Catch ex As Exception
                    MsgBox(ex.ToString)
                End Try
                '--------------------------------------------------------------------
                'recup cerificat fichier dLOI
                br_Increment.ReadChars(4)
                Dim taillesignature = br_Increment.ReadChars(4)
                br_Increment.ReadBytes(Val(taillesignature))
                Taille_Certificat = br_Increment.ReadChars(4)
                Certificat = br_Increment.ReadBytes(Val(Taille_Certificat))


            End Using
        End Using
        If My.Computer.FileSystem.FileExists(Config.LOI_Pop3_RepBAL + "loi.old") Then
            My.Computer.FileSystem.DeleteFile(Config.LOI_Pop3_RepBAL + "loi.old")
        End If
        My.Computer.FileSystem.RenameFile(Fichier_LOI, "loi.old")
        'My.Computer.FileSystem.DeleteFile(Fichier_LOI)


        Dim fs As FileStream
        fs = File.Create(Fichier_LOI)
        Dim bw As New BinaryWriter(fs)
        bw.Write(Encoding.ASCII.GetBytes("0042LOI                 01" + Ref_increment_obtenu + "BTMP" + taille_bitmap_LOI))
        bw.Write(XorResult)
        Dim taillecontrole As String
        taillecontrole = (12 + Val(Taille_Signature) + Val(Taille_Certificat)).ToString

        While taillecontrole.Length < 4
            taillecontrole = "0" + taillecontrole
        End While
        bw.Write(Encoding.ASCII.GetBytes(taillecontrole + Taille_Signature))
        bw.Write(Signature)
        bw.Write(Encoding.ASCII.GetBytes(Taille_Certificat))
        bw.Write(Certificat)
        bw.Close()
        fs.Close()

        If Security_Verify_LOI(Fichier_LOI) = False Then
            MsgBox("ERREUR CERTIFICAT INCREMENT  " + Fichier_Increment, MsgBoxStyle.Critical)
            Exit Sub
        End If

        '---------------------------------------------------------------------------------------
        If My.Computer.FileSystem.FileExists(Fichier_Increment + ".old") Then
            My.Computer.FileSystem.DeleteFile(Fichier_Increment + ".old")
        End If
        My.Computer.FileSystem.RenameFile(Fichier_Increment + ".dloi", Mid(Fichier_Increment, InStrRev(Fichier_Increment, "\") + 1) + ".old")
        '---------------------------------------------------------------------------------------
        'save new ref
        Config.LOI_Ref = Ref_increment_obtenu
        Dim ConfigXml As New XmlDocument
        Dim ConfigXMLelementliste As XmlNodeList
        ConfigXml.Load(Application.StartupPath + "\config.xml")
        ConfigXMLelementliste = ConfigXml.GetElementsByTagName("LOI")
        ConfigXMLelementliste.Item(0).Item("LOI_Ref").InnerText = Ref_increment_obtenu
        ConfigXml.Save(Application.StartupPath + "\config.xml")
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles incremente_Button.Click
        traitement_dLOI()
    End Sub
#End Region

#Region "CERTIFICATS"

    Private Sub verif_sign_dLOI_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles verif_sign_dLOI_Button.Click
        OpenFileDialog1.InitialDirectory = Config.LOI_Pop3_RepBAL + "dloi\"
        If OpenFileDialog1.ShowDialog() <> Windows.Forms.DialogResult.OK Then
            Exit Sub
        End If
        If OpenFileDialog1.FileName = "" Then
            Exit Sub
        End If
        MsgBox(Security_Verify_dLOI(OpenFileDialog1.FileName))
    End Sub
    Private Function Security_Verify_dLOI(ByVal Fichier As String) As Boolean
        Dim fs As FileStream
        fs = File.Open(Fichier, FileMode.Open)
        Dim Taille_En_Tete, Taille_BMP, Taille_controle, Taille_Signature_LOI, Taille_Signature_dLOI, Taille_certificat As Integer
        Dim Application, Version_appli, Référence, Référence_LOI_n_moins_1, Référence_LOI_n, Format As String
        Dim bitmap(), signature_LOI(), signature_dLOI(), data_that_has_been_signed() As Byte
        Dim certificat As New X509Certificate2


        Dim br As New BinaryReader(fs)
        Taille_En_Tete = Val(br.ReadChars(4))
        Application = br.ReadChars(20)
        Version_appli = br.ReadChars(2)
        Référence = br.ReadChars(12)
        Format = br.ReadChars(4)
        Référence_LOI_n_moins_1 = br.ReadChars(12)
        Référence_LOI_n = br.ReadChars(12)
        Taille_Signature_LOI = Val(br.ReadChars(4))
        signature_LOI = br.ReadBytes(Taille_Signature_LOI)
        Taille_BMP = Val(br.ReadChars(8))
        bitmap = br.ReadBytes(Taille_BMP)
        Taille_controle = Val(br.ReadChars(4))
        Taille_Signature_dLOI = Val(br.ReadChars(4))
        signature_dLOI = br.ReadBytes(Taille_Signature_dLOI)
        Taille_certificat = Val(br.ReadChars(4))
        certificat.Import(br.ReadBytes(Taille_certificat))
        br.Close()
        fs.Close()

        fs = File.Open(Fichier, FileMode.Open)
        Dim br2 As New BinaryReader(fs)
        data_that_has_been_signed = br2.ReadBytes(Taille_En_Tete + 8 + Taille_BMP)
        br2.Close()
        fs.Close()

        'MsgBox(Taille_En_Tete.ToString + Chr(10) + Application + Chr(10) + Version_appli + Chr(10) + Référence + Chr(10) + Format + Chr(10) + Taille_BMP.ToString + Chr(10) + bitmap.Length.ToString + Chr(10) + Taille_controle.ToString + Chr(10) + Taille_Signature.ToString + Chr(10) + signature_LOI.Length.ToString + Chr(10) + Taille_certificat.ToString + Chr(10) + certificat.ToString)
        'MsgBox(certificat.SignatureAlgorithm.FriendlyName.ToString)
        'MsgBox(certificat.ToString)

        '--------------------------
        'verif signature
        Dim rsa As RSACryptoServiceProvider = certificat.PublicKey.Key
        'MsgBox(rsa.VerifyData(data_that_has_been_signed, CryptoConfig.MapNameToOID("SHA1"), signature_dLOI))
        Dim sha1 = New SHA1Managed()
        Dim hash = sha1.ComputeHash(data_that_has_been_signed)
        Return (rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signature_dLOI))
    End Function

    Private Sub verif_sign_LOI_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles verif_sign_LOI_Button.Click
        OpenFileDialog1.InitialDirectory = Config.LOI_Pop3_RepBAL
        If OpenFileDialog1.ShowDialog() <> Windows.Forms.DialogResult.OK Then
            Exit Sub
        End If
        If OpenFileDialog1.FileName = "" Then
            Exit Sub
        End If
        MsgBox(Security_Verify_LOI(OpenFileDialog1.FileName))
    End Sub
    Private Function Security_Verify_LOI(ByVal Fichier As String) As Boolean
        Dim fs As FileStream
        fs = File.Open(Fichier, FileMode.Open)
        Dim Taille_En_Tete, Taille_BMP, Taille_controle, Taille_Signature, Taille_certificat As Integer
        Dim Application, Version_appli, Référence, Format As String
        Dim bitmap(), signature_LOI(), data_that_has_been_signed() As Byte
        Dim certificat As New X509Certificate2


        Dim br As New BinaryReader(fs)
        Taille_En_Tete = Val(br.ReadChars(4))
        Application = br.ReadChars(20)
        Version_appli = br.ReadChars(2)
        Référence = br.ReadChars(12)
        Format = br.ReadChars(4)
        Taille_BMP = Val(br.ReadChars(8))
        bitmap = br.ReadBytes(Taille_BMP)
        Taille_controle = Val(br.ReadChars(4))
        Taille_Signature = Val(br.ReadChars(4))
        signature_LOI = br.ReadBytes(Taille_Signature)
        Taille_certificat = Val(br.ReadChars(4))
        certificat.Import(br.ReadBytes(Taille_certificat))
        br.Close()
        fs.Close()

        fs = File.Open(Fichier, FileMode.Open)
        Dim br2 As New BinaryReader(fs)
        data_that_has_been_signed = br2.ReadBytes(Taille_En_Tete + 8 + Taille_BMP)
        br2.Close()
        fs.Close()
        Dim chain As New X509Chain()
        chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck
        If (chain.Build(certificat)) = False Then
            For Each obj_ In chain.ChainStatus
                MsgBox(obj_.Status.ToString + Chr(10) + obj_.StatusInformation)
            Next
        End If
        If (chain.ChainElements.Item(chain.ChainElements.Count - 1).Certificate.Verify) = False Then
            Return False
        End If
        '-------------------------- 
        'For i = 0 To certificat.Extensions.Count - 1
        '    My.Computer.FileSystem.WriteAllText("c:\test.txt", certificat.Extensions.Item(i).Oid.FriendlyName.ToString + "  " + certificat.Extensions.Item(i).Oid.Value _
        '                                       + "  " + certificat.Extensions.Item(i).RawData.Length.ToString + Chr(10), True)
        '    If certificat.Extensions.Item(i).RawData.Length > 0 Then
        '        For j = 0 To certificat.Extensions.Item(i).RawData.Length - 1
        '            My.Computer.FileSystem.WriteAllText("c:\test.txt", certificat.Extensions.Item(i).RawData(j).ToString + " ", True)
        '        Next
        '        My.Computer.FileSystem.WriteAllText("c:\test.txt", Chr(10), True)
        '    End If

        'Next

        'Dim sha1_2 = New SHA1Managed()
        'Dim hash2 = sha1_2.ComputeHash(certificat.GetPublicKey)
        'MsgBox(hash2.Length)
        'For i = 0 To 19
        '    My.Computer.FileSystem.WriteAllText("c:\hash.txt", hash2(i).ToString + " ", True)
        'Next


        'verif clé GIP-CPS
        If certificat.GetPublicKeyString <> Config.LOI_clé_GIP_CPS Then
            MsgBox("ERREUR CLE CERTIFICAT", MsgBoxStyle.Critical)
            Return False
        End If

        'verif signature
        Dim rsa As RSACryptoServiceProvider = certificat.PublicKey.Key
        Dim sha1 = New SHA1Managed()
        Dim hash = sha1.ComputeHash(data_that_has_been_signed)
        Return (rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signature_LOI))

    End Function

#End Region

#Region "INIT LOI"

    Private Sub init_LOI_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles init_LOI_Button.Click
        OpenFileDialog1.InitialDirectory = Config.LOI_Pop3_RepBAL
        If OpenFileDialog1.ShowDialog() <> Windows.Forms.DialogResult.OK Then
            Exit Sub
        End If
        If OpenFileDialog1.FileName = "" Then
            Exit Sub
        End If
        If Security_Verify_LOI(System.IO.Path.GetFullPath(OpenFileDialog1.FileName)) = False Then
            MsgBox("ERREUR: CERTIFICAT LOI NON VALIDE", MsgBoxStyle.Critical)
            Exit Sub
        End If
        If My.Computer.FileSystem.FileExists(Config.LOI_Pop3_RepBAL + "loi.loi") Then
            My.Computer.FileSystem.DeleteFile(Config.LOI_Pop3_RepBAL + "loi.loi")
        End If
        My.Computer.FileSystem.CopyFile(OpenFileDialog1.FileName, Config.LOI_Pop3_RepBAL + "loi.loi")

        Dim fs As FileStream
        fs = File.Open(Config.LOI_Pop3_RepBAL + "loi.loi", FileMode.Open)
        Dim br As New BinaryReader(fs)
        br.ReadBytes(26)
        Config.LOI_Ref = br.ReadChars(12)
        'Config.LOI_Ref = Mid(OpenFileDialog1.FileName, InStrRev(OpenFileDialog1.FileName, "\") + 1, 12)
        br.Close()
        fs.Close()

        Dim ConfigXml As New XmlDocument
        ConfigXml.Load(Application.StartupPath + "\config.xml")
        Dim XMLelementliste As XmlNodeList
        XMLelementliste = ConfigXml.GetElementsByTagName("LOI")
        XMLelementliste.Item(0).Item("LOI_Ref").InnerText = Config.LOI_Ref
        ConfigXml.Save(Application.StartupPath + "\config.xml")
        MsgBox("LOI initialisée " + Config.LOI_Ref, MsgBoxStyle.Information)
    End Sub

#End Region



    Private Sub Button10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

        Dim enteteMIME As String = "Content-Type: text/plain" + Chr(10) + "Content-Transfer-Encoding: 7bit" + Chr(10) + Chr(10)

        Dim stringXML = "<?xml version=" + Chr(34) + "1.0" + Chr(34) + " encoding=" + Chr(34) + "UTF-8" + Chr(34) + "?>" + Chr(10) + _
        "<demande_dLOI>" + Chr(10) + _
        "<date_envoi>" + Format(Now, "dd/MM/yyyy") + "</date_envoi>" + Chr(10) + _
        "<heure_envoi>" + Format(Now, "hh:mm") + "</heure_envoi>" + Chr(10) + _
        "<ref_LOI>200803261003</ref_LOI>" + Chr(10) + _
        "<bal_LOI>542025291@resopharma.fr</bal_LOI>" + Chr(10) + _
        "<code_resultat_incr_prec>0</code_resultat_incr_prec>" + Chr(10) + _
        "</demande_dLOI>"


        Dim stringXML_byte = Encoding.Default.GetBytes(stringXML)
        Dim base64stringXML = System.Convert.ToBase64String(stringXML_byte, Base64FormattingOptions.InsertLineBreaks)

        ' Dim strbody = Encoding.ASCII.GetBytes(stringXML)
        Dim entitéMIME As String = enteteMIME + base64stringXML
        'MsgBox(entitéMIME)
        Dim entitéMIME_byte = Encoding.ASCII.GetBytes(entitéMIME)

        Dim content = New ContentInfo(entitéMIME_byte)
        Dim signedCms = New SignedCms(content, False)
        Dim signer = New CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, get_certif)
        signedCms.ComputeSignature(signer)
        Dim signedbytes = signedCms.Encode()


        Dim msg = New MailMessage
        msg.From = New MailAddress("542025291@resopharma.fr")
        'msg.To.Add(New MailAddress("centre-de-service@sesam-vitale.fr"))
        'msg.To.Add(New MailAddress("542025291@resopharma.fr"))
        msg.To.Add(New MailAddress("cnda.loi@opposition.cnda.rss.fr"))

        msg.Subject = "dLOI/" + Format(Now, "yyyyMMddhhmmss") + "00001"
        msg.Headers.Add("Content-Description", "DEMANDE/dLOI")

        Dim ms = New MemoryStream(signedbytes)
        Dim av2 = New AlternateView(ms, "application/pkcs7-mime; smime-type=signed-data;name=smime.p7m")
        msg.AlternateViews.Add(av2)

        msg.Body.Remove(0, 0)

        Dim client As New SmtpClient
        client.Host = "smtp.numericable.fr"
        client.Port = 25
        client.Send(msg)
        MsgBox("done")
    End Sub

   

   
 
    Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Definir_clé_GIP_CPS_Button.Click
        OpenFileDialog1.InitialDirectory = Config.LOI_Pop3_RepBAL
        If OpenFileDialog1.ShowDialog() <> Windows.Forms.DialogResult.OK Then
            Exit Sub
        End If
        If OpenFileDialog1.FileName = "" Then
            Exit Sub
        End If
        Dim fs As FileStream
        fs = File.Open(OpenFileDialog1.FileName, FileMode.Open)
        Dim Taille_En_Tete, Taille_BMP, Taille_controle, Taille_Signature, Taille_certificat As Integer
        Dim Application_, Version_appli, Référence, Format As String
        Dim bitmap(), signature_LOI() As Byte
        Dim certificat As New X509Certificate2


        Dim br As New BinaryReader(fs)
        Taille_En_Tete = Val(br.ReadChars(4))
        Application_ = br.ReadChars(20)
        Version_appli = br.ReadChars(2)
        Référence = br.ReadChars(12)
        Format = br.ReadChars(4)
        Taille_BMP = Val(br.ReadChars(8))
        bitmap = br.ReadBytes(Taille_BMP)
        Taille_controle = Val(br.ReadChars(4))
        Taille_Signature = Val(br.ReadChars(4))
        signature_LOI = br.ReadBytes(Taille_Signature)
        Taille_certificat = Val(br.ReadChars(4))
        certificat.Import(br.ReadBytes(Taille_certificat))
        br.Close()
        fs.Close()

        Config.LOI_clé_GIP_CPS = certificat.GetPublicKeyString
        Dim ConfigXml As New XmlDocument
        ConfigXml.Load(Application.StartupPath + "\config.xml")
        Dim XMLelementliste As XmlNodeList
        XMLelementliste = ConfigXml.GetElementsByTagName("LOI")
        XMLelementliste.Item(0).Item("LOI_cle_GIP_CPS").InnerText = Config.LOI_clé_GIP_CPS
        ConfigXml.Save("config.xml")

    End Sub
End Class