# coding: utf-8

"""加密算法：公钥(私钥)加密，私钥解密"""

from Crypto.PublicKey import RSA
from Crypto import Random

DATA = 'Hello, word!'
PRIVATE_KEY_PEM = """-----<KEY>"""
PUBLIC_KEY_PEM = """-----<KEY>"""


def _encrypt_by_public():
    random_func = Random.new().read
    public_key = RSA.importKey(PUBLIC_KEY_PEM)
    encrypted = public_key.encrypt(DATA, random_func)
    return encrypted


def _encrypt_by_private():
    random_func = Random.new().read
    private_key = RSA.importKey(PRIVATE_KEY_PEM)
    encrypted = private_key.encrypt(DATA, random_func)
    return encrypted


def _decrypt_by_private(msg_encrypt):
    private_key = RSA.importKey(PRIVATE_KEY_PEM)
    decrypted = private_key.decrypt(msg_encrypt)
    return decrypted


def _decrypt_by_public_err(msg_encrypt):
    """无效"""
    public_key = RSA.importKey(PUBLIC_KEY_PEM)
    decrypted = public_key.decrypt(msg_encrypt)
    return decrypted

if __name__ == '__main__':
    print(DATA, _decrypt_by_private(_encrypt_by_public()))
    print(DATA, _decrypt_by_private(_encrypt_by_private()))
    try:
        print(DATA, _decrypt_by_public_err(_encrypt_by_public()))
    except TypeError as e1:
        print(DATA, e1)
    try:
        print(DATA, _decrypt_by_public_err(_encrypt_by_private()))
    except TypeError as e2:
        print(DATA, e2)

# coding: utf-8

"""加密算法：公钥(私钥)加密，私钥解密"""

from Crypto.PublicKey import RSA
from Crypto import Random

DATA = 'Hello, word!'
PRIVATE_KEY_PEM = """-----<KEY>"""
PUBLIC_KEY_PEM = """-----<KEY>"""


def _encrypt_by_public():
    random_func = Random.new().read
    public_key = RSA.importKey(PUBLIC_KEY_PEM)
    encrypted = public_key.encrypt(DATA, random_func)
    return encrypted


def _encrypt_by_private():
    random_func = Random.new().read
    private_key = RSA.importKey(PRIVATE_KEY_PEM)
    encrypted = private_key.encrypt(DATA, random_func)
    return encrypted


def _decrypt_by_private(msg_encrypt):
    private_key = RSA.importKey(PRIVATE_KEY_PEM)
    decrypted = private_key.decrypt(msg_encrypt)
    return decrypted


def _decrypt_by_public_err(msg_encrypt):
    """无效"""
    public_key = RSA.importKey(PUBLIC_KEY_PEM)
    decrypted = public_key.decrypt(msg_encrypt)
    return decrypted

if __name__ == '__main__':
    print(DATA, _decrypt_by_private(_encrypt_by_public()))
    print(DATA, _decrypt_by_private(_encrypt_by_private()))
    try:
        print(DATA, _decrypt_by_public_err(_encrypt_by_public()))
    except TypeError as e1:
        print(DATA, e1)
    try:
        print(DATA, _decrypt_by_public_err(_encrypt_by_private()))
    except TypeError as e2:
        print(DATA, e2)

# coding: utf-8 加密算法：公钥(私钥)加密，私钥解密 -----<KEY> -----<KEY> 无效