将字节转换为字符串或存储为字节 python

Convert bytes to string or store as bytes python

我正在尝试通过 RSA 使用 python 加密字符串,但加密的字符串 returns 为字节 我正在尝试找到一种方法,要么将字节转换为字符串并将其存储在数据库中,要么将其按原样存储为字节,但我找不到其中任何一个 我在 django 和 mysql 中使用这个项目 我需要一些帮助,这是完整的源代码

import secrets
import string

import rsa


def create_token():
    alphabet = string.ascii_letters + string.digits
    token = ''.join(secrets.choice(alphabet) for i in range(64))
    return token


def generate_keys():
    (pubKey, privKey) = rsa.newkeys(2048)
    with open('keys/pubkey.pem', 'wb') as f:
        f.write(pubKey.save_pkcs1('PEM'))

    with open('keys/privkey.pem', 'wb') as f:
        f.write(privKey.save_pkcs1('PEM'))


def load_keys():
    with open('E:/workstation/projects/amon/cryptoPATH/keys/pubkey.pem', 'rb') as f:
        pubKey = rsa.PublicKey.load_pkcs1(f.read())

    with open('E:/workstation/projects/amon/cryptoPATH/keys/privkey.pem', 'rb') as f:
        privKey = rsa.PrivateKey.load_pkcs1(f.read())

    return pubKey, privKey


def encrypt_rsa(msg, key):
    return rsa.encrypt(msg.encode('utf-16'), key)


def decrypt_rsa(ciphertext, key):
    try:
        return rsa.decrypt(ciphertext, key).decode('utf-16')
    except:
        return False


def sign_sha1(msg, key):
    return rsa.sign(msg.encode('utf-16'), key, 'SHA-1')


def verify_sha1(msg, signature, key):
    try:
        return rsa.verify(msg.encode('utf-16'), signature, key) == 'SHA-1'
    except:
        return False


# generate_keys()
pubKey, privKey = load_keys()


def encrypt(msg):
    ciphertext = encrypt_rsa(msg, pubKey)
    return ciphertext


def decrypt(message):
    plaintext = decrypt_rsa(message, privKey)
    if plaintext:
        return plaintext
    else:
        return 'Could not decrypt the message.'


message = 'encrypted'
ciphertext = encrypt(message)
plaintext = decrypt(ciphertext)
print(str(ciphertext)[2:-1])

print(f'msg= {message}\n cipher= {ciphertext}\n plain= {plaintext}\n')

输出

在数据库中存储密文 (bytes) 的一种方法是将其编码为 string。然而,挑战在于这些 encodings 在不同的 codecs 中可能完全有效,但在显示为字符串时可能会非常不同:

import codecs
data = b'\xf0\xf1\xf2'  # three hex bytes [F0, F1, F2]
data.decode('latin1')  # Result: 'ðñò'
data.decode('cp1254')  # Result: 'ğñò'

您可以将它们维护为 hexbase64 编码字符串,并对它们进行解码并在必要时使用它们。

import binascii
stored_data = binascii.hexlify(data)  # b'f0f1f2'
read_stored_data = binascii.unhexlify(stored_data)  # b'\xf0\xf1\xf2'

import base64
stored_data = base64.b64encode(data)  # b'8PHy'
read_stored_data = base64.b64decode(stored_data)  # b'\xf0\xf1\xf2'

通过使用 base64 解决了我的问题

import base64
import secrets
import string

import rsa


def create_token():
    alphabet = string.ascii_letters + string.digits
    token = ''.join(secrets.choice(alphabet) for i in range(32))
    return token


def generate_keys():
    (pubKey, privKey) = rsa.newkeys(2048)
    with open('keys/pubkey.pem', 'wb') as f:
        f.write(pubKey.save_pkcs1('PEM'))

    with open('keys/privkey.pem', 'wb') as f:
        f.write(privKey.save_pkcs1('PEM'))


def load_keys():
    with open('keys/pubkey.pem', 'rb') as f:
        pubKey = rsa.PublicKey.load_pkcs1(f.read())

    with open('keys/privkey.pem', 'rb') as f:
        privKey = rsa.PrivateKey.load_pkcs1(f.read())

    return pubKey, privKey


def encrypt_rsa(msg, key):
    return rsa.encrypt(msg.encode('utf-8'), key)


def decrypt_rsa(ciphertext, key):
    try:
        return rsa.decrypt(ciphertext, key).decode('utf-8')
    except:
        return False


def sign_sha1(msg, key):
    return rsa.sign(msg.encode('utf-8'), key, 'SHA-1')


def verify_sha1(msg, signature, key):
    try:
        return rsa.verify(msg.encode('utf-8'), signature, key) == 'SHA-1'
    except:
        return False


generate_keys()
pubKey, privKey = load_keys()


def encrypt(msg):
    ciphertext = encrypt_rsa(msg, pubKey)
    encoded = base64.b64encode(ciphertext)
    return encoded.decode()


def decrypt(message):
    message = base64.b64decode(message)
    plaintext = decrypt_rsa(message, privKey)
    if plaintext:
        return plaintext
    else:
        return 'Could not decrypt the message.'