python实现密码算法

python通过Cryptodome使用AES加密数据

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

data = b'secret data'

key = get_random_bytes(16)
cipher = AES.new(key, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(data)

file_out = open("encrypted.bin", "wb")
[ file_out.write(x) for x in (cipher.nonce, tag, ciphertext) ]
file_out.close()

file_in = open("encrypted.bin", "rb")
nonce, tag, ciphertext = [ file_in.read(x) for x in (16, 16, -1) ]

# let's assume that the key is somehow available again
cipher = AES.new(key, AES.MODE_EAX, nonce)
data = cipher.decrypt_and_verify(ciphertext, tag)
print(data)

生成RSA密钥

from Crypto.PublicKey import RSA
#对密钥加密的密码
secret_code = "Unguessable"
#生成一个 2048 位的密钥
key = RSA.generate(2048)

#导出私钥,passphrase 指定了对私钥加密的密码
encrypted_key = key.export_key(passphrase=secret_code, pkcs=8,
                              protection="scryptAndAES128-CBC")

#将私钥保存到文件
file_out = open("rsa_key.bin","wb")
file_out.write(encrypted_key)
file_out.close()

#输出公钥
print(key.publickey().export_key())

生成公钥和私钥

生成了私钥并保存到private.pem,之后生成了公钥,保存为receiver.pem

from Crypto.PublicKey import RSA
#生成密钥
key = RSA.generate(2048)

#保存私钥
private_key = key.export_key()
file_out = open("private.pem", "wb")
file_out.write(private_key)
file_out.close()

#保存公钥
public_key = key.publickey().export_key()
file_out = open("receiver.pem", "wb")
file_out.write(public_key)
file_out.close()

RSA + AES混合加密

为了加密任意数量的数据,这里使用混合加密方式(RSA+AES)。这里使用 RSA 和 PKCS#1oaep 对 AES 会话密钥进行非对称加密

from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP

#要加密的数据
data = "I met aliens in UFO. Here is the map.".encode("utf-8")
#加密数据的输出
file_out = open("encrypted_data.bin", "wb")

#读取公钥
recipient_key = RSA.import_key(open("receiver.pem").read())


session_key = get_random_bytes(16)

# Encrypt the session key with the public RSA key
#加密会话密钥
cipher_rsa = PKCS1_OAEP.new(recipient_key)
enc_session_key = cipher_rsa.encrypt(session_key)

# Encrypt the data with the AES session key
#利用 AES 会话密钥加密数据
cipher_aes = AES.new(session_key, AES.MODE_EAX)
ciphertext, tag = cipher_aes.encrypt_and_digest(data)
[ file_out.write(x) for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext) ]
file_out.close()


对于拥有私钥的解密者,首先使用私钥对会话密钥进行解密,再用会话密钥解密文件:

from Crypto.PublicKey import RSA
from Crypto.Cipher import AES, PKCS1_OAEP

file_in = open("encrypted_data.bin", "rb")

#导入私钥
private_key = RSA.import_key(open("private.pem").read())

#读取 AES 的相关参数
enc_session_key, nonce, tag, ciphertext = \
   [ file_in.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1) ]

# Decrypt the session key with the private RSA key
# 对会话密钥解密
cipher_rsa = PKCS1_OAEP.new(private_key)
session_key = cipher_rsa.decrypt(enc_session_key)

# Decrypt the data with the AES session key
#使用会话密钥解密数据
cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
data = cipher_aes.decrypt_and_verify(ciphertext, tag)
print(data.decode("utf-8"))


安装gmssl(pip install gmssl)和pysmx(pip install snowland-smx)

https://gitee.com/basddsa/hggm#https://gitee.com/link?target=https%3A%2F%2Fblog.csdn.net%2Fqq_43339242%2Farticle%2Fdetails%2F123709822

python实现sm4

通过gmssl

##############################################################################
#                                                                            #
#                            国产SM4加密算法                                  #
#                                                                            #
##############################################################################

import binascii

from gmssl import sm4


class SM4:
    """
    国产加密 sm4加解密
    """

    def __init__(self):
        self.crypt_sm4 = sm4.CryptSM4()  # 实例化

    def str_to_hexStr(self, hex_str):
        """
        字符串转hex
        :param hex_str: 字符串
        :return: hex
        """
        hex_data = hex_str.encode('utf-8')
        str_bin = binascii.unhexlify(hex_data)
        return str_bin.decode('utf-8')

    def encryptSM4(self, encrypt_key, value):
        """
        国密sm4加密
        :param encrypt_key: sm4加密key
        :param value: 待加密的字符串
        :return: sm4加密后的十六进制值
        """
        crypt_sm4 = self.crypt_sm4
        crypt_sm4.set_key(encrypt_key.encode(), sm4.SM4_ENCRYPT)  # 设置密钥
        date_str = str(value)
        encrypt_value = crypt_sm4.crypt_ecb(date_str.encode())  # 开始加密。bytes类型
        return encrypt_value.hex()  # 返回十六进制值

    def decryptSM4(self, decrypt_key, encrypt_value):
        """
        国密sm4解密
        :param decrypt_key:sm4加密key
        :param encrypt_value: 待解密的十六进制值
        :return: 原字符串
        """
        crypt_sm4 = self.crypt_sm4
        crypt_sm4.set_key(decrypt_key.encode(), sm4.SM4_DECRYPT)  # 设置密钥
        decrypt_value = crypt_sm4.crypt_ecb(bytes.fromhex(encrypt_value))  # 开始解密。十六进制类型
        return decrypt_value.decode()
        # return self.str_to_hexStr(decrypt_value.hex())


