How do I url encode a byte string and then decode the encoded byte string from AES?
This is my code:
from Cryptodome.Cipher import AES
from Cryptodome.Util.Padding import pad, unpad
key = "00112233445566778899aabbccddeeff".encode("utf8")
iv = b'\x0cK\x1c\x82\xf1\xa9w\xfe\xa9\x9a\xd0\xb3\x8c\xec1\x1c' # os.urandom(16)
aes = AES.new(key, AES.MODE_CBC, iv)
data = pad(b'HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH', 16) # <- 16 bytes
encd = aes.encrypt(data) # this works, but it's a byte string, not a string
aes = AES.new(key, AES.MODE_CBC, iv)
decd = unpad(aes.decrypt(encd), 16) # this works, it's a string
a = urllib.parse.quote(encd) # this works
b = urllib.parse.unquote(a) # this works
can_not_decrypt = unpad(aes.decrypt( b, 16)) # But this one does not work???
This is what i tried to solve my question, it doesn't work:
a = urllib.parse.quote(encd) # this works
b = urllib.parse.unquote(a) # this works
can_not_decrypt = unpad(aes.decrypt( b, 16)) # But this one does not work???
You are passing 16 as second argument to decrypt, as opposed to unpad.
can_not_decrypt = unpad(aes.decrypt( b, 16))
should be
can_not_decrypt = unpad(aes.decrypt(b), 16)
Working example with urllib.parse:
import urllib.parse
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
key = "00112233445566778899aabbccddeeff".encode("utf8")
iv = b'\x0cK\x1c\x82\xf1\xa9w\xfe\xa9\x9a\xd0\xb3\x8c\xec1\x1c' # os.urandom(16)
aesenc = AES.new(key, AES.MODE_CBC, iv)
data = pad(b'AllworkandnoplaymakesJackadullboyAllworkandnoplaymakesJackadullboyAllworkandnoplay...', 16)
encd = aesenc.encrypt(data) # this works, but it's a byte string, not a string
aesdec = AES.new(key, AES.MODE_CBC, iv)
a = urllib.parse.quote(encd)
print("Urlencoded: {}".format(a))
b = urllib.parse.unquote_to_bytes(a)
decd = unpad(aesdec.decrypt(b), 16)
print("Decoded: {}".format(decd))
Working example with base64 instead of urllib:
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
key = "00112233445566778899aabbccddeeff".encode("utf8")
iv = b'\x0cK\x1c\x82\xf1\xa9w\xfe\xa9\x9a\xd0\xb3\x8c\xec1\x1c' # os.urandom(16)
aesenc = AES.new(key, AES.MODE_CBC, iv)
data = pad(b'AllworkandnoplaymakesJackadullboyAllworkandnoplaymakesJackadullboyAllworkandnoplay...', 16)
encd = aesenc.encrypt(data) # this works, but it's a byte string, not a string
aesdec = AES.new(key, AES.MODE_CBC, iv)
a = base64.b64encode(encd, b"-_")
print("Base64: {}".format(a.decode('ascii')))
b = base64.b64decode(a, b"-_")
decd = unpad(aesdec.decrypt(b), 16)
print("Decoded: {}".format(decd))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.