一、代碼
# 導入rsa庫 import rsa.common class RSA(object): def __init__(self): self.key= rsa.newkeys(256) self.pub_key=rsa.PublicKey(self.key[1].n,self.key[1].e) self.pri_key=rsa.PrivateKey(self.key[1].n,self.key[1].e,self.key[1].d,self.key[1].p,self.key[1].q) # rsa 加密 def rsa_encrypt_bytes(self,bytes_str): if not isinstance(bytes_str, bytes): return None key_length = rsa.common.byte_size(self.key[1].n) max_msg_length = key_length - 11 count = len(bytes_str) // max_msg_length if len(bytes_str) % max_msg_length > 0: count = count + 1 cry_bytes = b'' # rsa加密要以max_msg_length分組, 每組分別加密(加密的數據長度為key_length, 解密時每key_length長度解密然后相加) for i in range(count): start = max_msg_length * i size = max_msg_length content = bytes_str[start: start + size] # rsa 分組 加密 crypto = rsa.encrypt(content, self.pub_key) cry_bytes = cry_bytes + crypto return cry_bytes # rsa 解密, bytes_string是rsa_encrypt_hex, rsa_encrypt_bytes的返回值 def rsa_decrypt(self,bytes_string): key_length = rsa.common.byte_size(self.key[1].n) if len(bytes_string) % key_length != 0: # 如果數據長度不是key_length的整數倍, 則數據是無效的 return None count = len(bytes_string) // key_length d_cty_bytes = b'' # 分組解密 for i in range(count): start = key_length * i size = key_length content = bytes_string[start: start + size] # rsa 分組 解密 d_crypto = rsa.decrypt(content, self.pri_key) d_cty_bytes = d_cty_bytes + d_crypto return d_cty_bytes # rsa 加密, 注意: 這里是傳遞的是16進制字符串 def rsa_encrypt_hex(self,hex_string): # bytes.fromhex字符串轉十六進制方法 return self.rsa_encrypt_bytes(bytes.fromhex(hex_string)) # rsa 庫的測試 def test_encrypt_decrypt(): # 產生公鑰私鑰 (pub, pri) = rsa.newkeys(256) # 構建新的公鑰私鑰 pubkey = rsa.PublicKey(pri.n, pri.e) pri_key = rsa.PrivateKey(pri.n, pri.e, pri.d, pri.p, pri.q) message = b'\x00\x00\x00\x00\x01' # 加密 message crypto = rsa.encrypt(message, pubkey) # 解密 d_crypto = rsa.decrypt(crypto, pri_key) print(d_crypto) if __name__ == '__main__': r=RSA() bts_str = 'hello world 中文'.encode() crypto_bytes = r.rsa_encrypt_bytes(bts_str) d_crypto_bytes = r.rsa_decrypt(crypto_bytes) print(d_crypto_bytes.decode()) hex_str = '001122334455AAff' crypto_bytes = r.rsa_encrypt_hex(hex_str) d_crypto_bytes = r.rsa_decrypt(crypto_bytes) # bytes.hex()十六進制轉字符串方法 print(d_crypto_bytes.hex())