RSA--通過模和指數加密模板--無填充
阿新 • • 發佈:2020-08-20
一.模板一
import rsa #模 m = "ae068c2039bd2d82a529883f273cf20a48e0b6faa564e740402375a9cb332a029b8492ae342893d9c9d53d94d3ab8ae95de9607c2e03dd46cebe211532810b73cc764995ee61ef435437bcddb3f4a52fca66246dbdf2566dd85fbc4930c548e7033c2bcc825b038e8dd4b3553690e0c438bbd5ade6f5a476b1cbc1612f5d501f" #指數 e = '10001' #加密引數 message = '123456' class Encrypt(object): def __init__(self, e, m): self.e = e self.m = m def encrypt(self, message): mm = int(self.m, 16) ee = int(self.e, 16) rsa_pubkey = rsa.PublicKey(mm, ee) crypto = self._encrypt(message.encode(), rsa_pubkey) return crypto.hex() def _pad_for_encryption(self, message, target_length): message = message[::-1] max_msglength = target_length - 11 msglength = len(message) padding = b'' padding_length = target_length - msglength - 3 for i in range(padding_length): padding += b'\x00' return b''.join([b'\x00\x00', padding, b'\x00', message]) def _encrypt(self, message, pub_key): keylength = rsa.common.byte_size(pub_key.n) padded = self._pad_for_encryption(message, keylength) payload = rsa.transform.bytes2int(padded) encrypted = rsa.core.encrypt_int(payload, pub_key.e, pub_key.n) block = rsa.transform.int2bytes(encrypted, keylength) return block if __name__ == '__main__': en = Encrypt(e, m) print(en.encrypt(message))
二.模板二
import codecs def rsa_encrypt(content): public_exponent = '010001' public_modulus = 'ae068c2039bd2d82a529883f273cf20a48e0b6faa564e740402375a9cb332a029b8492ae342893d9c9d53d94d3ab8ae95de9607c2e03dd46cebe211532810b73cc764995ee61ef435437bcddb3f4a52fca66246dbdf2566dd85fbc4930c548e7033c2bcc825b038e8dd4b3553690e0c438bbd5ade6f5a476b1cbc1612f5d501f' content = content[::-1] rsa = int(codecs.encode(content.encode('utf-8'), 'hex_codec'), 16) ** int(public_exponent, 16) % int(public_modulus, 16) # 把10進位制數rsa轉為16進位制('x'表示16進位制),再取前256位,不夠的在最前面補0 return format(rsa, 'x').zfill(256)
三.模板三
import math if __name__ == '__main__': # 實為16進位制串,前補0 e = '' # m也需要補00 m = '008eb933413be3234dddd2730fbb1d05c8848a43d5dc3bdd997f2a9935fba6beb9ffb36854482b0b46cf7e6f9afbbe2e2e7d606fde20bec57dbf722e7985192e8813e6b67628a6f202cf655b7d2ffce4e9dc682dd6034ae706c8e255f25e4051b9ca43f25b3ad686aac9c8f6aeb71d921c13a255c806f78a5a7b9a356c2dd274e3' m = int.from_bytes(bytearray.fromhex(m), byteorder='big') e = int.from_bytes(bytearray.fromhex(e), byteorder='big') # js加密為反向,為保持一致原文應反向處理,所以這裡原文實際為204dowls plaintext = 'slwod402'.encode('utf-8') # 無填充加密邏輯 input_nr = int.from_bytes(plaintext, byteorder='big') crypted_nr = pow(input_nr, e, m) keylength = math.ceil(m.bit_length() / 8) crypted_data = crypted_nr.to_bytes(keylength, byteorder='big') print(crypted_data.hex())