非对称加密算法RSA加密传输数据python3源代码实现

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

import rsa

# RSA 算法规定:
# 待加密的字节数不能超过密钥的长度值除以 8 再减去 11

NBIT = 4096
CAN_ENCODE_LEN = NBIT // 8 - 11
PER_ENCODE_LEN = CAN_ENCODE_LEN - (CAN_ENCODE_LEN % 2)
PER_DECODE_LEN = CAN_ENCODE_LEN + 11

PUBKEY_STR = """"""

PRIKEY_STR = """"""


def gen_pem_file():
    (public_key, private_key) = rsa.newkeys(NBIT)  # rsa-4096 加密得到公钥和私钥

    # 将公钥保存到文件
    with open('public.pem', 'wb') as file_pub:
        file_pub.write(public_key.save_pkcs1())

    # 将私钥保存到文件
    with open('private.pem', 'wb') as file_pri:
        file_pri.write(private_key.save_pkcs1())

if not PUBKEY_STR:
    # 取出公钥
    try:
        with open('public.pem', 'rb') as __file_pub:
            PUBKEY_STR = __file_pub.read()
    except FileNotFoundError:
        gen_pem_file()
        with open('public.pem', 'rb') as __file_pub:
            PUBKEY_STR = __file_pub.read()

if not PRIKEY_STR:
    # 取出私钥
    try:
        with open('private.pem', 'rb') as __file_pri:
            PRIKEY_STR = __file_pri.read()
    except FileNotFoundError:
        gen_pem_file()
        with open('public.pem', 'rb') as __file_pub:
            PUBKEY_STR = __file_pub.read()
        with open('private.pem', 'rb') as __file_pri:
            PRIKEY_STR = __file_pri.read()


PUBKEY = rsa.PublicKey.load_pkcs1(PUBKEY_STR)
PRIKEY = rsa.PrivateKey.load_pkcs1(PRIKEY_STR)


# 加密字符串string
def rsa_str_encode(s):
    s = s.encode('utf-16')
    len_s = len(s)
    res = b''
    res_len=0
    while len_s - res_len > PER_ENCODE_LEN:
        res += rsa.encrypt(s[res_len:res_len+PER_ENCODE_LEN], PUBKEY)  # 使用公钥去加密字符串
        res_len+=PER_ENCODE_LEN
        print('RSA加密 %d ... %.2f%%' % (res_len, 100* res_len/len_s))
    res += rsa.encrypt(s[res_len:], PUBKEY)  # 使用公钥去加密字符串
    return res


# 解密字符串string
def rsa_str_decode(s):
    len_s = len(s)
    res = b''
    res_len=0
    while len_s - res_len > PER_DECODE_LEN:
        res += rsa.decrypt(s[res_len:res_len+PER_DECODE_LEN], PRIKEY)  # 用私钥去解密
        res_len+=PER_DECODE_LEN
        print('RSA解密 %d ... %.2f%%' % (res_len, 100 * res_len / len_s))
    res += rsa.decrypt(s[res_len:], PRIKEY)
    return res.decode('utf-16')


# 加密字符串string list
def rsa_strs_encode(s):
    s = s.encode('utf-16')
    len_s = len(s)
    res_len=0
    while len_s - res_len > PER_ENCODE_LEN:
        yield rsa.encrypt(s[res_len:res_len+PER_ENCODE_LEN], PUBKEY)  # 使用公钥去加密字符串
        res_len+=PER_ENCODE_LEN
    yield rsa.encrypt(s[res_len:], PUBKEY)  # 使用公钥去加密字符串


# 解密字符串string list
def rsa_strs_decode(ss):
    for i, line in enumerate(ss):
        res = rsa.decrypt(line, PRIKEY)
        try:
            yield res.decode('utf-16')
        except UnicodeDecodeError:
            import traceback
            print(traceback.format_exc())

if __name__ == '__main__':
    en_str = rsa_str_encode('dsde军鳄科!@#¥cvr$#2#@1~~!@!#,.,2p4pfvwdwefv1234678435092430r098ygoiufvre2vdvwdvwfvw,.efkiv3evclkvs你'*12)
    de_crypt = rsa_str_decode(en_str)  # 用私钥去解密
    print(de_crypt)

    en_strs = rsa_strs_encode(
        'dsde军鳄科!@#¥cvr$#2#@1~~!@!#,.,2p4pfvwdwefv1234678435092430r098ygoiufvre2vdvwdvwfvw,.efkiv3evclkvs你' * 122)
    de_crypts = rsa_strs_decode(en_strs)  # 用私钥去解密
    # print(''.join(de_crypt))
    for _ in de_crypts:
        print(_)

转载于:https://my.oschina.net/readerror/blog/2885260

你可能感兴趣的:(非对称加密算法RSA加密传输数据python3源代码实现)