溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

rsa非對稱加密如何在python項(xiàng)目中使用

發(fā)布時(shí)間:2021-03-22 17:05:18 來源:億速云 閱讀:242 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章給大家介紹rsa非對稱加密如何在python項(xiàng)目中使用,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

1、安裝rsa

支持python 2.7 或者 python 3.5 以上版本

使用豆瓣pypi源來安裝rsa

pip install -i https://pypi.douban.com/simple rsa

rsa非對稱加密如何在python項(xiàng)目中使用

2、加密解密

2.1、生成公私鑰對

import rsa

# 1、接收者(A)生成512位公私鑰對
# a. lemon_pub為PublicKey對象, lemon_priv為PrivateKey對象
# b. 512為秘鑰的位數(shù), 可以自定義指定, 例如: 128、256、512、1024、2048等
lemon_pub, lemon_priv = rsa.newkeys(512)

此時(shí)的狀態(tài)

rsa非對稱加密如何在python項(xiàng)目中使用

2.2、發(fā)送者加密

# 2、發(fā)送者(B)使用接收者(A)的公鑰去加密消息
# rsa只能處理字節(jié)類型, 故字符串類型需要轉(zhuǎn)化為字節(jié)類型
love_talk = "Lemon little girl, I love you very much!".encode("utf-8")
cryto_info = rsa.encrypt(love_talk, lemon_pub)  # 使用接收者(A)的公鑰加密

此時(shí)狀態(tài)

rsa非對稱加密如何在python項(xiàng)目中使用

2.3、接收者解密

# 3. 接收者(A)使用自己的私鑰去解密消息
talk_real = rsa.decrypt(cryto_info, lemon_priv)
talk_real2 = talk_real.decode("utf-8")
print(talk_real2)

rsa非對稱加密如何在python項(xiàng)目中使用

3、其他場景加密解密

import rsa

# 生成密鑰
pubkey, privkey = rsa.newkeys(512)

# 保存密鑰
print("==============保存密鑰===============")
with open('public.pem' ,'w+') as f:
  f.write(pubkey.save_pkcs1().decode())
with open('private.pem' ,'w+') as f:
  f.write(privkey.save_pkcs1().decode())

#導(dǎo)入密鑰
with open('public.pem' ,'r') as f:
  pubkey = rsa.PublicKey.load_pkcs1(f.read().encode())
with open('private.pem' ,'r') as f:
  privkey = rsa.PrivateKey.load_pkcs1(f.read().encode())

"""
加密 RSA
"""
def rsa_encrypt(message):
  crypto_email_text = rsa.encrypt(message.encode(), pubkey)
  return crypto_email_text

text = rsa_encrypt("first test rsa")
print(text)

"""
解密
"""
def rsa_decrypt(message):
  message_str = rsa.decrypt(message,privkey).decode()
  return message_str

newmessage=rsa_encrypt("haha,one two three four smile!")
message = rsa_decrypt(newmessage)
print("\n",message)

"""
簽名
"""

message = '這是重要指令:...'
crypto_email_text = rsa.sign(message.encode(), privkey, 'SHA-1')

"""
驗(yàn)證
"""
# 收到指令明文、密文,然后用公鑰驗(yàn)證,進(jìn)行身份確認(rèn)
rsa.verify(message.encode(), crypto_email_text, pubkey)

4、加密過程的封裝

# 導(dǎo)入base64模塊來進(jìn)行base64編碼
import base64
import rsa

class HandleSign:
  # 定義服務(wù)器公鑰, 往往可以存放在公鑰文件中
  server_pub = """
    -----BEGIN PUBLIC KEY-----
    MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQENQujkLfZfc5Tu9Z1LprzedE
    O3F7gs+7bzrgPsMl29LemonPYvIG8C604CprLittlenJpnhWu2lGirlWZyLq6sBr
    tuPorOc42+gInFfyhJAwdZB6Sqlove7bW+jNe5youDtU7very6Gx+muchGo8Dg+S
    kKlZFc8Br7SHtbL2tQIDAQAB
    -----END PUBLIC KEY-----
    """

  @classmethod
  def to_encrypt(cls, msg, pub_key=None):
    """
    非對稱加密
    :param msg: 待加密字符串或者字節(jié)
    :param pub_key: 公鑰
    :return: base64密文字符串
    """
    if isinstance(msg, str):      # 如果msg為字符串, 則轉(zhuǎn)化為字節(jié)類型
      msg = msg.encode('utf-8')
    elif isinstance(msg, bytes):    # 如果msg為字節(jié)類型, 則無需處理
      pass
    else:                # 否則拋出異常
      raise TypeError('msg必須為字符串或者字節(jié)類型!')

    if not pub_key:           # 如果pub_key為空, 則使用全局公鑰
      pub_key = cls.server_pub.encode("utf-8")
    elif isinstance(pub_key, str):   # 如果pub_key為字符串, 則轉(zhuǎn)化為字節(jié)類型
      pub_key = pub_key.encode('utf-8')
    elif isinstance(pub_key, bytes):  # 如果msg為字節(jié)類型, 則無需處理
      pass
    else:                # 否則拋出異常
      raise TypeError('pub_key必須為None、字符串或者字節(jié)類型!')

    public_key_obj = rsa.PublicKey.load_pkcs1_openssl_pem(pub_key) # 創(chuàng)建 PublicKey 對象
    #2.創(chuàng)建 PublicKey 對象
    #public_key_obj = rsa.PublicKey.load_pkcs1(pub_key)

    cryto_msg = rsa.encrypt(msg, public_key_obj) # 生成加密文本
    cipher_base64 = base64.b64encode(cryto_msg)  # 將加密文本轉(zhuǎn)化為 base64 編碼

    return cipher_base64.decode()  # 將字節(jié)類型的 base64 編碼轉(zhuǎn)化為字符串類型


if __name__ == '__main__':
  # 待加密字符串或者字節(jié)
  love_talk = "Lemon little girl, I love you very much!"

  #1.用自己生成的publickye測試下
  #lemon_pub,lemon_priv=rsa.newkeys(512)
  #lemon_pub2=lemon_pub.save_pkcs1()

  # 調(diào)用to_encrypt類方法來進(jìn)行加密
  cryto_info = HandleSign.to_encrypt(love_talk)
  print(cryto_info)

關(guān)于rsa非對稱加密如何在python項(xiàng)目中使用就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI