非对称加密算法RSA加密解密流程

非对称加密算法RSA是目前最有影响力的公钥加密算法,它能够抵抗到目前为止已知的绝大多数密码攻击。具体的加密解密流程如下图所示:
RSA算法流程

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是模拟实现非对称密码算法RSA加密解密功能的代码,代码中使用了Python语言实现: ```python import random def gcd(a, b): while b != 0: a, b = b, a % b return a def extended_gcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = extended_gcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = extended_gcd(a, m) if g != 1: raise Exception('No modular inverse') else: return x % m def is_prime(num): if num < 2: return False for i in range(2, int(num**0.5)+1): if num % i == 0: return False return True def generate_keypair(p, q): if not (is_prime(p) and is_prime(q)): raise ValueError('Both numbers must be prime.') elif p == q: raise ValueError('p and q cannot be equal') n = p * q phi = (p-1) * (q-1) e = random.randrange(1, phi) g = gcd(e, phi) while g != 1: e = random.randrange(1, phi) g = gcd(e, phi) d = modinv(e, phi) return ((e, n), (d, n)) def encrypt(pk, plaintext): key, n = pk cipher = [(ord(char) ** key) % n for char in plaintext] return cipher def decrypt(pk, ciphertext): key, n = pk plain = [chr((char ** key) % n) for char in ciphertext] return ''.join(plain) if __name__ == '__main__': p = int(input("Enter a prime number (17, 19, 23, etc): ")) q = int(input("Enter another prime number (Not one you entered above): ")) public, private = generate_keypair(p, q) print("Your public key is ", public, " and your private key is ", private) message = input("Enter a message to encrypt with your private key: ") encrypted_msg = encrypt(private, message) print("Your encrypted message is: ") print(''.join(map(lambda x: str(x), encrypted_msg))) print("Decrypting message with public key ", public, " . . .") print("Your message is:") print(decrypt(public, encrypted_msg)) ``` 使用方法: 1. 首先输入两个不同的质数 p 和 q; 2. 程序会自动生成公钥和私钥,分别保存在 public 和 private 变量中; 3. 输入要加密的信息 message; 4. 程序会用私钥加密信息,并输出加密后的密文 encrypted_msg; 5. 程序会用公钥解密密文,并输出解密后的明文 message。 需要注意的是,这里生成的密文是数字序列,需要转换成字符序列,才能正确地输出解密后的明文。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值