crypto1.py

Created by dan-wallez

Created on August 08, 2020

8.62 KB

Codage de Hill : Pour plus de confort paramétrer police python à petit dans paramètres. Les mots entrés doivent être en MAJ. Fonction hillg( ) g comme génération automatique (de manière aléatoire)de la matrice clé de codage de taille n x n (n est à saisir au delà de la taille 6 cela prend du temps touche return pour stopper) puis détermination de la matrice de décodage. Saisissez un mot en MAJ. Après saisie du mot le codage s’exécute suivi du décodage de ce mot codé afin de retrouver le mot origine (si le mot n’est pas un multiple de n il est complété par le caractère Z). Fonction hills( ) s comme saisie : Codage de Hill avec saisie de la matrice codage et détermination par programme de la matrice décodage : hills(). Attention toutes les matrices carrées ne sont pas compatibles, vous pouvez utiliser une matrice générée par hillg() pour sortir saisir le caractère O comme indiqué.

Codage RSA : Pour plus de confort paramétrer police python à petit dans paramètres. Fonction rsa() : Codage RSA, il faut entrer 2 nombres premiers puis le message (tous les caractères sont acceptés) le message codé est sous forme d’une liste de nombres que vous pouvez consulter puis pour vérification il y a décodage pour retrouver le message initial.


from math import *

from random import *



def gcdw(a,b):

    a = int(fabs(a))

    b = int(fabs(b))

    r = 1

    if a % b == 0 :

        return b

    else :

        while r > 0 :

            r = a % b

            a = b

            b = r

        return a

    

def genematrice(t): # génération d'une matrice t x t

    m = []

    for ligne in range(t):

        m.append([])

        for colonne in range(t):

            m[ligne].append(randint(0, 25))

    return m



def deter(m):  # déterminant d'une matrice carrée m

    det = 0

    if len(m) == 1 :

        det = m[0][0]

    elif len(m) == 2 :

        det = m[0][0]*m[1][1] - m[1][0]*m[0][1]

    else :

        for c in range(len(m)):

            mm = []

            k = 0

            for i in range(1, len(m)):

                mm.append([])

                for j in range(0, c) :

                    mm[k].append(m[i][j])

                for j in range(c+1, len(m)) :            

                    mm[k].append(m[i][j])

                k += 1

            det = det + (((-1)**c) * m[0][c] * deter(mm))

    return det



def produit_mat(mata, matb, t):  # produit de 2 matrices carrées  

    matab = []    

    for i in range(t) :

        coeff = 0

        for x in range(t):             

            coeff += int(mata[i][x])* int(matb[x])

        matab.append(coeff)

    return matab



def comatrice(m):  # comatrice d'une matrice carrée  

    n = len(m)

    com = []

    for a in range(n) :

        com.append([])

        for b in range(n) :

            k = 0

            mm = []

            for i in range(a) :

                mm.append([])

                for j in range(b):

                    mm[k].append(m[i][j])

                for j in range(b+1,n):

                    mm[k].append(m[i][j])

                k += 1

            for i in range(a+1,n) :

                mm.append([])

                for j in range(b):

                    mm[k].append(m[i][j])

                for j in range(b+1,n):

                    mm[k].append(m[i][j])

                k += 1

            com[a].append(deter(mm) * ((-1) ** (a + b)))

    return com



def transposee(m):  # transposee d'une matrice

    n = len(m)

    transp = []

    for a in range(n) :

        transp.append([])

        for b in range(n) :

            transp[a].append(m[b][a])

    return transp



def valk(x) :

    for k in range(26) :

        if (k * x) % 26 == 1 :

            return k



def mhill(m, k): # matrice de décodage hill

    matdec = []

    for i in range(len(m)):

        matdec.append([])

        for j in range(len(m)):

            matdec[i].append((m[i][j] * k) % 26)

    return matdec



def codageh(mot, mmm, t):# codage hill     

    matx = []   

    for i in range(len(mot)):

        matx.append(ord(mot[i]) - ord("A"))

    print ("Les lettres du mot sont",matx)        

    mot_code = ""

    i = 0

    while i+t < len(mot)+1 :

        xxx = []

        for j in range (i,i+t):

            xxx.append(matx[j])

        glcode = produit_mat(mmm, xxx, t)

        for s in range (t):

            mot_code = mot_code + chr(((glcode[s]) % 26) + ord("A"))

        i += t

    return mot_code



def decompose(n):   # code numworks extrait de la fction factor(n)

  L=[]

  div=2

  while n>1 :

    if n%div==0:

      L.append(div)

      n=n/div

    else:

      div=div+1

  return L



def bezoutdw(a,b):  # utilisation de Bezout pour codage rsa

                    # seule une valeur retournee est necessaire

    bb = b

    r, u, v, x, y = 1, 1, 0, 0, 1

    while r > 0:

        q = a // b

        if b < 0 and q != a/b :

            q += 1

        r = a - b*q

        a = b

        b = r

        s = u - x*q

        u = x

        x = s

        t = v - q*y

        v = y

        y = t



    ii = 0   # attention u retourne doit etre positif

    u += ii*bb

    while u <= 0 :

        ii += 1

        u += ii*bb

    return u



