python实现rsa的公钥加密、私钥解密及私钥加密、公钥解密

rsa包中现成的公钥加密、私钥解密代码

import rsa
def rsa_encrypt(d_str):
    # 生成公钥和私钥
    pubkey, privkey = rsa.newkeys(1024)
    # 将字符串进行编码
    content = d_str.encode('utf-8')
    # 公钥加密
    crypto = rsa.encrypt(content, pubkey)
    print ('加密后', crypto)
    return crypto, privkey

def rsa_decrypt(crypto, privkey):
    # 解密
    content = rsa.decrypt(crypto, privkey)
    # 解码
    content = content.decode('utf-8')
    print ('解密结果', content)
if __name__ == '__main__':
    a = rsa_encrypt('hello word')
    rsa_decrypt(*a)

但没有现成的私钥加密、公钥解密的实现

通过阅读源码,整理出一份简易的实现方式

import rsa
from rsa import common, transform, core
import os


def _pad_for_encryption(message, target_length):

    max_msglength = target_length - 11
    msglength = len(message)

    if msglength > max_msglength:
        raise OverflowError(
            "%i bytes needed for message, but there is only"
            " space for %i" % (msglength, max_msglength)
        )

    padding = b""
    padding_length = target_length - msglength - 3

    while len(padding) < padding_length:
        needed_bytes = padding_length - len(padding)
        new_padding = os.urandom(needed_bytes + 5)
        new_padding = new_padding.replace(b"\x00", b"")
        padding = padding + new_padding[:needed_bytes]

    assert len(padding) == padding_length

    return b"".join([b"\x00\x02", padding, b"\x00", message])

def decrypt(data: bytes, d, n):
    num = transform.bytes2int(data)
    decrypto = core.decrypt_int(num, d, n)
    out = transform.int2bytes(decrypto)
    sep_idx = out.index(b"\x00", 2)
    out = out[sep_idx + 1 :]
    return out

def encrypt(data: bytes, d, n):
    keylength = common.byte_size(n)
    padded = _pad_for_encryption(data, keylength)
    num = transform.bytes2int(padded)
    decrypto = core.encrypt_int(num, d, n)
    out = transform.int2bytes(decrypto)
    return out

if __name__ == '__main__':

    pubkey, privkey = rsa.newkeys(2048)
    data = '123456789'
    data2b = data.encode('utf8')
    edata = encrypt(data2b, pubkey.e, pubkey.n)
    ddata = decrypt(edata, privkey.d, privkey.n)
    ddata = ddata.decode('utf8')
    assert ddata == data

其实上述代码也能实现公钥加密和私钥解密功能,只要改成下面即可

   edata = encrypt(data2b, privkey.d, privkey.n)
   ddata = decrypt(edata, pubkey.e, pubkey.n)

你可能感兴趣的:(python)