前言:网上有很多关于使用pyCryptodome库进行RSA加解密以及签名,但是大部分都是根据该库的开发文档进行的,只能算是最基础的版本。我们知道,RSA是明文分组加密,也就是说,它的加密的消息是定长的。但是现实场景中,我们大部分遇上的都是不定长消息,而超长消息在现实中更为常见。所以如何切割与填充,这是在实际应用中值得关注的问题所在。
观前提醒
本博客代码是查阅和分析pyCryptodome库关于RSA源码后,写的实际调用的代码。采用的是python语言编写,如果是Java,实际上也可以参考思路进行改造。
该博客写作之前,已经将分析源码的PPT上传,客官可移步: 基于RSA的PyCryptodome库讲解.pptx.(为卑微的一级菜鸡捐献一点点积分)
加解密之 ---- pkcs
网上的大部分代码都是遵循pkcs协议的,但是其测试的message长度都是很小。而实际中,pkcs协议只能抵御选择明文攻击(简单来讲,同样一个消息经过同样一个加密流程,最后出的密文结果还会是不一样的,这样可以防止别人使用各种搭配明文,推出密文甚至是秘钥。)pkcs协议是比较早期的协议,可以满足一般的加解密需求。
from Crypto.PublicKey import RSA
import Crypto.Cipher.PKCS1_v1_5 as cipher
def generate_key(bits):
'''
:param bits: the length of RSA key
:return: RSAKey object
'''
return RSA.generate(bits)
def encrypt(message, pk):
'''
:param message: the message would be encrypted
:param pk: the public key
:return: a cipher text for the message though encrypt
:rtype: bytes
'''
cipher_obj = cipher.new(RSA.importKey(pk))
org_bytes = message.encode()
length_en = RSA.RsaKey.size_in_bytes(RSA.importKey(pk)) - 11 # 2048/8-11=245
res_en = b''
for i in range(0, len(org_bytes), length_en):
res_en += cipher_obj.encrypt(org_bytes[i: i + length_en])
cipher_text = res_en
return cipher_text
def decrypt(cipher_text, sk):
'''
:param message: the cipher text would be decrypted
:param pk: the private key
:return: a message for the cipher text though decrypt
:rtype: string
'''
cipher_obj =