Nantes Université

Skip to content
Extraits de code Groupes Projets
Valider 6b2cfbce rédigé par E214194U's avatar E214194U
Parcourir les fichiers

maj

parent 6d2439f8
Aucune branche associée trouvée
Aucune étiquette associée trouvée
Aucune requête de fusion associée trouvée
Fichier ajouté
import math
import string
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import json
import unidecode
alphabet=string.ascii_lowercase
ALPHABET=string.ascii_uppercase
def is_upper(x):
for i in ALPHABET:
if x==i:
return True
return False
def caesar_crypt(msg,decal):
new_alphabet=alphabet[decal:]+alphabet[:decal]
new_ALPHABET=ALPHABET[decal:]+ALPHABET[:decal]
msg_crypt=""
for i in msg :
if is_upper(i):
for y in range (0, len(ALPHABET)):
if i== ALPHABET[y]:
msg_crypt+=new_ALPHABET[y]
else:
for y in range (0, len(alphabet)):
if i== alphabet[y]:
msg_crypt+=new_alphabet[y]
return msg_crypt
def filetofreq(text,fichier):
new_file = open(fichier,"w")
dictionnary ={}
Alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',' ']
with open(text, "r",encoding="UTF-8") as txt:
lignes = unidecode.unidecode(txt.read().lower())
for i in range(0,26):
freqlettre=lignes.count(Alphabet[i])/(len(lignes)-lignes.count(Alphabet[26]))*100
dictionnary[Alphabet[i]]=freqlettre
json.dump(dictionnary,new_file)
new_file.close()
def bar_freq(fichier):
dictionary = json.load(open(fichier, 'r'))
xAxis = [key for key, value in dictionary.items()]
yAxis = [value for key, value in dictionary.items()]
fig, ax = plt.subplots()
ax.bar(xAxis,yAxis)
plt.tight_layout()
ax.set_title("Fréquence d'apparition d'une lettre")
plt.show()
def bar_freq1_freq2(fichier1,fichier2):
dictionary = json.load(open(fichier1, 'r'))
xAxis = [key for key, value in dictionary.items()]
yAxis = [value for key, value in dictionary.items()]
dictionary2 = json.load(open(fichier2, 'r'))
xAxis2 = [key for key,value in dictionary2.items()]
yAxis2 = [value for key, value in dictionary2.items()]
fig, ax = plt.subplots()
ax.bar(np.arange(len(xAxis))+0.2,yAxis,0.4,label="Freq 1")
ax.bar(np.arange(len(xAxis2))-0.2,yAxis2,0.4,label="Freq 2")
plt.tight_layout()
plt.legend()
ax.set_title("Fréquence d'apparition d'une lettre")
plt.show()
def bar_compare_freq(fichier1,fichier2,decal):
dictionary = json.load(open(fichier1, 'r'))
xAxis = [key for key, value in dictionary.items()]
yAxis = [value for key, value in dictionary.items()]
dictionary2 = json.load(open(fichier2, 'r'))
xAxis2 = [key for key,value in dictionary2.items()]
yAxis2 = [value for key, value in dictionary2.items()]
yAxis2=yAxis2[decal:]+yAxis2[:decal]
fig, ax = plt.subplots()
ax.bar(np.arange(len(xAxis))+0.2,yAxis,0.4,label="Freq 1")
ax.bar(np.arange(len(xAxis2))-0.2,yAxis2,0.4,label="Freq 2")
plt.tight_layout()
plt.legend()
ax.set_title("Fréquence d'apparition d'une lettre")
plt.show()
def manualdecrypt(fichier1,fichier2):
for i in range(1,26):
print("décalage :",i)
bar_compare_freq(fichier1,fichier2,i)
def moy(x):
add=0
for e in x:
add+=e
return add/len(x)
def covar(X,Y):
som=0
if len(X) == len(Y):
for i in range(0,len(X)):
a=(X[i]-moy(X)) * (Y[i]-moy(Y))
a/=len(X)
som+=a
a=0
return som
else:
return "error"
def variance(X):
a=0
for i in range(0,len(X)):
a+=(X[i]-moy(X))**2
return a*(1/len(X))
def coeff_corr(X,Y):
return covar(X,Y)/(math.sqrt(variance(X)*variance(Y)))
def correlation_freqs(fichier1,fichier2):
dictionary = json.load(open(fichier1, 'r'))
yAxis = [value for key, value in dictionary.items()]
dictionary2 = json.load(open(fichier2, 'r'))
yAxis2 = [value for key, value in dictionary2.items()]
corr=-1
decal=0
for i in range(1,26):
yAxis2=yAxis2[1:]+yAxis2[:1]
print("décalage :",i," crypt correlation :",coeff_corr(yAxis,yAxis2))
if corr<coeff_corr(yAxis,yAxis2):
decal=i
corr=coeff_corr(yAxis,yAxis2)
print("Décalage de décryptage :", decal)
return decal
def decrpt(fichier):
filetofreq(fichier,"freq.json")
with open(fichier,"r",encoding="UTF-8") as txt:
new_file = open("decrypted_with_caesar.txt","w")
str=txt.read()
strdecry=caesar_crypt(str,-correlation_freqs("freq_lettre_fr.json","freq.json"))
new_file.write(strdecry)
new_file.close()
def main():
filetofreq("encrypted_with_caesar.txt","freq1.json")
#bar_freq("freq_lettre_fr.json")
#bar_freq1_freq2("freq_lettre_fr.json","freq1.json")
#bar_compare_freq("freq_lettre_fr.json","freq1.json",3)
#manualdecrypt("freq_lettre_fr.json","freq1.json") #ici c'est 17 de décalage
correlation_freqs("freq_lettre_fr.json","freq1.json")
decrpt("encrypted_with_caesar.txt")
OCEMCJMQRCOIIPJOPEFONOTMISPIPRORRASONMCBOLSOIVAOPESPCAPEJPCWEPRFMANNOACFIMKMCTNMAFPINONNPETOCNNMCRPENOFFAQOCENAINMCFMRMGYMCPRFIPEACIMSOCPRRMAJIPEPRRAESOPNPRCQNOPNPNNOPEVAACPSZIMWRPMGMCKANPRZAEOPEOEMAEPCNEOCENAIACSMETMCEPRPWCMIOPERONPWCPKPGOEPMCPROZOCTMCCONMCIMSOCNAINMCRPEPRORROONMCROJOZMPRSMAPRROACWOCEVAPRFONNONAINMCKIMCENAINMCGMANMCFMARNZOEEOPEEIMFKMIEPROJOPEGYOATPRMAJIPENMCJONPNEONNGIAEOROCAPEPRKOPNOPETMAUACZIAPEPCTPNEPCGESMCEOPETAKOAZMAIWACGOIPRRMCFRANRMAITVAACWRONFRANNMAITVAACEMGNPCFRANFIMKMCTVAACZMAITMCCMCRMPCNMCCOEIMPNGMAFNTAGOCORNOPCESOIEPCACGROFMEPNFROPCEPKNPWCOROPEACGYOROCTVAPFONNOPENAIROZOEEOCETAJONPNEONACOCPSOROAEYMIOUPCTPWMOROPWAPRRMCNOKIOCCPACGOKOITCPACGYOIOCGMCSOPNFRAEMEACOIEPNMCNOJOCGOPEEIOPCOCEACZIPCTORKOPRNOFFIMGYOJMAROCEROFROEPITACGMAFJPKSOPNROCPSORFIPENMCJMRTPNFOIOPNNOCETOCNROCAPEOJOCEVAPROPEFARONNOPRRPIPREOFMEOTACTMPWEACOPISOIEPORNAIRMZRMCWGYONNPNTAJONPNEONPRMAJIPENMCKIPWMSAIORPRFIPETAROPEKIMPTPRZAEACWIOCTZMRPRNOFOPNOPEPRNONNPENAINMCGMNQPRFIPEACBMAICORVAPRFOIGMAIAETACOPITPNEIOPEPRORRASOACGPWOIPRRMVAPRKASOBANVAOAZMAEVAMPVAPREIMAJOENMCFOIKASPIIPEOCEPREMANNOPRSPEROIOTPMACOPIOKIMGAZOPCKAENAPJPTACZMNEMCFAPNACEOCWMFAPNACKMUEIMEFAPNACGMEPRRMCSPNOAWMAETABMAITAEIMCGGYOCEOTAROCLSOCCZOIZOIOACSOTIPWORTOIOWMCNEPGYIOCTORRACOPITOPTOPRTAENONNMAFPIACPCNEOCEGOIPRNAINOAEONMATOPCROIOTPMOCCMCGOPEJMPGPCMNPCKMISOEPMCNPRCQOJOPEOAGACKOPEPSFMIEOCEOJORFOIOPNMRPCOAWAIOEPMCTACFMCEOJOPEKOPEJPCWEGPCVSMIENOLAIPGYCMIMTMSNPYOCMAXKOPNOPENOJMPIVAPRCPIOPEFONOHONYPCWEMCOSOEPWCMCFMSFPTMAFIMFMNOPEOAUNQCTPGOENRMIWOCPNOEPMCTACNEOEAVAMNMGPORSOPNKOPNOPEGYMAZROCGOAZPOKIOGMCKRPENIOGPOAUOGMCOXIQMCFOIROPETACFAENGYACEQFYMCNOZOEEOPENAICOWONOXPEOCTPNVAACMAIOWOCOABMRPNAICMSTOSOCTONOCCMCGOPENAIEIPNEOCTOGACYOTMCEMCIOFOEIPOPEROFMFAROEPMCFOIOJPMCNGOIWMNOIMROCTWOIIMNFMAIKPCPITOCNACSOEGYGMSFEOCEFMAIROTOJPNGAFNOCEOCOOJOPEZOEEATOISMCNPUEIMPNACNPUEIMPNNPUTPUYAPEYAPENPUPRGMAFOROIOTPM
\ No newline at end of file
Ce diff est replié.
{"a": 2.614727854855923, "b": 0.05336179295624333, "c": 6.189967982924227, "d": 1.44076840981857, "e": 1.4941302027748131, "f": 0.16008537886872998, "g": 8.164354322305229, "h": 7.790821771611527, "i": 13.927427961579507, "j": 11.419423692636073, "k": 0.42689434364994666, "l": 6.08324439701174, "m": 1.9743863393810033, "n": 3.2017075773745995, "o": 0.5336179295624333, "p": 0.9071504802561365, "q": 1.4941302027748131, "r": 0.16008537886872998, "s": 1.0138740661686232, "t": 1.1739594450373532, "u": 8.591248665955176, "v": 0.26680896478121663, "w": 9.818569903948772, "x": 0.0, "y": 8.057630736392744, "z": 3.04162219850587}
\ No newline at end of file
{"a": 8.4, "b": 1.1, "c": 3.0, "d": 4.2, "e": 17.3, "f": 1.1, "g": 1.3, "h": 0.9, "i": 7.3, "j": 0.3, "k": 0.1, "l": 6.0, "m": 3.0, "n": 7.1, "o": 5.3, "p": 3.0, "q": 1.0, "r": 6.6, "s": 8.1, "t": 7.1, "u": 5.7, "v": 1.3, "w": 0.1, "x": 0.4, "y": 0.3, "z": 0.1}
import json
import string
import random
import numpy as np
import unidecode
import c
def crypt(msg) :
new=msg.replace(' ','')
new = unidecode.unidecode(new)
new=new.upper()
c=list(new)
random.shuffle(c)
return ''.join(c)
def chiffre(msg,key):
ALPHABET=string.ascii_uppercase
new=msg.lower()
new=new.replace(' ','')
new = unidecode.unidecode(new)
new=new.upper()
for i in range(0,len(new)):
for y in range(0,len(ALPHABET)):
if new[i]==ALPHABET[y]:
new = new[:i] + key[y] + new[i+1:]
break
return new
def dictquad(text):
new_file = open("dictquad.json","w")
with open(text, "r",encoding="UTF-8") as txt:
lignes = txt.readlines()
for ligne in lignes:
DICT_QUAD[ligne[0:4]]=int(ligne[5:].replace("\n",""))
json.dump(DICT_QUAD,new_file)
new_file.close()
def logscore(chain):
logsum = 0
min_freq = 1e-10
for i in range(len(chain)-3):
logsum += np.log10(DICT_QUAD.get(chain[i:i+4], min_freq))
return -logsum
DICT_QUAD={}
key=crypt(string.ascii_uppercase)
print(key)
#print(chiffre('abc',key))
#c.decrpt("texte_chiffre_substitution.txt")
dictquad("quadrigramme.txt")
with open("texte_chiffre_substitution.txt", "r",encoding="UTF-8") as txt:
lignes = txt.read()
oldkey=[]
ls=999999999999999.9
ret=lignes
new=chiffre(lignes,key)
for i in range(0,1000000):
key=crypt(string.ascii_uppercase)
#print(oldkey)
if key not in oldkey:
oldkey+=key
new=chiffre(lignes,key)
#print("new",logscore(new))
#print("ret",logscore(ret))
if logscore(ret)>logscore(new):
ls=logscore(new)
ret=new
#print("best ls",ls)
print("ret",ret)
0% Chargement en cours ou .
You are about to add 0 people to the discussion. Proceed with caution.
Terminez d'abord l'édition de ce message.
Veuillez vous inscrire ou vous pour commenter