1. 程式人生 > 實用技巧 >rsa公鑰私鑰

rsa公鑰私鑰

rsa公鑰私鑰

import rsa
import base64

# 生成公鑰私鑰物件
pub_key_obj, priv_key_obj = rsa.newkeys(1024)

# 轉化為字串
pub_key_str = pub_key_obj.save_pkcs1()
priv_key_str = priv_key_obj.save_pkcs1()

print('公鑰:{}\n私鑰:{}'.format(pub_key_str, priv_key_str))

# 去掉字首
pub_key_code = base64.standard_b64encode(pub_key_str)
priv_key_code = base64.standard_b64encode(priv_key_str)

print('公鑰:{}\n私鑰:{}'.format(pub_key_code, priv_key_code))


# 公鑰加密
def encrypt(pub_key, data):
    """
    :param pub_key: 公鑰
    :param data: 要加密的資料,長度受rsa.newkeys(1024)影響
    :return: bytes,加密後的資料
    """
    key_str = base64.standard_b64decode(pub_key)
    pk = rsa.PublicKey.load_pkcs1(key_str)
    val = rsa.encrypt(data.encode('utf-8'), pk)
    return val

pub = encrypt(pub_key_code, 'hxf')
print(pub)


# 私鑰解密
def decrypt(priv_key, data):
    """
    :param priv_key: 私鑰
    :param data: 被加密的資料
    :return: str,原始資料
    """
    key_str = base64.standard_b64decode(priv_key)
    pk = rsa.PrivateKey.load_pkcs1(key_str)
    val = rsa.decrypt(data, pk).decode('utf-8')
    return val


print(decrypt(priv_key_code, pub))