python 对于实现rsa加密算法
import base64 import rsa class GenerateKey(object): d = "ascii" def generate_keys(self, bits=1024): (pubkey, privkey) = rsa.newkeys(bits) pem_pubkey = rsa.PublicKey.save_pkcs1(pubkey).decode(self.d) b64_pubkey = self.b64_encrypt(pem_pubkey).decode(self.d) pem_privkey = rsa.PrivateKey.save_pkcs1(privkey).decode(self.d) b64_privkey = self.b64_encrypt(pem_privkey).decode(self.d) return b64_pubkey, b64_privkey def decrypt( self, ciphertext: str | bytes, private_key_pem: bytes | str | rsa.PrivateKey ) -> str: """私钥入参必须是pem格式, 不接受(模数,指数) 的类型 Args: ciphertext (str): 字符串 private_key_pem (str): pem字节串 Returns: _type_: _description_ """ if isinstance(private_key_pem, (str, bytes)): private_key_pem = private_key_pem.strip() if isinstance(private_key_pem, str): private_key_pem = private_key_pem.encode() private_key = rsa.PrivateKey.load_pkcs1( private_key_pem, "PEM" ) # 解析成为 (模数,指数) 类型 else: private_key = private_key_pem if isinstance(ciphertext, str): ciphertext = ciphertext.encode() decrypted_text = rsa.decrypt(ciphertext, private_key) return decrypted_text.decode() def encrypt(self, plaintext: str | bytes, public_key: bytes | str | rsa.PublicKey): # rsa 加密函数 """仅接受pem格式数据,不支持(模数,指数) 的类型 Args: plaintext (str): 需要加密的文本 public_key (rsa.PublicKey): 使用的公钥字节串 Returns: _type_: _description_ """ if isinstance(plaintext, str): plaintext = plaintext.encode() if isinstance(public_key, (str, bytes)): public_key = public_key.strip() if isinstance(public_key, str): public_key = public_key.encode() public_key = rsa.PublicKey.load_pkcs1(public_key, "PEM") # 解析成为 (模数,指数) 类型 else: public_key = public_key ciphertext = rsa.encrypt(plaintext, public_key) return ciphertext.decode() def b64_encrypt(self, test: str): # b64编码 return base64.b64encode(test.encode(self.d)) def b64_decrypt(self, test: str): # b64解码 return base64.b64decode(test.encode(self.d))
前端与后端传输时,前端可能传给后端的是b64对象,后端解密时需要注意。