您的当前位置:首页正文

python RSA非对称加解密模块[M2Crypto]

2024-11-20 来源:个人技术集锦

python 实现rsa对称加解密目前有三个库:rsa、pycryptodome、M2Crypto

前两个库只能实现公钥加密私钥解密,M2Crypto可以实现公私钥互相加解密

M2Crypto的安装:

一、环境

1.操作系统:CentOS7.3

2.python: python3.6

3.M2Crypto安装:

(1)yum -y install python-devel

(2)pip install M2Crypto

二、代码

1.生成公私钥对

from M2Crypto import RSA

# 2048代表生成密钥的位数,65537代表公钥的指数
key = RSA.gen_key(2048, 65537)
key.save_key("private_key", None)
key.save_pub_key("public_key")

2.导入公私钥证书字符串加密

from M2Crypto import RSA
from M2Crypto import BIO
from binascii import a2b_hex, b2a_hex

PUBLIC_KEY = '''
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5VavyEaIAZEQzx9S5zdp
hrkluga2IDuxodXTUkVqTeMBx3j4iHv9P/Ci7+WZowXyCA9v3cuPaYjAFIbCOErW
QKP9w6xWEtlvFuFs0AJ4QIXlFM2UDYuTGzsrAH7wI7tJl5Bd2ugCl+YFz85J1XE1
3A1knlk4eoQ0UCaFCoHjqgI0U6+Immvv51kQ0R00UHjOkPI3WIoulFxXULw/Svpk
YHeWh3CgwFJridqf3w2wyXJOhKZWUt+ZadTy+2OHJ++vmpYaFFolN2fWSMCI682j
o47ZP2KTH/LTEYfhByAgkF3+09JZB6idgz3hgyqcRTdCQb/ziJD2D/z3WIAf0ts2
vQIDAQAB
-----END PUBLIC KEY-----
'''

PRIVATE_KEY = '''
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEA5VavyEaIAZEQzx9S5zdphrkluga2IDuxodXTUkVqTeMBx3j4
iHv9P/Ci7+WZowXyCA9v3cuPaYjAFIbCOErWQKP9w6xWEtlvFuFs0AJ4QIXlFM2U
DYuTGzsrAH7wI7tJl5Bd2ugCl+YFz85J1XE13A1knlk4eoQ0UCaFCoHjqgI0U6+I
mm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lYCD8R3rsxMTP+AXNBZ1KRTp1nmA08rV9
1Q8tR9VHkM0mF3a3TTURQimefyFDB5drQgNXitLKxJIdw+REAtAAP16gQaC/1ohw
MMaPd00+vnwUgxd5gdifqbyOBRYnFvYgjWkcgQAVwZddIHcUIIiTDelaG+9bl6rU
rVAJ8YkCgYEAyjNUvkjnuUz22aOO4oHsmtlyAhOJzFiV+WPgvFs+p5ltC2LzbnS6
L6IP9kl+A6twOxCEXGMjI7xHw1CP40kaUZQcesRdKyNg0PSWtKbI6h715Wxij7A6
DACJLae86hhP7nSI4X787UR+UP5p+NYkU0E9hQP7t+uyWTox7tM3tUE=
-----END RSA PRIVATE KEY-----
'''


def load_pub_key_string(string):
    bio = BIO.MemoryBuffer(string)
    return RSA.load_pub_key_bio(bio)


def block_data(texts, block_size):
    for i in range(0, len(texts), block_size):
        yield texts[i:i + block_size]


def encrypt(texts):
    ciphertext = b""
    block_size = 256 - 11

    for text in block_data(texts.encode('utf-8'), block_size):
        current_text = pri_key.private_encrypt(text, RSA.pkcs1_padding)
        ciphertext  += current_text

    return b2a_hex(ciphertext)


def decrypt(texts):
    plaintext = b""
    block_size = 256

    for text in block_data(a2b_hex(texts), block_size):
        current_text = pub_key.public_decrypt(text, RSA.pkcs1_padding)
        plaintext += current_text

    return plaintext