def transf(x,k,n):

# retourne le reste de la division euclidienne

# de x puissance k par n

# exemple : transf(2,7,5) = reste de ( 2 puiss 7 / 5 )

#          = reste de (128 / 5) = 3

    reste = 1

    while k > 0 :

        if k % 2 != 0 :

            reste = (reste*x) % n

        x = x*x % n

        k = k // 2

    return reste



   

######  PROGRAMMES PRINCIPAUX   #####################



def hillg():   # génère des matrices clés codage de hill

    

    #  GENERATION DE LA MATRICE DE CODAGE



    t = eval(input("Taille matrice codage n x n = "))



    detm = 0     

    while ((detm == 0) or (gcdw(abs(detm),26) != 1)) :

        matcod = genematrice(t)

        detm = deter(matcod)

        

    print ("Matrice de codage =")

    print ("")

    for p in range(t) :

        print(matcod[p])



    #  DETERMINATION DE LA MATRICE DE DECODAGE



    print ("\nDeter de matrice codage =",detm)



    k = valk(detm)

    matdec = mhill(transposee(comatrice(matcod)),k)



    print ("\nMatrice de décodage =")

    print ("")

    for p in range(t) :

        print(matdec[p])

    print ("")

        

    # SAISIE DU MOT A CODER ET VERIFICATION DE LA MATRICE DE DECODAGE



    motx = input("mot (en MAJ) = ")

    if (len(motx) % t) != 0 :

        acomp = t - (len(motx) % t)

    else :

        acomp = 0 

    for i in range(acomp):

        motx = motx + "Z"



    print ("Mot à coder :",motx)

    moty = codageh(motx, matcod, t)

    print ("Mot codé :", moty)

    motorigine = codageh(moty, matdec, t)

    print ("Mot origine :",motorigine)



def hills() :   #  codage de hill après saisie d'une matrice clé



    #  SAISIE DE LA MATRICE DE CODAGE



    t = eval(input("Taille matrice codage n x n = "))



    matcod = []   

    for i in range(t):

     matcod.append([])    

     for j in range(t):

      x = eval(input("a"+str(i+1)+str(j+1)+" = "))

      matcod[i].append(x)



    detm = deter(matcod)

    print ("")    

    print ("Matrice de codage =")

    for p in range(t) :

        print(matcod[p])



    if gcdw(abs(detm),26) != 1 :

        print ("Determinant =",detm)

        print ("PB : pgcd(26,", detm, ") diff de 1")

        

    else :

        #  DETERMINATION DE LA MATRICE DE DECODAGE



        k = valk(detm)

        matdec = mhill(transposee(comatrice(matcod)),k)

      

        print ("\nMatrice de décodage =")

        for p in range(t) :

            print(matdec[p])

        print ("")

            

        # SAISIE DU MOT A CODER ET CODAGE PUIS DECODAGE



        reponse = 'n'

        while reponse != 'O':

            motx = input("mot (en MAJ) = ")

            if (len(motx) % t) != 0 :

                acomp = t - (len(motx) % t)

            else :

                acomp = 0 

            for i in range(acomp):

                motx = motx + "Z"

            print ("\nMot à coder :",motx)

            moty = codageh(motx, matcod, t)

            print ("Mot codé :", moty)    

            motorigine = codageh(moty, matdec, t)

            print ("Mot origine :",motorigine)

            print ("\nFin? oui : saisir O")

            print ("Autre caractère sinon")

            reponse = input("Réponse ? ")



    print("\nAu revoir")



def rsa():    #   codage rsa

    

    p = int(input("Nbre premier p = "))

    decompose_nbre = decompose(p)

    while len(decompose_nbre) > 1 :

        print ("p non premier")

        print ("Ce nbre se décompose suivant ", decompose_nbre)

        p = int(input("Nbre premier p = "))

        decompose_nbre = decompose(p)

          

    q = int(input("Nbre premier q = "))

    decompose_nbre = decompose(q)

    while len(decompose_nbre) > 1 :

        print ("q non premier")

        print ("Ce nbre se décompose suivant ", decompose_nbre)

        q = int(input("Nbre premier q = "))

        decompose_nbre = decompose(q)



    n = p*q

    print ("n = pq =", n)



    phiden = (p-1)*(q-1)



    if p < q :

        c = q+1

    else :

        c = p+1

    while gcdw(phiden,c) != 1 :

        c += 1

    print ("Clé codage =",c)



    d = bezoutdw(c,phiden)

    print ("Clé décodage =",d)



    messagec = input("Message = ")



    listemessagec = []   

    for i in range(len(messagec)):

        listemessagec.append(ord(messagec[i]))



    listevalc = []   

    for i in range(len(listemessagec)):

        listevalc.append(transf(listemessagec[i],c,n))

    

    print ("\nValeurs codage des lettres du message :",listevalc)



    listevald = []   

    for i in range(len(listevalc)):

        listevald.append(transf(listevalc[i],d,n))



    message_origine = ""

    for i in range (len(listevald)):

        message_origine += chr(listevald[i])



    print ("\nMessage origine :",message_origine)







            

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.