首頁 > 軟體

利用Python實現RSA加密解密方法範例

2022-04-08 16:00:15

前言

  • 加密技術在資料安全儲存,資料傳輸中發揮著重要作用,能夠保護使用者隱私資料安全,防止資訊竊取。RSA是一種非對稱加密技術,在軟體、網頁中已得到廣泛應用。本文將介紹RSA加密解密在python中的實現。
  • 原則:公鑰加密,私鑰解密
  • 解釋:具體過程的解釋請見程式碼前的註釋

RSA加密實驗基本流程:

一、選取兩個大素數p、q,並計算得到n、phi_n

二、選取常用的e = 0x10001,方便將冪運算優化為左移,加快運算速度

三、計算d,使用了擴充套件歐幾里得演演算法

四、輸入明文a,將明文轉化為可以用於計算的數位形式

五、對a使用快速冪取模,得到密文b,以16進位制顯示

RSA解密流程:

六、對b使用快速冪取模,得到明文a,以字元形式顯示

一、安裝模組

pip install pycryptodome 

二、生成金鑰對

  • 金鑰對檔案生成和讀取
  • 程式碼:
from Crypto.PublicKey import RSA
def create_rsa_pair(is_save=False):
    '''
    建立rsa公鑰私鑰對
    :param is_save: default:False
    :return: public_key, private_key
    '''
    f = RSA.generate(2048)
    private_key = f.exportKey("PEM")  # 生成私鑰
    public_key = f.publickey().exportKey()  # 生成公鑰
    if is_save:
        with open("crypto_private_key.pem", "wb") as f:
            f.write(private_key)
        with open("crypto_public_key.pem", "wb") as f:
            f.write(public_key)
    return public_key, private_key

def read_public_key(file_path="crypto_public_key.pem") -> bytes:
    with open(file_path, "rb") as x:
        b = x.read()
        return b

def read_private_key(file_path="crypto_private_key.pem") -> bytes:
    with open(file_path, "rb") as x:
        b = x.read()
        return b

三、加密

  • 流程:輸入文字(str)→字串編碼(預設utf-8)(bytes)→rsa加密(bytes)→base64編碼(bytes)→解碼為字串(str)
  • 程式碼:
import base64
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA

def encryption(text: str, public_key: bytes):
	# 字串指定編碼(轉為bytes)
	text = text.encode('utf-8')
	# 構建公鑰物件
	cipher_public = PKCS1_v1_5.new(RSA.importKey(public_key))
	# 加密(bytes)
	text_encrypted = cipher_public.encrypt(text) 
	# base64編碼,並轉為字串
	text_encrypted_base64 = base64.b64encode(text_encrypted ).decode()
	return text_encrypted_base64 
	
if __name__ == '__main__':
	public_key = read_public_key()
	text = '123456'
	text_encrypted_base64 = encryption(text, public_key)
	print('密文:',text_encrypted_base64)

四、解密

  • 說明:解密流程與加密流程相反(按照加密流程逆序解密)
  • 流程:輸入文字(str)→字串編碼(預設utf-8)(bytes)→base64解碼(bytes)→rsa解密(bytes)→解碼為字串(str)
  • 程式碼:
import base64
from Crypto.Cipher import PKCS1_v1_5
from Crypto import Random
from Crypto.PublicKey import RSA

def decryption(text_encrypted_base64: str, private_key: bytes):
	# 字串指定編碼(轉為bytes)
	text_encrypted_base64 = text_encrypted_base64.encode('utf-8')
	# base64解碼
	text_encrypted = base64.b64decode(text_encrypted_base64 )
	# 構建私鑰物件
	cipher_private = PKCS1_v1_5.new(RSA.importKey(private_key))
	# 解密(bytes)
	text_decrypted = cipher_private.decrypt(text_encrypted , Random.new().read)
	# 解碼為字串
	text_decrypted = text_decrypted.decode()
	return text_decrypted 
	
if __name__ == '__main__':
	# 生成密文
	public_key = read_public_key()
	text = '123456'
	text_encrypted_base64 = encryption(text, public_key)
	print('密文:',text_encrypted_base64)
	
	# 解密
	private_key = read_private_key()
	text_decrypted = decryption(text_encrypted_base64, private_key)
	print('明文:',text_decrypted)

五、完整程式碼

import base64
from Crypto.Cipher import PKCS1_v1_5
from Crypto import Random
from Crypto.PublicKey import RSA
# ------------------------生成金鑰對------------------------
def create_rsa_pair(is_save=False):
    '''
    建立rsa公鑰私鑰對
    :param is_save: default:False
    :return: public_key, private_key
    '''
    f = RSA.generate(2048)
    private_key = f.exportKey("PEM")  # 生成私鑰
    public_key = f.publickey().exportKey()  # 生成公鑰
    if is_save:
        with open("crypto_private_key.pem", "wb") as f:
            f.write(private_key)
        with open("crypto_public_key.pem", "wb") as f:
            f.write(public_key)
    return public_key, private_key

def read_public_key(file_path="crypto_public_key.pem") -> bytes:
    with open(file_path, "rb") as x:
        b = x.read()
        return b

def read_private_key(file_path="crypto_private_key.pem") -> bytes:
    with open(file_path, "rb") as x:
        b = x.read()
        return b
# ------------------------加密------------------------
def encryption(text: str, public_key: bytes):
    # 字串指定編碼(轉為bytes)
    text = text.encode('utf-8')
    # 構建公鑰物件
    cipher_public = PKCS1_v1_5.new(RSA.importKey(public_key))
    # 加密(bytes)
    text_encrypted = cipher_public.encrypt(text)
    # base64編碼,並轉為字串
    text_encrypted_base64 = base64.b64encode(text_encrypted).decode()
    return text_encrypted_base64

# ------------------------解密------------------------
def decryption(text_encrypted_base64: str, private_key: bytes):
    # 字串指定編碼(轉為bytes)
    text_encrypted_base64 = text_encrypted_base64.encode('utf-8')
    # base64解碼
    text_encrypted = base64.b64decode(text_encrypted_base64)
    # 構建私鑰物件
    cipher_private = PKCS1_v1_5.new(RSA.importKey(private_key))
    # 解密(bytes)
    text_decrypted = cipher_private.decrypt(text_encrypted, Random.new().read)
    # 解碼為字串
    text_decrypted = text_decrypted.decode()
    return text_decrypted

if __name__ == '__main__':
    # 生成金鑰對
    # create_rsa_pair(is_save=True)
    # public_key = read_public_key()
    # private_key = read_private_key()
    public_key, private_key = create_rsa_pair(is_save=False)

    # 加密
    text = '123456'
    text_encrypted_base64 = encryption(text, public_key)
    print('密文:', text_encrypted_base64)

    # 解密
    text_decrypted = decryption(text_encrypted_base64, private_key)
    print('明文:', text_decrypted)

總結

到此這篇關於利用Python實現RSA加密解密的文章就介紹到這了,更多相關Python RSA加密解密內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com