1. 程式人生 > 程式設計 >Python如何基於rsa模組實現非對稱加密與解密

Python如何基於rsa模組實現非對稱加密與解密

這篇文章主要介紹了Python如何基於rsa模組實現非對稱加密與解密,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

1、簡單介紹:

RSA加密演算法是一種非對稱加密演算法 是由已知加密金鑰推匯出解密金鑰在計算上是不可行的”密碼體制。加密金鑰(即公開金鑰)PK是公開資訊,而解密金鑰(即祕密金鑰)SK是需要保密的。

RSA金鑰至少為500位長,一般推薦使用1024位。RSA金鑰長度隨著保密級別提高,增加很快。

由於RSA的特性,一個1024位的金鑰只能加密117位位元組資料,當資料量超過117位位元組的時候,程式就會丟擲異常。 ——來自大佬

2、程式碼實現:

來一段大佬的程式碼:

import rsa


# 一、生成公鑰及私鑰,並儲存
public_key,private_key = rsa.newkeys(1024) # 生成公鑰和私鑰
# 將生成的公鑰和私鑰進行轉換,以便儲存
pub = public_key.save_pkcs1()
pri = private_key.save_pkcs1('PEM') # save_pkcsl()是內建方法,其預設引數是‘PEM'
with open('pubkey.pem',mode='wb') as f,open('privkey.pem',mode='wb') as f1:
  f.write(pub) # 開啟兩個檔案,分別儲存公鑰及私鑰
  f1.write(pri)


# 二. 使用公鑰加密,私鑰解密
def func():
  with open('pubkey.pem',mode='rb') as f,'rb') as f1:
    pub = f.read() # 從檔案中再讀出公鑰和私鑰
    pri = f1.read()
    public_key = rsa.PublicKey.load_pkcs1(pub) # 轉換為原始狀態
    private_key = rsa.PrivateKey.load_pkcs1(pri)
  message = "rsa加密測試"
  info = rsa.encrypt(message.encode('utf-8'),public_key) # 使用公鑰加密內容,內容必須是二進位制
  msg = rsa.decrypt(info,private_key) # 使用私鑰解密,獲得解密後的內容
  print(msg.decode('utf-8')) # 使用之前記得先解碼

3、程式碼升級:

現在我將上述的程式碼段封裝成一個Rsa class(包含的方法有:__init__——初始化方法,key_transform_store——儲存公鑰與私鑰的方法、encry——加密方法、decry——解密方法),使用的時候,直接將下面的程式碼段拎到我們需要的地方去引用:先建立一Rsa物件,然後呼叫裡面的方法即可:

import rsa


class Rsa(object):
  """RSA加密、解密"""

  def __init__(self,number,pub_path='public_key.pem',priv_path='private_key.pem'):
    """

    :param pub_path: the path to public key,default its path is public_key.pem
    :param priv_path: the path to private key,default its path is private_key.pem
    """
    # Generate the public and private keys,and returns them
    self.public_key,self.private_key = rsa.newkeys(number)

    self.public_key_path = pub_path
    self.private_key_path = priv_path

  def key_transform_store(self):
    """
    convert and save the generated public and private keys to a file
    :return: None
    """
    # convert the generated public and private keys for storage
    pub = self.public_key.save_pkcs1()
    pri = self.private_key.save_pkcs1('PEM')

    # open two files to store the public key and private key respectively
    
    with open(self.public_key_path,mode='wb') as f:
      f.write(pub)

    with open(self.private_key_path,mode='wb') as f1:
      f1.write(pri)

  def encry(self,info):
    """
    encrypt information
    :param info: the original string information to be encrypted
    :return:info_encrypted
    """
    # read the public key from the file
    with open(self.public_key_path,mode='rb') as f:
      pub = f.read()
      # convert pub to original state
      public_key = rsa.PublicKey.load_pkcs1(pub)

    # use the public key to encrypt the content,which must be binary
    info_encrypted = rsa.encrypt(info.encode('utf-8'),public_key)
    return info_encrypted

  def decry(self,info_encrypted):
    """
    decrypt information
    :param info_encrypted: encrypted information
    :return: info
    """
    # read the private key from the file
    with open(self.private_key_path,'rb') as f:
      pri = f.read()
      # convert pri to original state
      private_key = rsa.PrivateKey.load_pkcs1(pri)

    # decrypt with private key to obtain the decrypted content
    msg = rsa.decrypt(info_encrypted,private_key)
    info = msg.decode('utf-8') # decode
    return info


rsa_obj = Rsa(1024) # 例項化
rsa_obj.key_transform_store() # 
info_encrypted = rsa_obj.encry('我是真心喜歡你的。') # 加密
print(info_encrypted)
info = rsa_obj.decry(info_encrypted) # 解密
print(info) # 我是真心喜歡你的。

這裡會出現一個問題:由於RSA的特性,一個1024位的金鑰只能加密117位位元組資料,當資料量超過117位位元組的時候,程式就會丟擲異常。如下測試會丟擲:

OverflowError: 189 bytes needed for message,but there is only space for 117

rsa_obj = Rsa(1024) # 例項化
rsa_obj.key_transform_store() # 
info_encrypted = rsa_obj.encry('我是真心喜歡你的。我是真心喜歡你的。我是真心喜歡你的。我是真心喜歡你的。我是真心喜歡你的。我是真心喜歡你的。我是真心喜歡你的。') # 加密
print(info_encrypted)
info = rsa_obj.decry(info_encrypted) # 解密
print(info)

後記: 通常使用中,會先對資料進行bas64加密,再對加密後的內容使用rsa加密,最後對rsa解密後的內容進行bas64解密。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。