Annonce

Réduire
Aucune annonce.

Crypter Vigenère Python

Réduire
X
 
  • Filtre
  • Heure
  • Afficher
Tout nettoyer
nouveaux messages

  • Crypter Vigenère Python

    Bonjour voici un code fait maison sur le cryptage de Vigenère

    Code:
    from operator import add, sub
    from string import ascii_lowercase as alphabet
    from itertools import cycle
    
    DICO_ALPHA = {letter: ord(letter)-97 for letter in alphabet}
    
    # {'b': 1, 'c': 2, 'a': 0, 'f': 5, 'g': 6, 'd': 3, 'e': 4, 'j': 9, 'k': 10, 'h': 7, 'i': 8, 'n': 13, 'o': 14, 'l': 11, 'm': 12, 'r': 17, 's': 18, 'p': 15, 'q': 16, 'v': 21, 'w': 22, 't': 19, 'u': 20, 'z': 25, 'x': 23, 'y': 24}
    
    DICO_NUMBER = {k:v for v, k in DICO_ALPHA.items()}
    
    # {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h', 8: 'i', 9: 'j', 10: 'k', 11: 'l', 12: 'm', 13: 'n', 14: 'o', 15: 'p', 16: 'q', 17: 'r', 18: 's', 19: 't', 20: 'u', 21: 'v', 22: 'w', 23: 'x', 24: 'y', 25: 'z'}
    
    def cypher(text, key, func='encrypt'):
        text = text.lower()
        res = ''
        ind = 0
        ind_max = len(text)
    
        if func == 'encrypt':
            op = add # add two numbers
        else:
            op = sub # subtract two numbers
        
        for letter in cycle(key):
            n = op(DICO_ALPHA[text[ind]], DICO_ALPHA[letter]) % 26
            res += DICO_NUMBER[n]
            ind += 1
            if ind == ind_max:
                break
        return res.upper() # string uppercase
    
    print(cypher('azertyuiop', 'sdhgf')) # encrypt by default
    # SCLXYQXPUU
    
    print(cypher('SCLXYQXPUU', 'sdhgf', 'decrypt')) # decrypt
    # AZERTYUIOP
    à bientôt,
    Dernière modification par fred, 08 octobre 2013, 22h01.
Chargement...
X