1. 程式人生 > >RSA私鑰加密解密

RSA私鑰加密解密

Copyright © 2018 Joyce_BY
All rights reserved.
Contact by [email protected]


實驗原理及演算法

  1. generate key
    本次模擬利用私鑰(n,sID)生成公鑰,具體過程如下:
    A)選擇一對512bit的素數p,q,計算n = p * q;
    B)計算fn = (p-1) * (q-1);
    C)根據e * d ≡ 1 (mod fn)計算出公鑰(n,e)。
    CODE
# key generation
def gen_key(p, q):
    n = p * q
    fn =
(p - 1) * (q - 1) d = 16337053 # generate e # use e*d = k*fn + 1 x = fn while (x + 1) % d: x += fn e = (x+1) // d # public key, self key return (n, e), (n, d)
  1. encryption and decryption
    加密:c ≡ m^e mod n
    解密::m ≡ c^d mod n
    將plaintext字串轉化為ascii十進位制數字。
    CODE
def encryption(m, pk):
    n = pk[0]
    e = pk[1]
    c = square_mod(m, e, n)
    return c

def decryption(c, sk):
    n = sk[0]
    d = sk[1]
    m = square_mod(c, d, n)
return m

# get bit string of plaintext
    pt = 'test RSA'
    m = int(''.join(format(ord(ch)) for ch in pt))
  1. 模重複平方演算法
    利用模重複平方演算法求得大數取模的結果。
    CODE
# b^m (mod m)
def square_mod(base, n, m):
    b = base
    bin_exp = bin(n)[2:][::-1]
    a = 1
    for bit in bin_exp:
        if bit == '1': 
            a = a * b % m
        b = b * b % m
    return a

試驗成功。