IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Delphi Discussion :

Usage de la bibliothèque Cryptlib


Sujet :

Delphi

  1. #1
    Membre régulier
    Homme Profil pro
    Analyse système
    Inscrit en
    Mai 2013
    Messages
    190
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Analyse système
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2013
    Messages : 190
    Points : 113
    Points
    113
    Par défaut Usage de la bibliothèque Cryptlib
    Bonjour,

    voilà je cherche plus de documentation concernant la lib Cryptlib (http://cryptlib.sogot.de/delpas.html)
    Je dois en gros crypter un fichier txt en AES CBC avec un vecteur d'initialisation de 16 octets, quelqu'un a t-il déjà jouer avec cela ?
    Voilà ce que j'ai pour le moment :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
     
    const InputFileTest = 'TestSource.cwl'; // File source
      OutputFileTest = 'TestEncoded.bin'; // File encrypted
     
    ...
     
    begin
    InputData := TFileStream.Create(InputFileTest, fmOpenRead);
    OutputData := TFileStream.Create(OutputFileTest, fmCreate);
     
    // je créé une clé je la met dans un fichier de clés
    MyKey := TCryptKey.Create(CRYPT_ALGO_RSA);
    MyKey.Labeled := MyLabel;
    MyKey.GenerateKey;
    MyKeyset := TCryptKeyset.Create(CRYPT_KEYSET_FILE, Keyfilename, CRYPT_KEYOPT_CREATE);
    MyKeyset.AddPrivateKey(MyKey, MyPassword);
    MyKeyset.Free;
    MyKeyset := nil;
     
    // je commence l'encryption
    Encrypt := TCryptEnvelope.Create(CRYPT_FORMAT_CRYPTLIB);
    Encrypt.SigningKey := MyKey.Handle;
    MyKey.Free;
    Encrypt.StreamIO(InputData, OutputData);
    Encrypt.Free;
    Je cherche un moyen d'initialiser un vecteur d'initialisation (c'est lourd) ^^

    merci pour vos rép !

  2. #2
    Expert éminent sénior
    Avatar de ShaiLeTroll
    Homme Profil pro
    Développeur C++\Delphi
    Inscrit en
    Juillet 2006
    Messages
    13 455
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Seine Saint Denis (Île de France)

    Informations professionnelles :
    Activité : Développeur C++\Delphi
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2006
    Messages : 13 455
    Points : 24 867
    Points
    24 867
    Par défaut
    Seulement 16 bits pour un ECB par bloc de 128 ?
    16 bits, suffit de faire un Random(High(Word));

    le vecteur d'initialisation du CBC permet de conserver la logique chainée du chiffrage
    VI + Bloc1 => Chiffre1
    Chiffre1 + Bloc2 => Chiffre2
    ...
    Et surtout de générer un VI différent pour chaque fois que l'on crypte d'où le random

    la seule chose que je peux te dire c'est via les API Windows faut utiliser CryptSetKeyParam(KP_IV, valeur de IV);

    D'ailleurs la documentation MSDN est très bizarre, confusion Bit / Bytes ?

    KP_IV
    pbData points to a BYTE array that specifies the initialization vector. This array must contain BlockLength/8 elements. For example, if the block length is 64 bits, the initialization vector consists of 8 bytes.

    The initialization vector is set to zero by default for the Microsoft Base Cryptographic Provider.
    Aide via F1 - FAQ - Guide du développeur Delphi devant un problème - Pensez-y !
    Attention Troll Méchant !
    "Quand un homme a faim, mieux vaut lui apprendre à pêcher que de lui donner un poisson" Confucius
    Mieux vaut se taire et paraître idiot, Que l'ouvrir et de le confirmer !
    L'ignorance n'excuse pas la médiocrité !

    L'expérience, c'est le nom que chacun donne à ses erreurs. (Oscar Wilde)
    Il faut avoir le courage de se tromper et d'apprendre de ses erreurs

  3. #3
    Membre régulier
    Homme Profil pro
    Analyse système
    Inscrit en
    Mai 2013
    Messages
    190
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Analyse système
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2013
    Messages : 190
    Points : 113
    Points
    113
    Par défaut
    Oui en effet confusion @ShaiLeTroll :s, bref en tout cas ça répond presque à ma question, sachant qu'il faut pas non plus que je retape tout, mais cette lib manque de doc c'est évident !

  4. #4
    Expert éminent sénior
    Avatar de ShaiLeTroll
    Homme Profil pro
    Développeur C++\Delphi
    Inscrit en
    Juillet 2006
    Messages
    13 455
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Seine Saint Denis (Île de France)

    Informations professionnelles :
    Activité : Développeur C++\Delphi
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2006
    Messages : 13 455
    Points : 24 867
    Points
    24 867
    Par défaut
    Au cas où qu'il y ait une confusion 16 Bits / 16 Octets donc 128 Bits
    à la place de Random, un CreateGUID est l'idéal pour une valeur pseudo-alétoire de 128 Bits
    Perso, par manque d'imagination, c'est ce que j'utilise comme générateur de clé lorsque j'utilise un EAS ECB 128

    The size of the IV is dependent on the cryptographic primitive used; for block ciphers, it is generally the cipher's block size.
    Aide via F1 - FAQ - Guide du développeur Delphi devant un problème - Pensez-y !
    Attention Troll Méchant !
    "Quand un homme a faim, mieux vaut lui apprendre à pêcher que de lui donner un poisson" Confucius
    Mieux vaut se taire et paraître idiot, Que l'ouvrir et de le confirmer !
    L'ignorance n'excuse pas la médiocrité !

    L'expérience, c'est le nom que chacun donne à ses erreurs. (Oscar Wilde)
    Il faut avoir le courage de se tromper et d'apprendre de ses erreurs

  5. #5
    Membre régulier
    Homme Profil pro
    Analyse système
    Inscrit en
    Mai 2013
    Messages
    190
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Analyse système
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2013
    Messages : 190
    Points : 113
    Points
    113
    Par défaut
    Oui oui grande confusion ! Alors moi je n'ai pas besoin dans ce contexte de générer aléatoirement les IV car je les ai déjà, en effet j'ai récupérer tout ça d'un test unitaire, donc le but étant:
    si je met une clé donnée + un IV donné je dois trouver un certain résultat.

    Alors au pire est-ce que tu bosses avec une autre lib sous Delphi quand tu gère cela ?

  6. #6
    Membre régulier
    Homme Profil pro
    Analyse système
    Inscrit en
    Mai 2013
    Messages
    190
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Analyse système
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2013
    Messages : 190
    Points : 113
    Points
    113
    Par défaut
    je suis tombé sur Lockbox3, est-ce une bonne lib ?

  7. #7
    Expert éminent sénior
    Homme Profil pro
    Analyste/ Programmeur
    Inscrit en
    Juillet 2013
    Messages
    4 630
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Analyste/ Programmeur

    Informations forums :
    Inscription : Juillet 2013
    Messages : 4 630
    Points : 10 556
    Points
    10 556

  8. #8
    Expert éminent sénior
    Avatar de ShaiLeTroll
    Homme Profil pro
    Développeur C++\Delphi
    Inscrit en
    Juillet 2006
    Messages
    13 455
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Seine Saint Denis (Île de France)

    Informations professionnelles :
    Activité : Développeur C++\Delphi
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2006
    Messages : 13 455
    Points : 24 867
    Points
    24 867
    Par défaut
    Citation Envoyé par phoenixgreg Voir le message
    Alors au pire est-ce que tu bosses avec une autre lib sous Delphi quand tu gère cela ?
    Une autre lib, oui, disons que c'est tout simplement les fonctions des API Windows
    et j'utilise une version de 2007 de JEDI JWA qui contient les headers des API système
    C'est je trouve l'avantage de C++Builder, où il y a beaucoup plus de Header Windows intégré que dans Delphi

    voici un exemple pour de l'ECB
    Pour le CBC, après le CryptAcquireContext, tu dois pouvoir fournir l'IV via

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    CryptSetKeyParam(KP_IV, {un array[0..15] of Byte});
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
     
    //------------------------------------------------------------------------------
    (*                SoLuTions is an Versatile Library for Delphi                 -
     *                                                                             -
     *  Version alternative publiée sur "www.developpez.net"                       -
     *  Post : "AES via CryptAPI"                                                  -
     *  Post Number : 6214517                                                      -
     *  Post URL = "http://www.developpez.net/forums/d1126336/environnements-developpement/delphi/api-com-sdks/aes-via-cryptapi/#post6214517"
     *                                                                             -
     *  Copyright ou © ou Copr. "SLT Solutions", (2006)                            -
     *  contributeur : ShaiLeTroll (2012) - Renommage Fichier et Correction XE2    -
     *  contributeur : ShaiLeTroll (2012) - Documentation Insight                  -
    *                                                                             -
     * Ce logiciel est un programme informatique servant à aider les développeurs  -
     * Delphi avec une bibliothèque polyvalente, adaptable et fragmentable.        -
     *                                                                             -
     * Ce logiciel est régi par la licence CeCILL-C soumise au droit français et   -
     * respectant les principes de diffusion des logiciels libres. Vous pouvez     -
     * utiliser, modifier et/ou redistribuer ce programme sous les conditions      -
     * de la licence CeCILL-C telle que diffusée par le CEA, le CNRS et l'INRIA    -
     * sur le site "http://www.cecill.info".                                       -
     *                                                                             -
     * En contrepartie de l'accessibilité au code source et des droits de copie,   -
     * de modification et de redistribution accordés par cette licence, il n'est   -
     * offert aux utilisateurs qu'une garantie limitée.  Pour les mêmes raisons,   -
     * seule une responsabilité restreinte pèse sur l'auteur du programme,  le     -
     * titulaire des droits patrimoniaux et les concédants successifs.             -
     *                                                                             -
     * A cet égard  l'attention de l'utilisateur est attirée sur les risques       -
     * associés au chargement,  à l'utilisation,  à la modification et/ou au       -
     * développement et à la reproduction du logiciel par l'utilisateur étant      -
     * donné sa spécificité de logiciel libre, qui peut le rendre complexe à       -
     * manipuler et qui le réserve donc à des développeurs et des professionnels   -
     * avertis possédant  des  connaissances  informatiques approfondies.  Les     -
     * utilisateurs sont donc invités à charger  et  tester  l'adéquation  du      -
     * logiciel à leurs besoins dans des conditions permettant d'assurer la        -
     * sécurité de leurs systèmes et ou de leurs données et, plus généralement,    -
     * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.          -
     *                                                                             -
     * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez      -
     * pris connaissance de la licence CeCILL-C, et que vous en avez accepté les   -
     * termes.                                                                     -
     *                                                                             -
     *----------------------------------------------------------------------------*)
    unit SLT.Common.Crypto;
     
    interface
     
    {*$DEFINE DEBUG_SLT_CRYPT*}
     
    uses System.Classes, System.SysUtils
      {$IFDEF MSWINDOWS}, JwaWinCrypt{$ENDIF MSWINDOWS};
     
    type
      { Forward class declarations }
      TSLTBase64 = class;
      TSLTSimpleEncrypter = class;
      TSLTAES128ECB = class;
     
      { class declarations }
     
      /// <summary>Simple encodage en Base64 pour stocker des valeurs binaires uniquement en caractères imprimables</summary>
      TSLTBase64 = class(TObject)
      public
        class function Encode(const Value: string): string;
        class function Decode(const Value: string): string;
      end;
     
      TSLTSimpleEncrypter = class(TObject)
      strict protected
        class function GetKeyData(): Pointer; virtual; abstract;
        class function GetKeySize(): Integer; virtual; abstract;
      public
        class function Encrypt(const Value: string): string; virtual; abstract;
        class function Decrypt(const Value: string): string; virtual; abstract;
      end;
      TSLTSimpleEncrypterClass = class of TSLTSimpleEncrypter;
     
      /// <summary>Chiffrement et Déchiffrement via l'algorithme AES 128 en ECB (Electronic Code Book)</summary>
      TSLTAES128ECB = class(TObject)
      public
        class function Encrypt(const Value: RawByteString; const Key: RawByteString): RawByteString;
        class function Decrypt(const Value: RawByteString; const Key: RawByteString): RawByteString;
      end;
     
      {$IFDEF DEBUG_SLT_CRYPT}
      procedure OutputDebugCRYPT(const Msg: string); inline;
      {$ENDIF DEBUG_SLT_CRYPT}
     
     
    implementation
     
    uses Soap.EncdDecd
    {$IFDEF MSWINDOWS}
      , Winapi.Windows
    {$ELSE MSWINDOWS}
    {$MESSAGE ERROR 'Implémentation uniquement Windows dans SLT.Common.Crypto'}
    {$ENDIF MSWINDOWS}
    {$IFDEF DEBUG_SLT_CRYPT}
      , SLT.Common.Tracing
    {$ENDIF DEBUG_SLT_CRYPT};
     
    { TModuleEDICryptoService }
     
    //------------------------------------------------------------------------------
    class function TSLTBase64.Decode(const Value: string): string;
    begin
      Result := Soap.EncdDecd.DecodeString(Value);
    end;
     
    //------------------------------------------------------------------------------
    class function TSLTBase64.Encode(const Value: string): string;
    begin
      Result := Soap.EncdDecd.EncodeString(Value);
    end;
     
    { TSLTAES128ECB }
     
    //------------------------------------------------------------------------------
    class function TSLTAES128ECB.Decrypt(const Value: RawByteString; const Key: RawByteString): RawByteString;
    var
      pbData: PByte;
      hCryptProvider: HCRYPTPROV;
      KeyBlob: packed record
        Header: BLOBHEADER;
        Size: DWORD;
        Data: array[0..15] of Byte;
      end;
      hKey, hDecryptKey: HCRYPTKEY;
      dwKeyCypherMode: DWORD;
      ResultLen: DWORD;
    const
      PROV_RSA_AES = 24;
      CALG_AES_128 = $0000660e;
      AESFinal = True;
    begin
      Result := '';
      // MS_ENH_RSA_AES_PROV
      if CryptAcquireContext(hCryptProvider, nil, nil, PROV_RSA_AES, CRYPT_VERIFYCONTEXT) then
      begin
        KeyBlob.Header.bType := PLAINTEXTKEYBLOB;
        keyBlob.Header.bVersion := CUR_BLOB_VERSION;
        keyBlob.Header.reserved := 0;
        keyBlob.Header.aiKeyAlg := CALG_AES_128;
        keyBlob.Size := Length(Key);
        CopyMemory(@keyBlob.Data[0], @Key[1], keyBlob.Size);
     
        if CryptImportKey(hCryptProvider, @KeyBlob, SizeOf(KeyBlob), 0, 0, hKey) then
        begin
          if CryptDuplicateKey(hKey, nil, 0, hDecryptKey) then
          begin
            dwKeyCypherMode := CRYPT_MODE_ECB;
            CryptSetKeyParam(hDecryptKey, KP_MODE, @dwKeyCypherMode, 0);
     
            Result := Value;
            pbData := Pointer(Result);
            ResultLen := Length(Result);
     
            // the calling application sets the DWORD value to the number of bytes to be decrypted. Upon return, the DWORD value contains the number of bytes of the decrypted plaintext.
            if CryptDecrypt(hDecryptKey, 0, AESFinal, 0, pbData, ResultLen) then
            begin
              SetLength(Result, ResultLen);
            end
            else
            begin
              Result := '';
              {$IFDEF DEBUG_SLT_CRYPT}
              OutputDebugCRYPT('TSLTAES128ECB.Decrypt ' + IntToStr(GetLastError()));
              {$ENDIF DEBUG_SLT_CRYPT}
            end;
     
            CryptDestroyKey(hDecryptKey);
          end;
     
          CryptDestroyKey(hKey);
        end;
     
        CryptReleaseContext(hCryptProvider, 0);
      end;
    end;
     
    //------------------------------------------------------------------------------
    class function TSLTAES128ECB.Encrypt(const Value: RawByteString; const Key: RawByteString): RawByteString;
    var
      pbData: PByte;
      hCryptProvider: HCRYPTPROV;
      KeyBlob: packed record
        Header: BLOBHEADER;
        Size: DWORD;
        Data: array[0..15] of Byte;
      end;
      hKey, hEncryptKey: HCRYPTKEY;
      dwKeyCypherMode: DWORD;
      InputLen, ResultLen: DWORD;
    const
      PROV_RSA_AES = 24;
      CALG_AES_128 = $0000660e;
      AESFinal = True;
    begin
      Result := '';
      // MS_ENH_RSA_AES_PROV
      if CryptAcquireContext(hCryptProvider, nil, nil, PROV_RSA_AES, CRYPT_VERIFYCONTEXT) then
      begin
        KeyBlob.Header.bType := PLAINTEXTKEYBLOB;
        keyBlob.Header.bVersion := CUR_BLOB_VERSION;
        keyBlob.Header.reserved := 0;
        keyBlob.Header.aiKeyAlg := CALG_AES_128;
        keyBlob.Size := Length(Key);
        CopyMemory(@keyBlob.Data[0], @Key[1], keyBlob.Size);
     
        if CryptImportKey(hCryptProvider, @KeyBlob, SizeOf(KeyBlob), 0, 0, hKey) then
        begin
          if CryptDuplicateKey(hKey, nil, 0, hEncryptKey) then
          begin
            dwKeyCypherMode := CRYPT_MODE_ECB;
            CryptSetKeyParam(hEncryptKey, KP_MODE, @dwKeyCypherMode, 0);
     
            InputLen := Length(Value);
            ResultLen := InputLen;
     
            // nil dans pbData => If this parameter contains NULL, this function will calculate the required size for the ciphertext and place that in the value pointed to by the pdwDataLen parameter.
            if CryptEncrypt(hEncryptKey, 0, AESFinal, 0, nil, ResultLen, 0) then
            begin
              SetLength(Result, ResultLen);
              Move(Value[1], Result[1], Length(Value));
              pbData := Pointer(PAnsiChar(Result));
              if not CryptEncrypt(hEncryptKey, 0, AESFinal, 0, pbData, InputLen, ResultLen) then
              begin
                Result := '';
                {$IFDEF DEBUG_SLT_CRYPT}
                OutputDebugCRYPT('TSLTAES128ECB.Encrypt ' + IntToStr(GetLastError()));
                {$ENDIF DEBUG_SLT_CRYPT}
              end;
            end
            else
            begin
              Result := '';
              {$IFDEF DEBUG_SLT_CRYPT}
              OutputDebugCRYPT('TSLTAES128ECB.Pre-Encrypt ' + IntToStr(GetLastError()));
              {$ENDIF DEBUG_SLT_CRYPT}
            end;
     
            CryptDestroyKey(hEncryptKey);
          end;
     
          CryptDestroyKey(hKey);
        end;
     
        CryptReleaseContext(hCryptProvider, 0);
      end;
    end;
     
    //------------------------------------------------------------------------------
    {$IFDEF DEBUG_SLT_CRYPT}
    procedure OutputDebugCRYPT(const Msg: string);
    begin
      TSLTDebugLogger.OutputDebugString('[SLT.CRYPT]', Msg);
    end;
    {$ENDIF DEBUG_SLT_CRYPT}
     
    end.
    Aide via F1 - FAQ - Guide du développeur Delphi devant un problème - Pensez-y !
    Attention Troll Méchant !
    "Quand un homme a faim, mieux vaut lui apprendre à pêcher que de lui donner un poisson" Confucius
    Mieux vaut se taire et paraître idiot, Que l'ouvrir et de le confirmer !
    L'ignorance n'excuse pas la médiocrité !

    L'expérience, c'est le nom que chacun donne à ses erreurs. (Oscar Wilde)
    Il faut avoir le courage de se tromper et d'apprendre de ses erreurs

  9. #9
    Membre régulier
    Homme Profil pro
    Analyse système
    Inscrit en
    Mai 2013
    Messages
    190
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Analyse système
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2013
    Messages : 190
    Points : 113
    Points
    113
    Par défaut
    Du coup j'ai essayé LockBox, j'ai donc cela, j'ai suivi cet exemple http://pasotech.altervista.org/delphi/articolo76.htm :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
     
     
    unit ExFile1;
     
    interface
     
    uses
    {$IFDEF WIN32}
      Windows,
      Messages,
      Graphics,
      Controls,
      Forms,
      Dialogs,
      StdCtrls,
      Buttons,
    {$ENDIF}
    {$IFDEF LINUX}
      QForms,
      QDialogs,
      QStdCtrls,
      QControls,
      QButtons,
    {$ENDIF}
      SysUtils,
      Classes;
     
    type
      TForm1 = class(TForm)
        btnGo: TButton;
        chkEncrypt: TCheckBox;
        procedure btnGoClick(Sender: TObject);
        function RDLEncryptStreamCBC(InStream, OutStream : TStream; Encrypt : Boolean): Boolean;
      end;
     
    var
      Form1: TForm1;
     
    const
      FileNameIn = 'test.txt';
      FileNameOut = 'test.bin';
     
    implementation
     
    {$R *.dfm}
     
    uses
      LbCipher, LbProc, LbString;
     
    type
      TEncryption = (eBf, eBfCbc, eDes, eDesCbc, e3Des, e3DesCbc, eRdl, eRdlCbc);
     
    var
      Key128           : TKey128;
     
    procedure TForm1.btnGoClick(Sender: TObject);
    var
      StreamSource: TFileStream;
      StreamTarget: TFileStream;
      OutString: string;
    begin
      Screen.Cursor := crHourglass;
      StreamSource := TFileStream.Create(FileNameIn, fmOpenRead);
      StreamTarget := TFileStream.Create(FileNameOut, fmCreate or fmOpenWrite);
     
      try
        RDLEncryptStreamCBC(StreamSource, StreamTarget, chkEncrypt.Checked);
      finally
        StreamSource.Free;
        StreamTarget.Free;
        Screen.Cursor := crDefault;
      end;
    end;
     
    function TForm1.RDLEncryptStreamCBC(InStream, OutStream : TStream; Encrypt : Boolean): Boolean;
    var
      Key        : TKey128;
      I          : LongInt;
      Block      : TRDLBlock;
      IV         : TRDLBlock;
      Work       : TRDLBlock;
      Context    : TRDLContext;
      BlockCount : LongInt;
    begin
      Result := True;
     
      {reset the streams}
      InStream.Position := 0;
      OutStream.Position := 0;
      {create a key}
      Key[0] := $06;
      Key[1] := $A9;
      Key[2] := $21;
      Key[3] := $40;
      Key[4] := $36;
      Key[5] := $B8;
      Key[6] := $A1;
      Key[7] := $5B;
      Key[8] := $51;
      Key[9] := $2E;
      Key[10] := $03;
      Key[11] := $D5;
      Key[12] := $34;
      Key[13] := $12;
      Key[14] := $00;
      Key[15] := $06;
     
      {initialize the Rijndael context}
      InitEncryptRDL(Key, sizeof(Key), Context, Encrypt);
     
      {get the number of blocks in the file}
      BlockCount := (InStream.Size div SizeOf(Block));
     
      if Encrypt then
        begin
          {set up an initialization vector (IV)}
          Block[0] := $3D;
          Block[1] := $AF;
          Block[2] := $BA;
          Block[3] := $42;
          Block[4] := $9D;
          Block[5] := $9E;
          Block[6] := $B4;
          Block[7] := $30;
          Block[8] := $B4;
          Block[9] := $22;
          Block[10] := $DA;
          Block[11] := $80;
          Block[12] := $2C;
          Block[13] := $9F;
          Block[14] := $AC;
          Block[15] := $41;
          EncryptRDL(Context, Block);
          OutStream.Write(Block, SizeOf(Block));
          IV := Block;
        end
      else
        begin
          {read the frist block to prime the IV}
          InStream.Read(Block, SizeOf(Block));
          Dec(BlockCount);
          IV := Block;
        end;
     
      {when encrypting, make sure we have a block with at least one free}
      {byte at the end. used to store the odd byte count value}
      if Encrypt then
        Inc(BlockCount);
     
      {process all except the last block}
      for I := 1 to BlockCount - 1 do
        begin
          if InStream.Read(Block, SizeOf(Block)) <> SizeOf(Block) then
            begin
              Result := False;
              Exit;
            end;
     
          if Encrypt then
            begin
              EncryptRDLCBC(Context, IV, Block);
              IV := Block;
            end
          else
            begin
              Work := Block;
              EncryptRDLCBC(Context, IV, Block);
              IV := Work;
            end;
     
          OutStream.Write(Block, SizeOf(Block));
     
          if Assigned(LbOnProgress) then
            begin
              if InStream.Position mod LbProgressSize = 0 then
                begin
                  LbOnProgress (InStream.Position, InStream.Size);
                end;
            end;
        end;
     
      if Encrypt then
        begin
          FillChar(Block, SizeOf(Block), #0);
     
          {set actual number of bytes to read}
          I := (InStream.Size mod SizeOf(Block));
          if InStream.Read(Block, I) <> I then
            begin
              Result := False;
              Exit;
            end;
     
          {store number of bytes as last byte in last block}
          PByteArray(@Block)^[SizeOf(Block)-1] := I;
     
          {encrypt and save full block}
          EncryptRDLCBC(Context, IV, Block);
          OutStream.Write(Block, SizeOf(Block));
        end
      else
        begin
          {encrypted file is always a multiple of the block size}
          if InStream.Read(Block, SizeOf(Block)) <> SizeOf(Block) then
            begin
              Result := False;
              Exit;
            end;
          EncryptRDLCBC(Context, IV, Block);
     
          {get actual number of bytes encoded}
          I := PByteArray(@Block)^[SizeOf(Block)-1];
     
          {save valid portion of block}
          OutStream.Write(Block, I);
        end;
      if Assigned(LbOnProgress) then
        begin
          LbOnProgress (InStream.Position, InStream.Size);
        end;
    end;
     
    end.
    Bon ça à l'air de bien mouliner sauf que je ne trouve pas le résultat attendu .... car je ne trouve pas la même chose avec ce générateur http://aes.online-domain-tools.com/.
    Le Block correspond bien au vecteur d'init. non ?

  10. #10
    Membre régulier
    Homme Profil pro
    Analyse système
    Inscrit en
    Mai 2013
    Messages
    190
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Analyse système
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2013
    Messages : 190
    Points : 113
    Points
    113
    Par défaut
    Pour être concret :
    En AES CBC 128 Bits

    La clé => {0x06, 0xa9, 0x21, 0x40, 0x36, 0xb8, 0xa1, 0x5b, 0x51, 0x2e, 0x03, 0xd5, 0x34, 0x12, 0x00, 0x06} (128 bits)
    l'IV => {0x3d, 0xaf, 0xba, 0x42, 0x9d, 0x9e, 0xb4, 0x30, 0xb4, 0x22, 0xda, 0x80, 0x2c, 0x9f, 0xac, 0x41} (16 octets)
    Le data = {"Single block msg"}

    Je dois trouver => {0xe3, 0x53, 0x77, 0x9c, 0x10, 0x79, 0xae, 0xb8, 0x27, 0x08, 0x94, 0x2d, 0xbe, 0x77, 0x18, 0x1a}

    et bien pour le moment aucune des solutions me retourne cela (mais je dois mal faire les choses )

  11. #11
    Membre régulier
    Homme Profil pro
    Analyse système
    Inscrit en
    Mai 2013
    Messages
    190
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Analyse système
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2013
    Messages : 190
    Points : 113
    Points
    113
    Par défaut
    J'ai trouvé !!! J'ai retiré ces deux lignes de mon Unit d'avant :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    //EncryptRDL(Context, Block);
    //OutStream.Write(Block, SizeOf(Block));
    Je suppose que la procédure EncryptRDL devait modifier mon Block en le cryptant, et OutStream.Write pour l'écrire dans le stream. Donc oui c'est bourrin en initialisant mon vecteur moi même mais fait exprès pour le bien de mon projet.
    je vous remercie une nouvelle fois de m'avoir supporté dans cette nouvelle épreuve. Donc pour résumer (sous Delphi 2007), j'ai télécharger LockBox-2-09, (je suis parti du répertoire "example/Delphi/ExFile.dpr"), et c'est tout, suffit de mettre les unités suivantes : bCipher, LbProc, LbString.

    Bon week-end de Pâques !

  12. #12
    Expert éminent sénior
    Avatar de ShaiLeTroll
    Homme Profil pro
    Développeur C++\Delphi
    Inscrit en
    Juillet 2006
    Messages
    13 455
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Seine Saint Denis (Île de France)

    Informations professionnelles :
    Activité : Développeur C++\Delphi
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2006
    Messages : 13 455
    Points : 24 867
    Points
    24 867
    Par défaut
    Bon, tu as résolu ton problème avec cette lib
    Avec les API Windows, j'obtiens bien le même résultat

    Et comme je l'ai fait autant que je l'ajoute à mon unité
    même si je sais que je gère très mal le paramètre Final de CryptEncrypt/CryptDecrypt

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    procedure TZooxxxxVCLMainForm.btn1Click(Sender: TObject);
    procedure TZooThomVCLMainForm.btn1Click(Sender: TObject);
    const
      K_KEY: array[0..15] of Byte = ($06, $a9, $21, $40, $36, $b8, $a1, $5b, $51, $2e, $03, $d5, $34, $12, $00, $06);
      K_IV: array[0..15] of Byte = ($3d, $af, $ba, $42, $9d, $9e, $b4, $30, $b4, $22, $da, $80, $2c, $9f, $ac, $41);
    var
      C, Key, IV: RawByteString;
      Hex: string;
    begin
      SetLength(Key, Length(K_KEY));
      Move(K_KEY[0], Key[1], Length(K_KEY));
      SetLength(IV, Length(K_IV));
      Move(K_IV[0], IV[1], Length(K_IV));
     
      C := SLT.Common.Crypto.TSLTAES128CBC.Encrypt('Single block msg', Key, IV); // 16 octets trop facile !
      SetLength(Hex, Length(C) * 2);
      BinToHex(PAnsiChar(@C[1]), PWideChar(@Hex[1]), Length(C));
      Memo1.Lines.Add('TSLTAES128CBC.Encrypt : ' + Hex);
     
      Memo1.Lines.Add('TSLTAES128CBC.Decrypt : ' + SLT.Common.Crypto.TSLTAES128CBC.Decrypt(C, Key, IV));
     
     
      C := SLT.Common.Crypto.TSLTAES128CBC.Encrypt('Single block msgSingle block msg', Key, IV); // 32 octets pour vérifier
      SetLength(Hex, Length(C) * 2);
      BinToHex(PAnsiChar(@C[1]), PWideChar(@Hex[1]), Length(C));
      Memo1.Lines.Add('TSLTAES128CBC.Encrypt : ' + Hex);
     
      Memo1.Lines.Add('TSLTAES128CBC.Decrypt : ' + SLT.Common.Crypto.TSLTAES128CBC.Decrypt(C, Key, IV));
     
     
      C := SLT.Common.Crypto.TSLTAES128ECB.Encrypt('Single block msgSingle block msg', Key); // 32 octets pour vérifier en ECB
      SetLength(Hex, Length(C) * 2);
      BinToHex(PAnsiChar(@C[1]), PWideChar(@Hex[1]), Length(C));
      Memo1.Lines.Add('TSLTAES128ECB.Encrypt : ' + Hex);
     
      Memo1.Lines.Add('TSLTAES128ECB.Decrypt : ' + SLT.Common.Crypto.TSLTAES128ECB.Decrypt(C, Key));
     
     
      C := SLT.Common.Crypto.TSLTAES128CBC.Encrypt('Single block msg1234567890123456', Key, IV); // 32 octets pour vérifier
      SetLength(Hex, Length(C) * 2);
      BinToHex(PAnsiChar(@C[1]), PWideChar(@Hex[1]), Length(C));
      Memo1.Lines.Add('TSLTAES128CBC.Encrypt : ' + Hex);
     
      Memo1.Lines.Add('TSLTAES128CBC.Decrypt : ' + SLT.Common.Crypto.TSLTAES128CBC.Decrypt(C, Key, IV));
     
     
      C := SLT.Common.Crypto.TSLTAES128CBC.Encrypt('Single block msg / 2 Single block msg / 3 Single block msg / 4 Single block msg = 84', Key, IV); // 84 octets pour vérifier le Final !
      SetLength(Hex, Length(C) * 2);
      BinToHex(PAnsiChar(@C[1]), PWideChar(@Hex[1]), Length(C));
      Memo1.Lines.Add('TSLTAES128CBC.Encrypt : ' + Hex);
     
      Memo1.Lines.Add('TSLTAES128CBC.Decrypt : ' + SLT.Common.Crypto.TSLTAES128CBC.Decrypt(C, Key, IV));
    end;
    cela m'affiche évidemment une clé plus grande à cause du Final à True pour la version ECB et l'on voit bien la répétition
    Pour le mode BCB, on voit bien même en répétant deux fois la même donnée, que le chiffrement par bloc est différent, preuve du bon fonctionnement du mode chainé
    le mode BCB oblige a gérer manuellement la gestion de bloc, le code implique une boucle qui n'est pas obligatoire en ECB mais rien de compliqué

    Cela donne juste ce qu'il faut aussi bien pour une donnée de la même taille/multiple que le Block/IV mais aussi pour un donnée non mulitple

    Memo1
    TSLTAES128CBC.Encrypt : E353779C1079AEB82708942DBE77181A
    TSLTAES128CBC.Decrypt : Single block msg
    TSLTAES128CBC.Encrypt : E353779C1079AEB82708942DBE77181AAE956B47632204412C1AD35F689BF0DC
    TSLTAES128CBC.Decrypt : Single block msgSingle block msg
    TSLTAES128ECB.Encrypt : 3AE00FBD31DFAEED4DA6E44FE2C11B4F3AE00FBD31DFAEED4DA6E44FE2C11B4F8B1CCC6F8CD525FFE22D6327D891A063
    TSLTAES128ECB.Decrypt : Single block msgSingle block msg
    TSLTAES128CBC.Encrypt : E353779C1079AEB82708942DBE77181A4C6FD66FA5988D34FC33EC608EE5B5A6
    TSLTAES128CBC.Decrypt : Single block msg1234567890123456
    TSLTAES128CBC.Encrypt : E353779C1079AEB82708942DBE77181AE5A7055AA4A825EA8B7FB09BF5A58B10EF87C1DA644B4244F1121B68E27421EF0E85DF6166410520403BA80CE04881EF5ED8FA1FBCB8BF920C34A7995F40CE992DD089A0
    TSLTAES128CBC.Decrypt : Single block msg / 2 Single block msg / 3 Single block msg / 4 Single block msg = 84

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
     
    //------------------------------------------------------------------------------
    (*                SoLuTions is an Versatile Library for Delphi                 -
     *                                                                             -
     *  Version alternative publiée sur "www.developpez.net"                       -
     *  Post : "AES via CryptAPI"                                                  -
     *  Post Number : 6214517                                                      -
     *  Post URL = "http://www.developpez.net/forums/d1126336/environnements-developpement/delphi/api-com-sdks/aes-via-cryptapi/#post6214517"
     *                                                                             -
     *  Copyright ou © ou Copr. "SLT Solutions", (2006)                            -
     *  contributeur : ShaiLeTroll (2012) - Renommage Fichier et Correction XE2    -
     *  contributeur : ShaiLeTroll (2012) - Documentation Insight                  -
     *                                                                             -
     * Ce logiciel est un programme informatique servant à aider les développeurs  -
     * Delphi avec une bibliothèque polyvalente, adaptable et fragmentable.        -
     *                                                                             -
     * Ce logiciel est régi par la licence CeCILL-C soumise au droit français et   -
     * respectant les principes de diffusion des logiciels libres. Vous pouvez     -
     * utiliser, modifier et/ou redistribuer ce programme sous les conditions      -
     * de la licence CeCILL-C telle que diffusée par le CEA, le CNRS et l'INRIA    -
     * sur le site "http://www.cecill.info".                                       -
     *                                                                             -
     * En contrepartie de l'accessibilité au code source et des droits de copie,   -
     * de modification et de redistribution accordés par cette licence, il n'est   -
     * offert aux utilisateurs qu'une garantie limitée.  Pour les mêmes raisons,   -
     * seule une responsabilité restreinte pèse sur l'auteur du programme,  le     -
     * titulaire des droits patrimoniaux et les concédants successifs.             -
     *                                                                             -
     * A cet égard  l'attention de l'utilisateur est attirée sur les risques       -
     * associés au chargement,  à l'utilisation,  à la modification et/ou au       -
     * développement et à la reproduction du logiciel par l'utilisateur étant      -
     * donné sa spécificité de logiciel libre, qui peut le rendre complexe à       -
     * manipuler et qui le réserve donc à des développeurs et des professionnels   -
     * avertis possédant  des  connaissances  informatiques approfondies.  Les     -
     * utilisateurs sont donc invités à charger  et  tester  l'adéquation  du      -
     * logiciel à leurs besoins dans des conditions permettant d'assurer la        -
     * sécurité de leurs systèmes et ou de leurs données et, plus généralement,    -
     * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.          -
     *                                                                             -
     * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez      -
     * pris connaissance de la licence CeCILL-C, et que vous en avez accepté les   -
     * termes.                                                                     -
     *                                                                             -
     *----------------------------------------------------------------------------*)
    unit SLT.Common.Crypto;
     
    interface
     
    {*$DEFINE DEBUG_SLT_CRYPT*}
     
    uses System.Classes, System.SysUtils
      {$IFDEF MSWINDOWS}, JwaWinCrypt{$ENDIF MSWINDOWS};
     
    type
      { Forward class declarations }
      TSLTBase64 = class;
      TSLTSimpleEncrypter = class;
      TSLTAES128ECB = class;
     
      { class declarations }
     
      /// <summary>Simple encodage en Base64 pour stocker des valeurs binaires uniquement en caractères imprimables</summary>
      TSLTBase64 = class(TObject)
      public
        class function Encode(const Value: string): string;
        class function Decode(const Value: string): string;
      end;
     
      TSLTSimpleEncrypter = class(TObject)
      strict protected
        class function GetKeyData(): Pointer; virtual; abstract;
        class function GetKeySize(): Integer; virtual; abstract;
      public
        class function Encrypt(const Value: string): string; virtual; abstract;
        class function Decrypt(const Value: string): string; virtual; abstract;
      end;
      TSLTSimpleEncrypterClass = class of TSLTSimpleEncrypter;
     
      /// <summary>Chiffrement et Déchiffrement via l'algorithme AES 128 en ECB (Electronic Code Book)</summary>
      TSLTAES128ECB = class(TObject)
      public
        class function Encrypt(const Value: RawByteString; const Key: RawByteString): RawByteString;
        class function Decrypt(const Value: RawByteString; const Key: RawByteString): RawByteString;
      end;
     
      /// <summary>Chiffrement et Déchiffrement via l'algorithme AES 128 en CBC (Cipher Block Chaining)</summary>
      TSLTAES128CBC = class(TObject)
      public
        class function Encrypt(const Value: RawByteString; const Key: RawByteString; const IV: RawByteString): RawByteString;
        class function Decrypt(const Value: RawByteString; const Key: RawByteString; const IV: RawByteString): RawByteString;
      end;
     
     
      {$IFDEF DEBUG_SLT_CRYPT}
      procedure OutputDebugCRYPT(const Msg: string); inline;
      {$ENDIF DEBUG_SLT_CRYPT}
     
     
    implementation
     
    uses Soap.EncdDecd
    {$IFDEF MSWINDOWS}
      , Winapi.Windows
    {$ELSE MSWINDOWS}
    {$MESSAGE ERROR 'Implémentation uniquement Windows dans SLT.Common.Crypto'}
    {$ENDIF MSWINDOWS}
    {$IFDEF DEBUG_SLT_CRYPT}
      , SLT.Common.Tracing
    {$ENDIF DEBUG_SLT_CRYPT};
     
    { TModuleEDICryptoService }
     
    //------------------------------------------------------------------------------
    class function TSLTBase64.Decode(const Value: string): string;
    begin
      Result := Soap.EncdDecd.DecodeString(Value);
    end;
     
    //------------------------------------------------------------------------------
    class function TSLTBase64.Encode(const Value: string): string;
    begin
      Result := Soap.EncdDecd.EncodeString(Value);
    end;
     
    { TSLTAES128ECB }
     
    //------------------------------------------------------------------------------
    class function TSLTAES128ECB.Decrypt(const Value: RawByteString; const Key: RawByteString): RawByteString;
    var
      pbData: PByte;
      hCryptProvider: HCRYPTPROV;
      KeyBlob: packed record
        Header: BLOBHEADER;
        Size: DWORD;
        Data: array[0..15] of Byte;
      end;
      hKey, hDecryptKey: HCRYPTKEY;
      dwKeyCypherMode: DWORD;
      ResultLen: DWORD;
    const
      PROV_RSA_AES = 24;
      CALG_AES_128 = $0000660e;
      AESFinal = True;
    begin
      Result := '';
      // MS_ENH_RSA_AES_PROV
      if CryptAcquireContext(hCryptProvider, nil, nil, PROV_RSA_AES, CRYPT_VERIFYCONTEXT) then
      begin
        KeyBlob.Header.bType := PLAINTEXTKEYBLOB;
        keyBlob.Header.bVersion := CUR_BLOB_VERSION;
        keyBlob.Header.reserved := 0;
        keyBlob.Header.aiKeyAlg := CALG_AES_128;
        keyBlob.Size := Length(Key);
        CopyMemory(@keyBlob.Data[0], @Key[1], keyBlob.Size);
     
        if CryptImportKey(hCryptProvider, @KeyBlob, SizeOf(KeyBlob), 0, 0, hKey) then
        begin
          if CryptDuplicateKey(hKey, nil, 0, hDecryptKey) then
          begin
            dwKeyCypherMode := CRYPT_MODE_ECB;
            CryptSetKeyParam(hDecryptKey, KP_MODE, @dwKeyCypherMode, 0);
     
            Result := Value;
            pbData := Pointer(Result);
            ResultLen := Length(Result);
     
            // the calling application sets the DWORD value to the number of bytes to be decrypted. Upon return, the DWORD value contains the number of bytes of the decrypted plaintext.
            if CryptDecrypt(hDecryptKey, 0, AESFinal, 0, pbData, ResultLen) then
            begin
              SetLength(Result, ResultLen);
            end
            else
            begin
              Result := '';
              {$IFDEF DEBUG_SLT_CRYPT}
              OutputDebugCRYPT('TSLTAES128ECB.Decrypt ' + IntToStr(GetLastError()));
              {$ENDIF DEBUG_SLT_CRYPT}
            end;
     
            CryptDestroyKey(hDecryptKey);
          end;
     
          CryptDestroyKey(hKey);
        end;
     
        CryptReleaseContext(hCryptProvider, 0);
      end;
    end;
     
    //------------------------------------------------------------------------------
    class function TSLTAES128ECB.Encrypt(const Value: RawByteString; const Key: RawByteString): RawByteString;
    var
      pbData: PByte;
      hCryptProvider: HCRYPTPROV;
      KeyBlob: packed record
        Header: BLOBHEADER;
        Size: DWORD;
        Data: array[0..15] of Byte;
      end;
      hKey, hEncryptKey: HCRYPTKEY;
      dwKeyCypherMode: DWORD;
      InputLen, ResultLen: DWORD;
    const
      PROV_RSA_AES = 24;
      CALG_AES_128 = $0000660e;
      AESFinal = True;
    begin
      Result := '';
      // MS_ENH_RSA_AES_PROV
      if CryptAcquireContext(hCryptProvider, nil, nil, PROV_RSA_AES, CRYPT_VERIFYCONTEXT) then
      begin
        KeyBlob.Header.bType := PLAINTEXTKEYBLOB;
        keyBlob.Header.bVersion := CUR_BLOB_VERSION;
        keyBlob.Header.reserved := 0;
        keyBlob.Header.aiKeyAlg := CALG_AES_128;
        keyBlob.Size := Length(Key);
        CopyMemory(@keyBlob.Data[0], @Key[1], keyBlob.Size);
     
        if CryptImportKey(hCryptProvider, @KeyBlob, SizeOf(KeyBlob), 0, 0, hKey) then
        begin
          if CryptDuplicateKey(hKey, nil, 0, hEncryptKey) then
          begin
            dwKeyCypherMode := CRYPT_MODE_ECB;
            CryptSetKeyParam(hEncryptKey, KP_MODE, @dwKeyCypherMode, 0);
     
            InputLen := Length(Value);
            ResultLen := InputLen;
     
            // nil dans pbData => If this parameter contains NULL, this function will calculate the required size for the ciphertext and place that in the value pointed to by the pdwDataLen parameter.
            if CryptEncrypt(hEncryptKey, 0, AESFinal, 0, nil, ResultLen, 0) then
            begin
              SetLength(Result, ResultLen);
              Move(Value[1], Result[1], Length(Value));
              pbData := Pointer(PAnsiChar(Result));
              if not CryptEncrypt(hEncryptKey, 0, AESFinal, 0, pbData, InputLen, ResultLen) then
              begin
                Result := '';
                {$IFDEF DEBUG_SLT_CRYPT}
                OutputDebugCRYPT('TSLTAES128ECB.Encrypt ' + IntToStr(GetLastError()));
                {$ENDIF DEBUG_SLT_CRYPT}
              end;
            end
            else
            begin
              Result := '';
              {$IFDEF DEBUG_SLT_CRYPT}
              OutputDebugCRYPT('TSLTAES128ECB.Pre-Encrypt ' + IntToStr(GetLastError()));
              {$ENDIF DEBUG_SLT_CRYPT}
            end;
     
            CryptDestroyKey(hEncryptKey);
          end;
     
          CryptDestroyKey(hKey);
        end;
     
        CryptReleaseContext(hCryptProvider, 0);
      end;
    end;
     
    //------------------------------------------------------------------------------
    {$IFDEF DEBUG_SLT_CRYPT}
    procedure OutputDebugCRYPT(const Msg: string);
    begin
      TSLTDebugLogger.OutputDebugString('[SLT.CRYPT]', Msg);
    end;
    {$ENDIF DEBUG_SLT_CRYPT}
     
    { TSLTAES128CBC }
     
    //------------------------------------------------------------------------------
    class function TSLTAES128CBC.Decrypt(const Value: RawByteString; const Key: RawByteString; const IV: RawByteString): RawByteString;
    var
      pbData, pbEnd: PByte;
      hCryptProvider: HCRYPTPROV;
      KeyBlob: packed record
        Header: BLOBHEADER;
        Size: DWORD;
        Data: array[0..15] of Byte;
      end;
      hKey, hDecryptKey: HCRYPTKEY;
      dwKeyCypherMode: DWORD;
      ResultLen: DWORD;
    const
      PROV_RSA_AES = 24;
      CALG_AES_128 = $0000660e;
      AESFinal = False;
    begin
      Result := '';
      // MS_ENH_RSA_AES_PROV
      if CryptAcquireContext(hCryptProvider, nil, nil, PROV_RSA_AES, CRYPT_VERIFYCONTEXT) then
      begin
        KeyBlob.Header.bType := PLAINTEXTKEYBLOB;
        keyBlob.Header.bVersion := CUR_BLOB_VERSION;
        keyBlob.Header.reserved := 0;
        keyBlob.Header.aiKeyAlg := CALG_AES_128;
        keyBlob.Size := Length(Key);
        CopyMemory(@keyBlob.Data[0], @Key[1], keyBlob.Size);
     
        if CryptImportKey(hCryptProvider, @KeyBlob, SizeOf(KeyBlob), 0, 0, hKey) then
        begin
          if CryptDuplicateKey(hKey, nil, 0, hDecryptKey) then
          begin
            dwKeyCypherMode := CRYPT_MODE_CBC;
            CryptSetKeyParam(hDecryptKey, KP_MODE, @dwKeyCypherMode, 0);
            CryptSetKeyParam(hDecryptKey, KP_IV, @IV[1], 0);
     
            Result := Value;
            pbData := Pointer(Result);
            pbEnd := pbData + Length(Value);
            // La taille de bloc sera pour simplifier la taille du vecteur d'initialisation
            ResultLen := Length(IV);
     
            while (pbData < pbEnd) and (Length(Result) > 0) do
            begin
              // the calling application sets the DWORD value to the number of bytes to be decrypted. Upon return, the DWORD value contains the number of bytes of the decrypted plaintext.
              if not CryptDecrypt(hDecryptKey, 0, AESFinal, 0, pbData, ResultLen) then
              begin
                Result := '';
                {$IFDEF DEBUG_SLT_CRYPT}
                OutputDebugCRYPT('TSLTAES128CBC.Decrypt ' + IntToStr(GetLastError()));
                {$ENDIF DEBUG_SLT_CRYPT}
     
              end;
     
              Inc(pbData, Length(IV));
            end;
     
            CryptDestroyKey(hDecryptKey);
          end;
     
          CryptDestroyKey(hKey);
        end;
     
        CryptReleaseContext(hCryptProvider, 0);
      end;
    end;
     
    //------------------------------------------------------------------------------
    class function TSLTAES128CBC.Encrypt(const Value: RawByteString; const Key: RawByteString; const IV: RawByteString): RawByteString;
    var
      pbData, pbEnd: PByte;
      hCryptProvider: HCRYPTPROV;
      KeyBlob: packed record
        Header: BLOBHEADER;
        Size: DWORD;
        Data: array[0..15] of Byte;
      end;
      hKey, hEncryptKey: HCRYPTKEY;
      dwKeyCypherMode: DWORD;
      ResultLen: DWORD;
    const
      PROV_RSA_AES = 24;
      CALG_AES_128 = $0000660e;
      AESFinal = False;
    begin
      Result := '';
      // MS_ENH_RSA_AES_PROV
      if CryptAcquireContext(hCryptProvider, nil, nil, PROV_RSA_AES, CRYPT_VERIFYCONTEXT) then
      begin
        KeyBlob.Header.bType := PLAINTEXTKEYBLOB;
        keyBlob.Header.bVersion := CUR_BLOB_VERSION;
        keyBlob.Header.reserved := 0;
        keyBlob.Header.aiKeyAlg := CALG_AES_128;
        keyBlob.Size := Length(Key);
        CopyMemory(@keyBlob.Data[0], @Key[1], keyBlob.Size);
     
        if CryptImportKey(hCryptProvider, @KeyBlob, SizeOf(KeyBlob), 0, 0, hKey) then
        begin
          if CryptDuplicateKey(hKey, nil, 0, hEncryptKey) then
          begin
            dwKeyCypherMode := CRYPT_MODE_CBC;
            CryptSetKeyParam(hEncryptKey, KP_MODE, @dwKeyCypherMode, 0);
            CryptSetKeyParam(hEncryptKey, KP_IV, @IV[1], 0);
     
            Result := Value;
            pbData := Pointer(Result);
            pbEnd := pbData + Length(Value);
            // La taille de bloc sera pour simplifier la taille du vecteur d'initialisation
            ResultLen := Length(IV);
     
            while (pbData < pbEnd) and (Length(Result) > 0) do
            begin
              // the calling application sets the DWORD value to the number of bytes to be decrypted. Upon return, the DWORD value contains the number of bytes of the decrypted plaintext.
              if not CryptEncrypt(hEncryptKey, 0, AESFinal, 0, pbData, ResultLen, pbEnd - pbData) then
              begin
                Result := '';
                {$IFDEF DEBUG_SLT_CRYPT}
                OutputDebugCRYPT('TSLTAES128CBC.Encrypt ' + IntToStr(GetLastError()));
                {$ENDIF DEBUG_SLT_CRYPT}
              end;
     
              Inc(pbData, Length(IV));
            end;
     
            CryptDestroyKey(hEncryptKey);
          end;
     
          CryptDestroyKey(hKey);
        end;
     
        CryptReleaseContext(hCryptProvider, 0);
      end;
    end;
     
    end.
    Aide via F1 - FAQ - Guide du développeur Delphi devant un problème - Pensez-y !
    Attention Troll Méchant !
    "Quand un homme a faim, mieux vaut lui apprendre à pêcher que de lui donner un poisson" Confucius
    Mieux vaut se taire et paraître idiot, Que l'ouvrir et de le confirmer !
    L'ignorance n'excuse pas la médiocrité !

    L'expérience, c'est le nom que chacun donne à ses erreurs. (Oscar Wilde)
    Il faut avoir le courage de se tromper et d'apprendre de ses erreurs

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Python 3.2 - Cryptage symétrique AES en mode CBC
    Par jeby6372 dans le forum Général Python
    Réponses: 26
    Dernier message: 02/02/2014, 18h25
  2. [Algo] AES - Algorithme détaillé
    Par Khorne dans le forum Algorithmes et structures de données
    Réponses: 8
    Dernier message: 31/12/2008, 12h35
  3. [C#] AES - CBC - PKCS5Padding
    Par mioux dans le forum ASP.NET
    Réponses: 2
    Dernier message: 02/10/2007, 09h37
  4. AES / Détails.
    Par etranger dans le forum Algorithmes et structures de données
    Réponses: 2
    Dernier message: 09/05/2005, 23h08
  5. Standard cryptographique AES et licence d'utilisation
    Par KORTA dans le forum Algorithmes et structures de données
    Réponses: 6
    Dernier message: 24/09/2003, 13h33

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo