#-*- coding:UTF-8 -*-
'''
time: 2018-5-30
content:RSA
python 3.6
mac os
'''
from random import randint
import random
import math
import sys
def charToAscii(message): #将字符转化为ASCII码
Output = []
for i in message:
Output.append(ord(i))
return Output
#将ASCII码变为十六进制
def AsciiToHex(message):
Output = ''
for each in message:
Output = Output + str(hex(each)).split('x')[1]
return Output
def Hex_to_dec(hexnumber): #16进制字符串转化为十进制
decnumber = int(hexnumber,16)
return decnumber
def dec_to_Hex(decumber): #十进制转化为十六进制
hexnumber = hex(decumber)
return hexnumber
def big_P_Q(): #产生两个大素数
flag = 0
while not flag:
p = random.randrange(10**10,10**11)
if charge_sushu_1(p) and _ack(2,p):
q = random.randrange(p,10**11)
if charge_sushu_1(q) and p != q and _ack(2,q):
flag = 1
return p,q
def fastExpMod(b, e, m): #快速求模
result = 1
while e != 0:
if (e&1) == 1:
# ei = 1, then mul
result = (result * b) % m
e >>= 1
# b, b^2, b^4, b^8, ... , b^(2^n)
b = (b*b) % m
return result
def gcd(a,b): #判断互素
if a0:
# u = N/2**t
# if N%2*t==0 and u%2 == 1:
# break
# u = t-1
# b = fastExpMod(a,u,n)
# if(b == 1):
# return True
#
# for n in range(0,t,1):
# if(b == n-1):
# return True
# else:
# b = fastExpMod(b,2,n)
# return False
def charge_sushu_1(n):
Sushu = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41
, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97)
for y in Sushu:
if n % y == 0:
return False
return True
def _ack(a,n):
a1 = pow(17-a,n,n)
a2 = pow(17,n,n) - (a%n)
if a1 == a2:
return 1
else:
return 0
def charge_sushu_2(n, k):
if n < 2:
return False
d = n - 1
r = 0
while not (d & 1):
r += 1
d >>= 1
for i in range(k):
a = randint(120) #随机数
x = fastExpMod(a, d, n)
if x == 1 or x == n - 1:
continue
for i in range(r - 1):
x = fastExpMod(x, 2, n)
if x == 1:
return False
if x == n - 1:
break
else:
return False
return True
以上是函数的主要函数
输出结果:
源代码查看此地址:https://download.csdn.net/download/weixin_39641975/10458941