问题
我希望能够在 Go 中解密在 Python 中加密的内容。加密/解密函数分别在每种语言中工作,但当我在 Python 中加密和在 Go 中解密时,我猜测编码有问题,因为我得到了乱码输出:
Rx����d��I�K|�ap���k��B%F���UV�~d3h�����|�����>�B��B�
Python中的加密/解密
def encrypt(plaintext, key=config.SECRET, key_salt='', no_iv=False):
"""Encrypt shit the right way"""
# sanitize inputs
key = SHA256.new((key + key_salt).encode()).digest()
if len(key) not in AES.key_size:
raise Exception()
if isinstance(plaintext, string_types):
plaintext = plaintext.encode('utf-8')
# pad plaintext using PKCS7 padding scheme
padlen = AES.block_size - len(plaintext) % AES.block_size
plaintext += (chr(padlen) * padlen).encode('utf-8')
# generate random initialization vector using CSPRNG
if no_iv:
iv = ('\0' * AES.block_size).encode()
else:
iv = get_random_bytes(AES.block_size)
log.info(AES.block_size)
# encrypt using AES in CFB mode
ciphertext = AES.new(key, AES.MODE_CFB, iv).encrypt(plaintext)
# prepend iv to ciphertext
if not no_iv:
ciphertext = iv + ciphertext
# return ciphertext in hex encoding
log.info(ciphertext)
return ciphertext.hex()
def decrypt(ciphertext, key=config.SECRET, key_salt='', no_iv=False):
"""Decrypt shit the right way"""
# sanitize inputs
key = SHA256.new((key + key_salt).encode()).digest()
if len(key) not in AES.key_size:
raise Exception()
if len(ciphertext) % AES.block_size:
raise Exception()
try:
ciphertext = codecs.decode(ciphertext, 'hex')
except TypeError:
log.warning("Ciphertext wasn't given as a hexadecimal string.")
# split initialization vector and ciphertext
if no_iv:
iv = '\0' * AES.block_size
else:
iv = ciphertext[:AES.block_size]
ciphertext = ciphertext[AES.block_size:]
# decrypt ciphertext using AES in CFB mode
plaintext = AES.new(key, AES.MODE_CFB, iv).decrypt(ciphertext).decode()
繁花如伊
相关分类