当前位置:   article > 正文

RSA密码原理详解及算法实现(六步即可掌握)_rsa算法实现

rsa算法实现

一、RSA算法概述

rsa算法是一种非对称加密算法,其安全性是建立在大素数难以分解的基础上的,即将两个大素数相乘十分容易,但想对其乘积进行分解却很困难,所以可以将其乘积公开作为加密密钥

二、RSA算法设计理念

根据数论,寻求两个大素数比较简单,而将它们的乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥

三、加解密过程及密钥生成

1、加解密过程

此处从明文和密文加密和解密开始,然后讲密钥的生成

(1). 对于明文M,则有密文C=M^e mod n  (获得密文是明文的e次方再模n,即求余数)    

(2). 对于密文C,则有明文M=C^d mod n   (获得明文是密文的d次方再模n,即求余数)

明文和密文的产生是建立在一对密钥的基础上的,即(e,n)和(d,n) ,(e,n)称为公钥 , (d,n)称为私钥   (先记下公钥和私钥的概念,有个印象)

下面是一个形象的例子

假设A要与B通信:

 A————————————————————————————B

(e,n)                                                                                             (d,n)

A握着(e,n)对想发送的明文M加密C=M^e mod n形成密文C,再将C发送给B

B拿到密文C,再用自己的私钥(d,n)对密文C解密还原明文M

现在我们只需要知道(e,n)和(d,n)即(e,d,n)三个密钥怎么来的就搞定了RSA算法

2、密钥生成过程  (e,d,n)

(1).求n

准备两个素数p,q(最好准备较大的素数)   (注:素数 质数是同一个东东)

n=p*q

至此n得到了

(2).根据第一步准备的p和q计算 n的欧拉函数φ(n)

φ(n)=(p-1)*(q-1)

(3).选取公钥e

选取条件:质数,1<e<φ(n)  ,  (e,φ(n))=1(e与φ(n)互质)

至此e得到了,在实际应用中,e一般为65537,(ctfer应该比较敏感吧hhh

(4).计算私钥d,计算e对于φ(n)的模反元素d。

d应满足:ed ≡ 1 (mod φ(n))             (即 (d*e)mod φ(n)=1)

至此(e,d,n)全部得出

带具体例子的视频在这里:

数学不好也能听懂的算法 - RSA加密和解密原理和过程_哔哩哔哩_bilibili

安全性推荐看这篇,此处不讲了,因为本文主要内容只是给大家讲解原理

python实现RSA算法-Python教程-PHP中文网

四、python实现

明白了算法的原理,代码实现也就变的简单了

具体思路就是,按照p,q得到密钥e,d,n后,执行加密和解密的式子。

  1. import random
  2. '''
  3. Euclid's algorithm for determining the greatest common divisor
  4. Use iteration to make it faster for larger integers
  5. '''
  6. def gcd(a, b):
  7. while b != 0:
  8. a, b = b, a % b
  9. return a
  10. '''
  11. Euclid's extended algorithm for finding the multiplicative inverse of two numbers
  12. '''
  13. def multiplicative_inverse(e, phi):
  14. d = 0
  15. x1 = 0
  16. x2 = 1
  17. y1 = 1
  18. temp_phi = phi
  19. while e > 0:
  20. temp1 = temp_phi//e
  21. temp2 = temp_phi - temp1 * e
  22. temp_phi = e
  23. e = temp2
  24. x = x2 - temp1 * x1
  25. y = d - temp1 * y1
  26. x2 = x1
  27. x1 = x
  28. d = y1
  29. y1 = y
  30. if temp_phi == 1:
  31. return d + phi
  32. '''
  33. Tests to see if a number is prime.
  34. '''
  35. def is_prime(num):
  36. if num == 2:
  37. return True
  38. if num < 2 or num % 2 == 0:
  39. return False
  40. for n in range(3, int(num**0.5)+2, 2):
  41. if num % n == 0:
  42. return False
  43. return True
  44. def generate_key_pair(p, q):
  45. if not (is_prime(p) and is_prime(q)):
  46. raise ValueError('Both numbers must be prime.')
  47. elif p == q:
  48. raise ValueError('p and q cannot be equal')
  49. # n = pq
  50. n = p * q
  51. # Phi is the totient of n
  52. phi = (p-1) * (q-1)
  53. # Choose an integer e such that e and phi(n) are coprime
  54. e = random.randrange(1, phi)
  55. # Use Euclid's Algorithm to verify that e and phi(n) are coprime
  56. g = gcd(e, phi)
  57. while g != 1:
  58. e = random.randrange(1, phi)
  59. g = gcd(e, phi)
  60. # Use Extended Euclid's Algorithm to generate the private key
  61. d = multiplicative_inverse(e, phi)
  62. # Return public and private key_pair
  63. # Public key is (e, n) and private key is (d, n)
  64. return ((e, n), (d, n))
  65. def encrypt(pk, plaintext):
  66. # Unpack the key into it's components
  67. key, n = pk
  68. # Convert each letter in the plaintext to numbers based on the character using a^b mod m
  69. cipher = [pow(ord(char), key, n) for char in plaintext]
  70. # Return the array of bytes
  71. return cipher
  72. def decrypt(pk, ciphertext):
  73. # Unpack the key into its components
  74. key, n = pk
  75. # Generate the plaintext based on the ciphertext and key using a^b mod m
  76. aux = [str(pow(char, key, n)) for char in ciphertext]
  77. # Return the array of bytes as a string
  78. plain = [chr(int(char2)) for char2 in aux]
  79. return ''.join(plain)
  80. if __name__ == '__main__':
  81. '''
  82. Detect if the script is being run directly by the user
  83. '''
  84. print("===========================================================================================================")
  85. print("================================== RSA Encryptor / Decrypter ==============================================")
  86. print(" ")
  87. p = int(input(" - Enter a prime number (17, 19, 23, etc): "))
  88. q = int(input(" - Enter another prime number (Not one you entered above): "))
  89. print(" - Generating your public / private key-pairs now . . .")
  90. public, private = generate_key_pair(p, q)
  91. print(" - Your public key is ", public, " and your private key is ", private)
  92. message = input(" - Enter a message to encrypt with your public key: ")
  93. encrypted_msg = encrypt(public, message)
  94. print(" - Your encrypted message is: ", ''.join(map(lambda x: str(x), encrypted_msg)))
  95. print(" - Decrypting message with private key ", private, " . . .")
  96. print(" - Your message is: ", decrypt(private, encrypted_msg))
  97. print(" ")
  98. print("============================================ END ==========================================================")
  99. print("===========================================================================================================")

懒得写了,git上co的)

笔者在22-23年做过的题放在了该仓库GitHub - SlientRainyDay/Rain_CTF: CTF — 学习笔记&比赛题目&WP

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/799707
推荐阅读
相关标签
  

闽ICP备14008679号