[英]RSA Implemenations
我正在研究rsa實現。 我想我已經快完成了,我偶爾遇到一個錯誤,在我運行代碼時,這是在shell中彈出的錯誤:
追溯(最近一次通話):
File "/home/damion/Documents/projects/project2.py", line 164, in <module>
decrypt_message = decrypt(encrypted_message,d,n)# decrypt message that was encrypted.
File "/home/damion/Documents/projects/project2.py", line 115, in decrypt
decrypt_string+=DecimalToChar(m)#add each charactor to a string
File "/home/damion/Documents/projects/project2.py", line 96, in DecimalToChar
return str(chr(d))
ValueError: chr() arg not in range(256)
這是我的代碼:
from random import randint
def prime(n):
for i in range(2,n):
if n%i==0:
return False
return True
def isprime(n):
"""
return true if n is a prime number and false otherwise"""
if prime(n):
return True
else:
return False
def prime_generator():
primeone=12
while not isprime(primeone):
primeone=randint(11,5000)
print primeone
print "prime number is: "+str(primeone)
primetwo = primeone
primetwo+=1
while not isprime(primetwo):
primetwo+=1
print primetwo
return primeone,primetwo
def gcd(x,y):
"""
use to calculate the greatest common divisible of x and y """
if y == 0:
return x
else:
return gcd(y,x%y)
def n(prime1,prime2):
"""
calculte and return 'N' That is used to find phi(N),and that is also used as to
make up the private and public key
"""
return prime1*prime2
def caculatePhi(prime1,prime2):
"""
calculate Phi(N) and return Phi(N)"""
return (prime1-1)*(prime2-1)
def e_finder(e,phi):
"""
calculate e for the public key and return Phi(n),e,n"""
while True:
if gcd(phi,e) == 1:# check to see if phi and e has no common factor except one(1)
return e
else:
e +=2 #increment e by to if there is a gcd>1
def Extended_Euclidean_Algorithm(PHI, E):
phi = PHI
e = E
A,X,previous_X,Y,previous_Y = phi,0,1,1,0
while e != 0:
temp = e
quotient = int(phi/e)
e = phi % e
phi = temp
temp = X
phi = previous_X - quotient * X
previous_X = temp
temp = Y
Y = previous_Y - quotient * Y
previous_Y = temp
return A + previous_Y
def generate_keys(E,D,N):
e,d,n = E,D,N
"""Calcualte private key(d),generate keys and return these keys
ie. public and private keys for encryption and decryption"""
return {"public_key":{"e":e,"n":n}},{"private_key":{"d":d,"n":n}}
def CharToDecimal(char):
"""convert a charactor to its decimal value
"""
c=char
return int(ord(c))
def DecimalToChar(decimal):
d=decimal
return str(chr(d))
def encrypt(m,e,n):
"""encrypt message and return that encrypted message """
encryped_string = ""
encrypt_lst=[]
for i in m:# loop through message, getting charactor at a time for encryption
m_char = CharToDecimal(i)#convert each charactor to its decimal equivalent
c=pow(m_char,e,n)#equivalent to c=(m**e)%n
encrypt_lst.append(c) # add each encrypted charactor to a LIST
encryped_string+=str(c)
return encrypt_lst,encryped_string
def decrypt(c,d,n):
"""decrypt message and return that decrypted message"""
decrypt_string = ""
for i in c: #loop through LIST of encrypted values,for decryption index by index
m=pow(i,d,n)#equivalent to m=(i**d)%n
decrypt_string+=DecimalToChar(m)#add each charactor to a string
return decrypt_string
if __name__ == "__main__":
"""Main for excuting programme"""
message = str(raw_input("Enter message to encrypt: "))
## prime_one = int(raw_input("Please Enter First Prime Number: "))
## prime_two = int(raw_input("Please Enter Second Prime Number: "))
##
prime_one,prime_two = prime_generator()
while (not isprime(prime_one) or not isprime(prime_two)):#prompt user to enter value if not prime
print""
print""
print"_________________________________________________________"
if not isprime(prime_one):print "first number was not prime!!!"
if not isprime(prime_two):print "Second number was not prime!!!"
print""
print"_________________________________________________________"
print""
prime_one = int(raw_input("Please enter first prime nuber: "))
prime_two = int(raw_input("Please enter second prime : "))
while prime_one<11 or prime_two<11: # prompt user to re-enter prime if less than 11
print""
print""
print"_________________________________________________________"
if prime_one<11:print "first number Must Be greater Than 10!!!"
if prime_two<11:print "Second number Must Be greater Than 10!!!"
print""
print"_________________________________________________________"
print""
prime_one = int(raw_input("Please enter first prime nuber: "))
prime_two = int(raw_input("Please enter second prime : "))
n= n(prime_one,prime_two)
phi = caculatePhi(prime_one,prime_two)
e=e_finder(3,phi)
d=Extended_Euclidean_Algorithm(phi,e)
keys = generate_keys(e,d,n) #get generated keys(public and private) and store them in keys
print "keys are: ",keys
encrypted_message,encryped_string = encrypt(message,e,n)#encrypt message from user
print "Encrypted string: "+str(encryped_string)#display string of encrypted input
print encrypted_message
decrypt_message = decrypt(encrypted_message,d,n)# decrypt message that was encrypted.
print "Our message decrypted is: "+str(decrypt_message)
正如Korem所說,您正在DecimalToChar
函數DecimalToChar
非法值傳遞給chr
。 (堆棧跟蹤是您的朋友。請閱讀堆棧跟蹤。) DecimalToChar
只是chr
周圍的一個大而胖的包裝器,在Python 2中它僅接受一個無符號的一字節整數(0到255,包括0和255)。
您只需要在一個位置調用DecimalToChar
,參數為m
:
m=pow(i,d,n)#equivalent to m=(i**d)%n
這將僅偶然地向chr
產生合法輸入(並且在這種情況下非常罕見): i ** d
可能很大,而n
是兩個大質數的乘積。)
確保未知(非負)整數在給定范圍內的傳統方法是模除法,在這種情況下,類似於:
def DecimalToChar(decimal):
d=decimal % 256
return str(chr(d))
這樣可以避免您遇到的錯誤,但是我認為它不會解決您的程序。 一個更大的問題是: 為什么您首先認為m
應該是有效的ASCII字節?
其他一些建議:
全局名稱空間中有很多代碼。 (事實上,你垃圾你n
-the功能,當您重用名稱n
-the -產品-的-兩個大素數,這是一個錯誤。)獲取所有的爛攤子到合適的main
功能。
您有很多功能實際上並沒有做任何事情。 n
是一個(要啟動時使用無用的神秘名稱), CharToDecimal
和DecimalToChar
,它們復制Python內置DecimalToChar
,但需要更多鍵入內容。
您有很多代碼根本不執行任何操作。 前面提到的CharToDecimal
在ord
的輸出( 總是一個整數)上調用int
,而DecimalToChar
在chr
的輸出(一個始終是字符串)的輸出上調用str
。 (它們也完全沒有理由重命名參數。) isprime
只會返回任何prime
。 這樣的無用代碼可以包含錯誤,但是它永遠無法幫助您。
一致性! 函數和變量名,空格,文檔字符串,甚至注釋格式無處不在。 通過使您的良好代碼和不良代碼看起來同樣糟糕,這將隱藏錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.