Rsa Python module for use asymmetric encryption and decryption

Rsa Python module for use asymmetric encryption and decryption

1, a brief introduction:

RSA encryption algorithm is an asymmetric encryption algorithm to derive the decryption key is computationally infeasible "cryptosystem encryption key is known by the encryption key (i.e. public key) PK is the public information, and the decryption - key (secret key) SK is confidential.
RSA key length of at least 500, is generally recommended to use 1024 as the secret key length .RSA improve the level increases rapidly.
due to the nature of RSA, a 1024 the encryption key can only 117 bytes of data, when the amount of data exceeds 117 bytes, the program will throw an exception - from big brother

2, code implementation:

To some chiefs code :

import rsa


# 一、生成公钥及私钥, 并保存
public_key, private_key = rsa.newkeys(1024)  # 生成公钥和私钥
# 将生成的公钥和私钥进行转换,以便存储
pub = public_key.save_pkcs1()
pri = private_key.save_pkcs1('PEM')  # save_pkcsl()是内置方法,其默认参数是‘PEM’
with open('pubkey.pem', mode='wb') as f, open('privkey.pem', mode='wb') as f1:
    f.write(pub)  # 打开两个文件,分别存储公钥及私钥
    f1.write(pri)


# 二. 使用公钥加密, 私钥解密
def func():
    with open('pubkey.pem', mode='rb') as f, open('privkey.pem', 'rb') as f1:
        pub = f.read()  # 从文件中再读出公钥和私钥
        pri = f1.read()
        public_key = rsa.PublicKey.load_pkcs1(pub)  # 转换为原始状态
        private_key = rsa.PrivateKey.load_pkcs1(pri)
    message = "rsa加密测试"
    info = rsa.encrypt(message.encode('utf-8'), public_key)  # 使用公钥加密内容,内容必须是二进制
    msg = rsa.decrypt(info, private_key)  # 使用私钥解密,获得解密后的内容
    print(msg.decode('utf-8'))  # 使用之前记得先解码

3, code upgrades:

I will now packaged as described above snippet a Rsa class (with a method comprising of: __init__- initialization method key_transform_store- storing the public and private key method, encry- an encryption method, decry- decryption method), when used, direct the following code snippet Lin Dao where we need to go quote: create a Rsa object and then call a method which can be:

import rsa


class Rsa(object):
    """RSA加密、解密"""

    def __init__(self, number, pub_path='public_key.pem', priv_path='private_key.pem'):
        """

        :param pub_path: the path to public key, default its path is public_key.pem
        :param priv_path: the path to private key, default its path is private_key.pem
        """
        # Generate the public and private keys, and returns them
        self.public_key, self.private_key = rsa.newkeys(number)

        self.public_key_path = pub_path
        self.private_key_path = priv_path

    def key_transform_store(self):
        """
        convert and save the generated public and private keys to a file
        :return: None
        """
        # convert the generated public and private keys for storage
        pub = self.public_key.save_pkcs1()
        pri = self.private_key.save_pkcs1('PEM')

        # open two files to store the public key and private key respectively
        
        with open(self.public_key_path, mode='wb') as f:
            f.write(pub)

        with open(self.private_key_path, mode='wb') as f1:
            f1.write(pri)

    def encry(self, info):
        """
        encrypt information
        :param info: the original string information to be encrypted
        :return:info_encrypted
        """
        # read the public key from the file
        with open(self.public_key_path, mode='rb') as f:
            pub = f.read()
            # convert pub to original state
            public_key = rsa.PublicKey.load_pkcs1(pub)

        # use the public key to encrypt the content, which must be binary
        info_encrypted = rsa.encrypt(info.encode('utf-8'), public_key)
        return info_encrypted

    def decry(self, info_encrypted):
        """
        decrypt information
        :param info_encrypted: encrypted information
        :return: info
        """
        # read the private key from the file
        with open(self.private_key_path, 'rb') as f:
            pri = f.read()
            # convert pri to original state
            private_key = rsa.PrivateKey.load_pkcs1(pri)

        # decrypt with private key to obtain the decrypted content
        msg = rsa.decrypt(info_encrypted, private_key)
        info = msg.decode('utf-8')  # decode
        return info


rsa_obj = Rsa(1024)  # 实例化
rsa_obj.key_transform_store()  # 
info_encrypted = rsa_obj.encry('我是真心喜欢你的。')  # 加密
print(info_encrypted)
info = rsa_obj.decry(info_encrypted)  # 解密
print(info)  # 我是真心喜欢你的。

Here there will be a problem: Due to the nature of RSA, a 1024-bit key encryption only 117 bytes of data, when the amount of data over 117 bytes, the program will throw an exception. The following tests will be thrown:OverflowError: 189 bytes needed for message, but there is only space for 117

rsa_obj = Rsa(1024)  # 实例化
rsa_obj.key_transform_store()  # 
info_encrypted = rsa_obj.encry('我是真心喜欢你的。我是真心喜欢你的。我是真心喜欢你的。我是真心喜欢你的。我是真心喜欢你的。我是真心喜欢你的。我是真心喜欢你的。')  # 加密
print(info_encrypted)
info = rsa_obj.decry(info_encrypted)  # 解密
print(info)

。。。。。。

Postscript: In general use, the data will first bas64 encryption, and then use rsa encryption of the encrypted content, the content of the final decrypted bas64 rsa decryption.

the above.

Guess you like

Origin www.cnblogs.com/sirxy/p/12141633.html