# RSA加密及AES对称加密代码实现

1：N = p*q(p、q互质，即公约数只有1)可以用辗转相除去判断

2：L是p-1和q-1的最小公倍数。如果减一后仍互质，则为乘积。否则最小公倍数=两数的乘积/最大公约数

3：求E：1<E<L并且要满足E，L互质

4：求D：1<E<L 并且要满足E*D mod L =1

#辗转相除判断互质
def judge(n,m):
t = 0
while m>0:
t = n%m
n = m
m = t
if n == 1:
return 1
else :
return 0

#快速幂取模:b^e%m
def PowMod(b,e,m):
result = 1
while e != 0:
if (e&1) == 1:
result = (result * b) % m
e >>= 1
b = (b*b) % m
return result
def lcm(a, b):
for i in range(min(a,b),0,-1):
if a % i ==0 and b % i == 0:
return a*b//i
def main():
p,q = map(int,input().split())
n = p*q
if judge(p-1,q-1):
L = (p-1)*(q-1)
else:
L = lcm(p-1,q-1)

for i in range(2,L):
if judge(i,L) == 1:
e = i
break
for i in range(2,L):
if e*i%L == 1:
d = i
break
print("public_key:"+str(e)+","+str(n))
print("private_key:"+str(d)+","+str(n))

Array = []
Result=""
decode=""
Key = str(n)
Key_Len = len(Key)
original = input("Numbers:")
original_len = len(original)
while Key_Len < original_len:  #分片
flag = original[0:Key_Len]
original = original[Key_Len:original_len]
Array.append(str(PowMod(int(flag),e,n)))
original_len = len(original)
Array.append(str(PowMod(int(original),e,n)))
for i in Array:
decode += str(PowMod(int(i),d,n))
#print("i"+str(i))
Result += str(i)

print("result:"+Result)
print("decode："+decode)
main()



================================================================================================

AES对称加密：

#
#AES对称加密
#对同一路径下的文件进行加密，随机生成16位密钥，加密结果保存在同目录下
#

import random
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex

def encryption(file,key):
message = file
mode = AES.MODE_OFB
cryptor = AES.new(key.encode('utf-8'), mode, b'0000000000000000')
length = 16
count = len(message)
if count % length != 0:
add = length - (count % length)
else:
message = message + ('\0' * add)
ciphertext = cryptor.encrypt(message.encode('utf-8'))
result = b2a_hex(ciphertext)
with open("jiemi.txt",'w+') as f:
f.write(result.decode('utf-8'))
print("加密成功")
#print(result.decode('utf-8'))

def deciphering(file,key):
result = file
mode = AES.MODE_OFB
cryptor = AES.new(key.encode('utf-8'), mode, b'0000000000000000')
plain_text = cryptor.decrypt(a2b_hex(result))
print(plain_text.decode('utf-8').rstrip('\0'))

def Key():#生成16位密钥
Str = ""
for i in range(16):
K = random.choice('1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
Str += K
return Str

if __name__ == "__main__":
while(1):
i = int(input("1:加密 2.解密 其他：退出\n"))
if i == 1:
file_name = input("请输入加密文件名：")
File = open(file_name)
key = Key()
print("密钥："+key)
encryption(f,key)
elif i == 2:
file_name = input("请输解密文件名：")
File = open(file_name,'r+')
#print(f)
key = input("请输入密钥：")
deciphering(f,key)
else:
break

09-01 4180

10-30 628

11-11 479

10-19 50

12-27 298

09-14 3534

07-31 449

04-26 1196

#### RSA算法Python实现

©️2020 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。