简体   繁体   English

在Python中从stdin进行编码/加密

[英]Encoding/Encrypting from stdin in Python

I'm trying to encrypt data from stdin to send across a socket, so for testing I'm trying to decrypt what I just encrypted and it's not producing the original message as is. 我正在尝试从stdin加密数据以通过套接字发送,因此为了进行测试,我试图解密我刚刚加密的内容,并且它不会按原样生成原始消息。

BS = 16
client_cipher = AES.new(client_conf_key, AES.MODE_CBC, randIV)
message = sys.stdin.readline()

padded_message = message + '$' + (BS - ((len(message)+1)%16))*'#'
client_message = base64.b64encode(client_cipher.encrypt(padded_message))

print "Encrypted: " + client_message

enc_str = base64.b64decode(client_message)
dec_str = client_cipher.decrypt(enc_str)

print "Decrypted: " + dec_str

Here's what my output looks like now 这是我现在的输出 在此处输入图片说明

I feel like I'm messing up the encoding somehow, any help would be appreciated 我觉得我以某种方式弄乱了编码,任何帮助将不胜感激

Edit: client_cipher is an AES cipher, client_cipher = AES.new(client_conf_key, AES.MODE_CBC, randIV) 编辑:client_cipher是一个AES密码,client_cipher = AES.new(client_conf_key,AES.MODE_CBC,randIV)

Here is some code I once wrote to a similar effect; 这是我曾经写过的类似效果的一些代码。

BS = 16

pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-ord(s[-1])]


def encrypt(plaintext, key, iv):
    cipher = AES.new(key, AES.MODE_CBC,iv)
    plaintext = pad(plaintext)
    return cipher.encrypt(plaintext)

def decrypt(ciphertext, key, iv):
    cipher = AES.new(key, AES.MODE_CBC, iv)
    decrypted = cipher.decrypt(ciphertext)
    return unpad(decrypted)

This got the job done for me, make sure you pass in appropriate params! 这为我完成了工作,请确保您传递适当的参数!

HTH 高温超导

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM