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

Réseau/Web Python Discussion :

Problème chiffrement Blowfish


Sujet :

Réseau/Web Python

  1. #1
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Mars 2014
    Messages
    14
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Mars 2014
    Messages : 14
    Points : 19
    Points
    19
    Par défaut Problème chiffrement Blowfish
    Bonjour,

    Je dois pour mon stage faire un projet pour chiffrer des messages, j'utilise l'algo de chiffrement BlowFish.

    Mais j'ai du mal a le mettre en oeuvre.

    Si quelqu'un peut m'aider cela serait sympa, merci.

    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
     
    # -*- coding: utf-8 -*-
     
     
    from datetime import datetime
    from struct import pack, unpack
    from Crypto.Cipher import Blowfish
    import binascii
     
    class Entry:
        ENTRY_SIZE = 22
        DATA_SIZE = 12
        def __init__(self, timestamp=0, data="", entete = "", signal=0):
            '''
            @param timestamp: the date of reception of the data
            @param data: data received from Sigfox
            @param signal: the strangth of the signal, 0 means unknown
            '''
            self.time        = datetime.fromtimestamp(timestamp)
            self.pressure    = 0
            self.temperature = 0
            self.humidity    = 0
            self.external    = 0
            self.external2   = 0
            self.external3   = 0
            self.data        = data
            self.entete      = entete
            self.signal      = signal
     
     
        def init(self, time, p, t, h, e, signal):
            self.data = ""
            self.time = datetime.fromtimestamp(time)
            self.pressure = p
            self.temperature = t
            self.humidity = h
            self.external = e
            self.signal = signal
     
        def init2(self, time, p, t, h, e, e2, signal):
            self.data = ""
            self.time = datetime.fromtimestamp(time)
            self.pressure = p
            self.temperature = t
            self.humidity = h
            self.external = e
            self.external2 = e2
            self.signal = signal
     
     
    #Partie de chiffrement : BlowFish
     
    #Variable glocal c1  et key
     
     
    def PKCS5Padding(string):
        byteNum = len(string)
        packingLength = 8 - byteNum % 8
        appendage = chr(packingLength) * packingLength
        return string + appendage
     
    def PandoraEncrypt(string):
        key = b'6#26FRL$ZWD'
        c1  = Blowfish.new(key, Blowfish.MODE_ECB)
        packedString = PKCS5Padding(string)
        return c1.encrypt(packedString)
     
    def PandoraDecrypt(string):
        key = b'6#26FRL$ZWD'
        c1  = Blowfish.new(key, Blowfish.MODE_ECB)
        return c1.decrypt(string)
    if __name__ == '__main__':
        s = 'testings'
        data_encrypted= PandoraEncrypt(s)
        data_decrypted = PandoraDecrypt(s)
        print(binascii.hexlify(data_encrypted))
        print(binascii.hexlify(data_decrypted))
        assert data_decrypted == s
     
        def pack(self):
          '''
            @pre  : L'année en cours est inférieur à 2106 (timestamp sur 32 bits) et data fait 12 chars
            @post : On renvoie 20 chars
            @note : Format :  5 bits p  --  6 bits t  --  5 bits h  --  32 bits e, en hexadécimal
          '''
          assert len(self.data) == Entry.DATA_SIZE, "Entry data should be 12 char long."
          entryData = "%8s" % hex(int(self.time.strftime("%s")))[2:].zfill(8)+self.data+hex(int(self.signal*2.5))[2:].zfill(2)
          assert len(entryData) == Entry.ENTRY_SIZE, "Packed entry data should be 22 char long and not %d" % len(entryData)
          return entryData

  2. #2
    Expert éminent
    Avatar de tyrtamos
    Homme Profil pro
    Retraité
    Inscrit en
    Décembre 2007
    Messages
    4 462
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Var (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Retraité

    Informations forums :
    Inscription : Décembre 2007
    Messages : 4 462
    Points : 9 249
    Points
    9 249
    Billets dans le blog
    6
    Par défaut
    Bonjour,

    Je n'ai pas une compétence suffisante sur le sujet pour te répondre, mais j'ai au moins un conseil: pose des questions plus précises sur ce que tu ne sais pas faire, et montre un petit code de 10 ou 20 lignes maxi qui ne traite que de ça.

    Pour l'instant, on a un code déjà élaboré de 89 lignes, et on ne sait pas ce qui coince...
    Un expert est une personne qui a fait toutes les erreurs qui peuvent être faites, dans un domaine étroit... (Niels Bohr)
    Mes recettes python: http://www.jpvweb.com

  3. #3
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Mars 2014
    Messages
    14
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Mars 2014
    Messages : 14
    Points : 19
    Points
    19
    Par défaut
    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
    
    
    #Partie de chiffrement : BlowFish
     
    #Variable glocal c1  et key
     
     
    def PKCS5Padding(string):
        byteNum = len(string)
        packingLength = 8 - byteNum % 8
        appendage = chr(packingLength) * packingLength
        return string + appendage
     
    def PandoraEncrypt(string):
        key = b'6#26FRL$ZWD'
        c1  = Blowfish.new(key, Blowfish.MODE_ECB)
        packedString = PKCS5Padding(string)
        return c1.encrypt(packedString)
     
    def PandoraDecrypt(string):
        key = b'6#26FRL$ZWD'
        c1  = Blowfish.new(key, Blowfish.MODE_ECB)
        return c1.decrypt(string)
    if __name__ == '__main__':
    
    #Voila ce qui coince
        s = 'testings'
        data_encrypted= PandoraEncrypt(s)
        data_decrypted = PandoraDecrypt(s)
        print(binascii.hexlify(data_encrypted))
        print(binascii.hexlify(data_decrypted))
        assert data_decrypted == s
    Quand je compile le fichier .py ca me donne ce type erreur erreur :

    python entry.py
    223950ff19fbea872fce0ee543692ba7
    fac4f55b0ca0dd77
    Traceback (most recent call last):
    File "entry.py", line 79, in <module>
    assert data_encrypted == s
    AssertionError



    J'y comprend rien....

  4. #4
    Expert éminent sénior
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 287
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 287
    Points : 36 776
    Points
    36 776
    Par défaut
    Salut,

    Si vous écrivez:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
        s = 'testings'
        data_encrypted= PandoraEncrypt(s)
        data_decrypted = PandoraDecrypt(s)
        print(binascii.hexlify(data_encrypted))
        print(binascii.hexlify(data_decrypted))
        assert data_decrypted == s
    je ne vois pas pourquoi çà devrait fonctionner (relisez plus attentivement votre code, surtout la 3ème ligne).
    Puis il faut traiter le padding (dans PandoraDecrypt) avant de pouvoir comparer.

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  5. #5
    Expert éminent
    Avatar de tyrtamos
    Homme Profil pro
    Retraité
    Inscrit en
    Décembre 2007
    Messages
    4 462
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Var (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Retraité

    Informations forums :
    Inscription : Décembre 2007
    Messages : 4 462
    Points : 9 249
    Points
    9 249
    Billets dans le blog
    6
    Par défaut
    Je suis loin d'être spécialiste de ces questions, mais comme je suis curieux , voilà un petit code qui a l'air de fonctionner.

    Il a l'air assez simple, et j'ai commenté les opérations:

    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
    #!/usr/bin/python3
    # -*- coding: utf-8 -*-
    # Python 3
     
    from Crypto.Cipher import Blowfish
    import binascii
     
    def bencrypt(chb, key):
        """encrypte la chaine (type bytes) chb avec la clé key (type bytes)
        """
        bs = Blowfish.block_size
        chb += b" "*(bs-len(chb)%bs) # ajustement de la longueur en ajoutant des espaces
        cb = Blowfish.new(key, Blowfish.MODE_ECB)
        return cb.encrypt(chb)
     
    def bdecrypt(chb, key):
        """décrypte la chaine (type bytes) chb avec la clé key (type bytes)
        """
        cb = Blowfish.new(key, Blowfish.MODE_ECB)
        return cb.decrypt(chb)
     
     
    #texte type str encodé utf-8
    texte = "Que j'aime à faire apprendre ce nombre utile aux sages"
    print(texte)
     
    # suppression d'éventuels espaces terminaux
    texte = texte.rstrip()
     
    # conversion en bytes
    texteb = bytes(texte, "utf-8")
     
    # clé type bytes (a priori de longueur divisible par Blowfish.block_size)
    key = b"abcdefghijklmnop"
     
    # encryptage du texte (type bytes) avec la clé key (type bytes)
    textebcrypt = bencrypt(texteb, key)
     
    # conversion en hexa pour envoi au destinataire
    textehexa = binascii.hexlify(textebcrypt)
    print(textehexa)
     
    #...............................
     
    # retrouver le texte crypté à partir de l'hexa
    textebcrypt2 =  binascii.unhexlify(textehexa)
     
    # décryptage du texte avec la (même!) clé
    texteb2 = bdecrypt(textebcrypt2, key)
     
    # retrouver le texte en str encodée utf-8
    texte2 = str(texteb2, "utf-8")
     
    # retirer les éventuels espaces terminaux
    texte2 = texte2.rstrip()
     
    print(texte2==texte)
    Ce qui donne:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    Que j'aime à faire apprendre ce nombre utile aux sages
    b'05213d49e0ad8c5b91ca851835740a266429c8521352b9ab00b4b0c3e2d216733574c0ce9dbe6f468667dd0c47965ee9dc501967e07b1a7a'
    True
    Un expert est une personne qui a fait toutes les erreurs qui peuvent être faites, dans un domaine étroit... (Niels Bohr)
    Mes recettes python: http://www.jpvweb.com

  6. #6
    Expert éminent sénior
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 287
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 287
    Points : 36 776
    Points
    36 776
    Par défaut
    Citation Envoyé par tyrtamos Voir le message
    Je suis loin d'être spécialiste de ces questions, mais comme je suis curieux , voilà un petit code qui a l'air de fonctionner.
    Excepté la gestion du padding, le code posté par le PO fonctionne très bien (modulo un peu de rigueur quant à son utilisation).

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

Discussions similaires

  1. problème cryptage blowfish
    Par xokami35x dans le forum Sécurité
    Réponses: 10
    Dernier message: 25/02/2010, 09h29
  2. Problème de chiffrement implicit SSL/TLS avec VSFTPD !
    Par djskynet dans le forum Réseau
    Réponses: 0
    Dernier message: 05/09/2009, 02h58
  3. Problème cryptage Blowfish
    Par Nicoclem dans le forum Composants VCL
    Réponses: 2
    Dernier message: 12/03/2009, 15h26
  4. Problème avec blowfish et OpenSSL
    Par HacKSpideR dans le forum C
    Réponses: 6
    Dernier message: 01/03/2009, 20h46
  5. problème avec blowfish
    Par Hydre dans le forum Sécurité
    Réponses: 2
    Dernier message: 19/10/2005, 12h35

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