pri_key = RSA.load_key_string(PRIVATE_KEY.strip('\n').encode('utf-8'))
pub_key = load_pub_key_string(PUBLIC_KEY.strip('\n').encode('utf-8'))

texts ="hellohellohellohellohellohellohellohellohellohellohellohellohello" \
       "hellohellohellohellohellohellohellohellohellohellohellohellohello" \
       "hellohellohellohellohellohellohellohellohellohellohellohellohello" \
       "hellohellohellohellohellohellohellohellohellohellohello"


ciphertext = encrypt(texts)
print(ciphertext)
plaintext = decrypt(ciphertext)
print(plaintext)

类:

from M2Crypto import RSA
from M2Crypto import BIO
from M2Crypto import m2
from binascii import a2b_hex, b2a_hex


class RsaCipherer(object):
    PUBLIC_KEY = '''
    -----BEGIN PUBLIC KEY-----
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA320PEM1KarSKHoXa/K9V
    ki0vBCLYkyX22yXbEabiGVFdY+H3nZsDAtmm8ydgKUM+4f9HOM6Vv060cloQDPa0
    XjI02ihbfHZ7fz5ve6BZbTZOTs5qit8UJR/pqwn1O2U0EAANYswIhb81xbBXA2bA
    IjIGQ2kD+4AjkrYtGCHtosgNrCa06wX/FDaIlcT4i347fjlgzZeoQQo1WIt9py0F
    wz8iMN5KyOxtd7pH7BmRnyC4UI85wmBe0f2k+JsN0yczuOxSV4F4Ros+n8Xld6xY
    KVXGndvQNpYzaGjQ9iMndFq4xDOozEGirJlpggJEtsCYmM94DGuX4QIpYnNTRteX
    rQIDAQAB
    -----END PUBLIC KEY-----
    '''

    PRIVATE_KEY = '''
    -----BEGIN RSA PRIVATE KEY-----
    MIIEpQIBAAKCAQEA320PEM1KarSKHoXa/K9Vki0vBCLYkyX22yXbEabiGVFdY+H3
    nZsDAtmm8ydgKUM+4f9HOM6Vv060cloQDPa0XjI02ihbfHZ7fz5ve6BZbTZOTs5q
    it8UJR/pqwn1O2U0EAANYswIhb81xbBXA2bAIjIGQ2kD+4AjkrYtGCHtosgNrCa0
    6wX/FDaIlcT4i347fjlgzZeoQQo1WIt9py0Fwz8iMN5KyOxtd7pH7BmRnyC4UI85
    wmBe0f2k+JsN0yczuOxSV4F4Ros+n8Xld6xYKVXGndvQNpYzaGjQ9iMndFq4xDOo
    zEGirJlpggJEtsCYmM94DGuX4QIpYnNTRteXrQIDAQABAoIBAAV+3TwAkLAHOM5/
    ZF+KwIQT8HAdm04jROsnBzhr7mvJAI8QY9LQmUZcrCqW8VqSeN1+NfZDvpMyEGYv
    qO1otA8NFRe4nmd1UpxSoNNdolV5XHu7wAsiaZBwNIMsf4eyeZFbLvkbI6qGhYAT
    UlCXGmq86EKINrzc7gMR0BIj44B5d3iVDN8QfAo7J0NBWenI8cOOFQvIqTds+b4Q
    AzNGbNwN3ogr+FAo8ILtL0A5PwYorRZ38/+gums7TcZjWyij12YLmnhlZuFU/3PV
    i33hsivg7MRr0frK46io+cmBuvjy31vOMjQv4x4CzrWMD1UTer+atxpKDv5AXudr
    RKcugQECgYEA7ObperdBVPAUbB0ULygxbjIMiWjkASUHX2HYIz9oh7ocFOGV3FM/
    SKtjN+NGSqQCiT62Jq7q9oJZrdYqGHtzCk7oEWVUt3Ba7VAJcOQHBwRGIfplP6lc
    nlCt0UtQyWmVtBhWp5/XBv5nRIUy8BF//aypMQ6AG8CbZHotDCjULB0CgYEA8XAI
    6D0U2Lei06wMEzZhM32/fEIgwSPryCQoq9QifF8Yej8BNUSQc5a2AJCv0tPH6VRh
    5MU1jxEdIrJ1y2rra9Bys+x6XfDjVFsDEtdtaGX/qN8U/ghSmj8DqYQmJHIFINTo
    HqavUvZOnaBCzcuOIbzo3WIaSeTKUVPrbXpBpNECgYEA3apqyQJzxRAna8oBuuY2
    6k82X9Sfk1qcfWlGHiUUn/tKj1dNLC1Qx6RmYELu4KR6IwVk1ulQvXvWgcwk82d/
    iyOuDajtDf+5dNgxHUqgMLaVEPIEjv7fxNrk6TM50lxTUYJ8grgTMV4WLo0bznnx
    cuF+JoLU6CLew7N2Nyx06xkCgYEAuq3GpVL9OGgcxQ/lMkG8vGSBV2GGE/BjUZfr
    vphCpemdcoAevgIqssUYKq201Q2dKCNvocR+GgXAgmB8RfGA4BcHaWjyYIpuK35H
    jRz24l7jY75Ba/4haFRKz5p3J3zlzDHy3ChDraD2vlf470hxuFJptyswamw1ptZ9
    VWPPN9ECgYEAhk1wX5IRFunaHRQOVIM9qZZb4nRacqBZ2AeK1iNgND5c/Hlme+wJ
    zowLAerKS773MD2F/5VCL2NKAml41p8nHqdB0qaKGjxPD06DeoIn1KeXoj4oD1YM
    n3tS4++Tgf/0aJeS9U9ypmDl5/Fyw8lC6KxIKCjm9g0Ln30On1wt2lg=
    -----END RSA PRIVATE KEY-----
    '''

    def __init__(self):
        self.public_key = \
            RsaCipherer.PUBLIC_KEY.strip('\n').replace('    ', '')
        self.private_key = \
            RsaCipherer.PRIVATE_KEY.strip('\n').replace('    ', '')
        self.public_key_cipher = \
            self.load_pub_key_string(self.public_key.encode('utf-8'))
        self.private_key_cipher = \
            RSA.load_key_string(self.private_key.encode('utf-8'))
        self.secret_key_length = self.size_in_bytes(self.public_key_cipher)

    def encrypt(self, texts):
        ciphertext = b""
        block_size = self.secret_key_length - 11

        for text in self.block_data(texts.encode('utf-8'), block_size):
            current_text = self.private_key_cipher.private_encrypt(text, RSA.pkcs1_padding)
            ciphertext += current_text

        return b2a_hex(ciphertext)

    def decrypt(self, texts):
        plaintext = b""
        block_size = self.secret_key_length

        for text in self.block_data(a2b_hex(texts), block_size):
            current_text = \
                self.public_key_cipher.public_decrypt(text, RSA.pkcs1_padding)
            plaintext += current_text

        return plaintext

    @staticmethod
    def block_data(texts, block_size):
        for i in range(0, len(texts), block_size):
            yield texts[i:i + block_size]

    @staticmethod
    def load_pub_key_string(string):
        bio = BIO.MemoryBuffer(string)
        return RSA.load_pub_key_bio(bio)

    @staticmethod
    def size_in_bytes(cipher_obj):
        return m2.rsa_size(cipher_obj.rsa)


if  __name__ == "__main__":
    texts ="hellohellohellohellohellohellohellohellohellohellohellohellohello" \
           "hellohellohellohellohellohellohellohellohellohellohellohellohello" \
           "hellohellohellohellohellohellohellohellohellohellohellohellohello" \
           "hellohellohellohellohellohellohellohellohellohellohello"
    tests1 = "hello"

    RsaCipher = RsaCipherer()

    # Encrypted data
    cipher = RsaCipherer()
    cipher_text = cipher.encrypt(texts)
    plain_text = cipher.decrypt(cipher_text)
    print("密文:\n", cipher_text)
    print("明文:\n", plain_text)

 

显示全文