crypto/crittografia/alfabeto.py

82 lines
2.3 KiB
Python
Raw Normal View History

2013-07-15 15:34:50 +02:00
from crittografia.numeri import *
alfabeto = tuple("abcdefghijklmnopqrstuvwxyz")
ordinale = dict([(k,i) for i,k in enumerate(alfabeto)])
class codifica:
2012-12-25 23:19:52 +01:00
def __init__(self, valore):
valore = str(valore)
if valore.isnumeric():
self.numero = int(valore)
else:
self.stringa = valore
2013-07-15 15:34:50 +02:00
def rot13(self):
rotazione = str.maketrans(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"
2013-07-15 15:34:50 +02:00
)
return str.translate(self.stringa, rotazione)
def vigenère(self, verme):
self.stringa = self.stringa.lower().replace(" ","")
cifrata = ""
for i in range(len(self.stringa)):
cifrata += alfabeto[(ordinale[self.stringa[i]] + ordinale[verme[i % len(verme)]]) % 26]
return cifrata
def gödel(self, primo):
self.stringa = self.stringa.lower().replace(" ","")
cifrata = 1
sequenza = primi.lista(primo, len(self.stringa))
for i in range(len(self.stringa)):
cifrata *= sequenza[i]**(ordinale[self.stringa[i]] + 1)
return cifrata
def vernam(self, pad=()):
self.stringa = self.stringa.lower().replace(" ","")
cifrata = ""
if pad is ():
pad = generatore.onetimepad(len(self.stringa))
for i in range(len(self.stringa)):
cifrata += alfabeto[(ordinale[self.stringa[i]] + pad[i]) % 26]
return cifrata, pad
class decodifica:
2012-12-25 23:19:52 +01:00
def __init__(self, valore):
valore = str(valore)
if valore.isnumeric(): self.numero = int(valore)
else: self.stringa = str(valore)
2013-07-15 15:34:50 +02:00
def rot13(self):
rotazione = str.maketrans(
"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM",
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
2013-07-15 15:34:50 +02:00
)
return str.translate(self.stringa, rotazione)
def vigenère(self, verme):
self.stringa = self.stringa.lower().replace(" ","")
decifrata = ""
for i in range(len(self.stringa)):
decifrata += (alfabeto[(ordinale[self.stringa[i]] - ordinale[verme[i % len(verme)]]) % 26])
return decifrata
def gödel(self, primo, n):
decifrata = ""
for i in primi.lista(primo,n):
lettera = -1
while self.numero % i == 0:
self.numero /= i
lettera += 1
decifrata += alfabeto[lettera % 26]
return decifrata
def vernam(self, pad):
self.stringa = self.stringa.lower().replace(" ","")
cifrata = ""
for i in range(len(self.stringa)):
cifrata += alfabeto[(ordinale[self.stringa[i]] - pad[i]) % 26]
return cifrata