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

发布于 2025-01-12 19:07:45 字数 2048 浏览 1 评论 0原文

我正在尝试通过 RSA 使用 python 加密字符串,但加密的字符串以字节形式返回 我正在尝试找到一种方法,将字节转换为字符串并将其存储在数据库中或按原样将其存储为字节,但我找不到其中任何一个 我在 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')

输出

代码输出

I'm trying to encrypt string with python by RSA but the encrypted string returns as bytes
I'm trying to find a way either to convert bytes to string and store it in db or store it as bytes as it is but I couldn't find either of them
i use this project in django and mysql
i need some help on it and this is the full source code

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')

OUTPUT

outputof code

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦毁影碎の 2025-01-19 19:07:45

通过使用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.'

by using base64 solved my problem

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.'

最美的太阳 2025-01-19 19:07:45

在数据库中存储密文(字节)的一种方法是将其编码为字符串。然而,挑战在于这些编码可能是完全有效的在不同的编解码器中,但以字符串形式呈现时可能会非常不同:

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'

One way to store the cipher text (bytes) in a database is encoding it into a string. However, the challenge is that these encodings could be perfectly valid in different codecs but could be very different when presented as strings:

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

You could maintain these as hex or base64 encoded strings and decode them and use them as necessary.

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'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文