首页 > 编程 > Python > 正文

Python实现的rsa加密算法详解

2019-11-25 15:18:27
字体:
来源:转载
供稿:网友

本文实例讲述了Python实现的rsa加密算法。分享给大家供大家参考,具体如下:

算法过程

1. 随意选择两个大的质数p和q,p不等于q,计算N=pq。
2. 根据欧拉函数,不大于N且与N互质的整数数(p-1)(q-1)。
3. 选择一个整数e与(p-1)(q-1)互质,并且e小于(p-1)(q-1)。
4. 用以下这个公式计算d:d× e ≡ 1 (mod (p-1)(q-1))。
5. 将p和q的记录销毁。

(N,e)是公钥,(N,d)是私钥。

python代码

# -*- coding: utf-8 -*-#!/usr/bin/env pythondef range_prime(start, end): l = list() for i in range(start, end+1):  flag = True  for j in range(2, i):   if i % j == 0:    flag = False    break  if flag:   l.append(i) return ldef generate_keys(p, q): #numbers = (11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47) numbers =range_prime(10, 100) N = p * q C = (p-1) * (q-1) e = 0 for n in numbers:  if n < C and C % n > 0:   e = n   break if e==0:  raise StandardError("e not found") #Python3中改为BaseException d = 0 for n in range(2, C):  if(e * n) % C == 1:   d = n   break if d==0:  raise StandardError("d not found") return ((N, e), (N, d))def encrypt(m, key): C, x = key return (m ** x) % Cdecrypt = encryptif __name__ == '__main__': pub, pri = generate_keys(47, 79) L = range(20, 30) C = map(lambda x: encrypt(x, pub), L) D = map(lambda x: decrypt(x, pri), C) print "武林网测试结果:" print "keys:", pub, pri print "message:", L print "encrypt:", C print "decrypt:", D

运行结果:

其实用什么语言实现这个过程都不是很麻烦,只是我们老师要求生成1024的随机数,用c语言写就有点恶心了,所以用python或者java实现要更加方便一点。

PS:关于加密解密感兴趣的朋友还可以参考本站在线工具:

文字在线加密解密工具(包含AES、DES、RC4等):
http://tools.VeVB.COm/password/txt_encode

MD5在线加密工具:
http://tools.VeVB.COm/password/CreateMD5Password

在线散列/哈希算法加密工具:
http://tools.VeVB.COm/password/hash_encrypt

在线MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具:
http://tools.VeVB.COm/password/hash_md5_sha

在线sha1/sha224/sha256/sha384/sha512加密工具:
http://tools.VeVB.COm/password/sha_encode

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表