Cryptography With Python 简明教程

RSA Cipher Encryption

在本章中,我们将重点介绍 RSA 密码加密的不同实现以及涉及此算法的功能。您可以参考或包含此 Python 文件来实现 RSA 密码算法的实现。

In this chapter, we will focus on different implementation of RSA cipher encryption and the functions involved for the same. You can refer or include this python file for implementing RSA cipher algorithm implementation.

包含在加密算法中的模块如下:

The modules included for the encryption algorithm are as follows −

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA512, SHA384, SHA256, SHA, MD5
from Crypto import Random
from base64 import b64encode, b64decode
hash = "SHA-256"

出于更好的安全目的,我们已经将哈希值初始化为 SHA-256。我们将使用一个函数,以使用以下代码生成新密钥或一对公钥和私钥。

We have initialized the hash value as SHA-256 for better security purpose. We will use a function to generate new keys or a pair of public and private key using the following code.

def newkeys(keysize):
   random_generator = Random.new().read
   key = RSA.generate(keysize, random_generator)
   private, public = key, key.publickey()
   return public, private
def importKey(externKey):
   return RSA.importKey(externKey)

对于加密,请使用遵循 RSA 算法的以下函数:

For encryption, the following function is used which follows the RSA algorithm −

def encrypt(message, pub_key):
   cipher = PKCS1_OAEP.new(pub_key)
   return cipher.encrypt(message)

两个参数是必需的: messagepub_key ,它们指公钥。公钥用于加密,而私钥用于解密。

Two parameters are mandatory: message and pub_key which refers to Public key. A public key is used for encryption and private key is used for decryption.

下面提到了加密过程的完整程序:

The complete program for encryption procedure is mentioned below −

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA512, SHA384, SHA256, SHA, MD5
from Crypto import Random
from base64 import b64encode, b64decode
hash = "SHA-256"

def newkeys(keysize):
   random_generator = Random.new().read
   key = RSA.generate(keysize, random_generator)
   private, public = key, key.publickey()
   return public, private

def importKey(externKey):
   return RSA.importKey(externKey)

def getpublickey(priv_key):
   return priv_key.publickey()

def encrypt(message, pub_key):
   cipher = PKCS1_OAEP.new(pub_key)
   return cipher.encrypt(message)