if __name__ == '__main__':
    key = "f38fc9b32af486e65d6f93dbc41b9123"
    strData = "90897h8789thvht"
    SM4 = SM4()
    print("原字符:", strData)
    encData = SM4.encryptSM4(key, strData)  # 加密后的数据,返回bytes类型
    print("sm4加密结果:", encData)
    
    decData = SM4.decryptSM4(key, encData)
    print("sm4解密结果:", decData)  # 解密后的数据

python通过gmssl实现sm2

import sys
from gmssl import sm2
from base64 import b64encode, b64decode
# sm2的公私钥
SM2_PRIVATE_KEY = '00B9AB0B828FF68872F21A837FC303668428DEA11DCD1B24429D0C99E24EED83D5'
SM2_PUBLIC_KEY = 'B9C9A6E04E9C91F7BA880429273747D7EF5DDEB0BB2FF6317EB00BEF331A83081A6994B8993F3F5D6EADDDB81872266C87C018FB4162F5AF347B483E24620207'

sm2_crypt = sm2.CryptSM2(public_key=SM2_PUBLIC_KEY, private_key=SM2_PRIVATE_KEY)

# 加密
def encrypt(info):
    encode_info = sm2_crypt.encrypt(info.encode(encoding="utf-8"))
    encode_info = b64encode(encode_info).decode()  # 将二进制bytes通过base64编码
    return encode_info


# 解密
def decrypt(info):
    decode_info = b64decode(info.encode())  # 通过base64解码成二进制bytes
    decode_info = sm2_crypt.decrypt(info).decode(encoding="utf-8")
    return decode_info


if __name__ == "__main__":
    action = sys.argv[1]  # 取命令中的加解密动作
    contact_info = sys.argv[2]  # 取命令中需要加解密的内容
    if action == "encrypt":
        encrypted_contact_info = encrypt(contact_info)
        print(encrypted_contact_info)
    if action == "decrypt":
        decrypted_contact_info = decrypt(contact_info)
        print(decrypted_contact_info)
from gmssl import sm2
# sm2的公私钥
SM2_PRIVATE_KEY = '00B9AB0B828FF68872F21A837FC303668428DEA11DCD1B24429D0C99E24EED83D5'
SM2_PUBLIC_KEY = 'B9C9A6E04E9C91F7BA880429273747D7EF5DDEB0BB2FF6317EB00BEF331A83081A6994B8993F3F5D6EADDDB81872266C87C018FB4162F5AF347B483E24620207'

sm2_crypt = sm2.CryptSM2(public_key=SM2_PUBLIC_KEY, private_key=SM2_PRIVATE_KEY)

# 加密
def encrypt(info):
    encode_info = sm2_crypt.encrypt(info.encode(encoding="utf-8"))
    return encode_info


# 解密
def decrypt(info):
    decode_info = sm2_crypt.decrypt(info).decode(encoding="utf-8")
    return decode_info


if __name__ == "__main__":
    info = "123456"
    encode_info = encrypt(info)
    print(encode_info)
    decode_info = decrypt(encode_info)
    print(decode_info)
from gmssl import sm2
# sm2的公私钥
SM2_PRIVATE_KEY = '00B9AB0B828FF68872F21A837FC303668428DEA11DCD1B24429D0C99E24EED83D5'
SM2_PUBLIC_KEY = 'B9C9A6E04E9C91F7BA880429273747D7EF5DDEB0BB2FF6317EB00BEF331A83081A6994B8993F3F5D6EADDDB81872266C87C018FB4162F5AF347B483E24620207'

sm2_crypt = sm2.CryptSM2(public_key=SM2_PUBLIC_KEY, private_key=SM2_PRIVATE_KEY)

# 加密
def encrypt(info):
    encode_info = sm2_crypt.encrypt(info.encode(encoding="utf-8"))
    return encode_info


# 解密
def decrypt(info):
    decode_info = sm2_crypt.decrypt(info).decode(encoding="utf-8")
    return decode_info


if __name__ == "__main__":
    info = "123456"
    encode_info = encrypt(info)
    print(encode_info)
    decode_info = decrypt(encode_info)
    print(decode_info)

posted @ 2022-11-17 08:16  20201327刘谨铭  阅读(422)  评论(1编辑  收藏  举报