RSA加密演算法簡單介紹以及python實現

專注的阿熊發表於2021-10-11

#coding=gbk

import math

import random

# 平方乘演算法求餘數 base^n mod mod

def repeatMod(base, n, mod):

     a = 1

     while n:

         if n&1:

             a = (a*base)%mod

         base = (base*base)%mod

         n = n>>1

     return a

# 判斷是否為素數( Miller-Rabbin

def IsPrime(BigNum, RoundTime):

     temp = BigNum - 1

     k = 0

     while (temp & 0x1)==0 and temp:

         temp = temp >>1

         k = k+1

     m = temp

     while RoundTime:

         a = random.randint(1, BigNum- 2)

         b =  repeatMod(a, m, BigNum)

         if b == 1 or b==BigNum-1:

             return True

         for i in range(1,k):

             b = repeatMod(b, 2, BigNum) # b^2^(k-1) mod n ==+-1, 則是一個素數

             if b == 1 or b==BigNum-1:

                 return True

         RoundTime = RoundTime -1

     return False

# 生成大素數

def BuildBigPrime():

     flag = False

     while not flag:

         BigNum = random.randint(2**512,2**513)

         if BigNum % 2 !=0 :

             flag = IsPrime(BigNum, 10)

     return BigNum

# 輾轉相除求最大公約數

def MaxCommDivisor(m,n):

     if n == 1:

         return True

     if m % n == 0:

       return False

     else:

         flag = MaxCommDivisor(n, m%n)

     return flag

  # b mod a b 的逆元

def get_(a, b):

if b == 0:

return 1, 0

else:

k = a // b  

x1, y1 = get_(b, a % b)

x, y = y1, (x1 - k * y1)

return x,y

if __name__ == '__main__':

     print(" 正在生成大素數 ------")

     p = BuildBigPrime()

     q = BuildBigPrime()

     while p==q:

         q = BuildBigPrime()

     print("外匯跟單gendan5.com 大素數 p:",p,"\n 大素數 q:",q)

     n = p*q

     fn = (p-1)*(q-1)

     while True:

         key1 = random.randint(2**64,2**65)

         if  MaxCommDivisor(fn, key1):

             break

     print(" 金鑰 1 :",key1)

     k, key2 = get_(fn,key1)

     # 生成的私鑰 key2 可能為負數,我們需要 mod fn 來保證其為正數

     if key2<0:

         key2 = key2 % fn

     print(" 金鑰 2 :",key2)

     m = input(" 請輸入明文: ")

     m = int(m.encode('utf-8').hex(),16)

     print('\n------ 加密中 ----')

     c = repeatMod(m,key1,n)

     print(" 明文為: ",m,"\n 密文為: ",c)

     print('\n------ 解密中 ----')

     m = repeatMod(c,key2,n)

     print(" 密文為: ",c,"\n 明文為: ",m)


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2795402/,如需轉載,請註明出處,否則將追究法律責任。

相關文章