I wrote a custom encoding code snippet. When i run it on pyton 3.6 i got type error. I couldn't figure it out exactly. The code snippet is working fine with python 2.7.
import os
import sys
import base64
def encode(key, clear):
"""encode custom """
enc = []
for i in range(len(clear)):
key_c = key[i % len(key)]
enc_c = chr((ord(clear[i]) + ord(key_c)) % 256)
#change the int or str
enc.append(enc_c)
return base64.urlsafe_b64encode("".join(enc))
clear = "ABCDEFGH"
encode_var = encode("crumbs", clear)
Error Log :
(py3) C:\Dev\crumbles>python s1.py
Traceback (most recent call last):
File "s1.py", line 45, in <module>
encode_var = encode("crumbs", clear)
File "s1.py", line 42, in encode
return base64.urlsafe_b64encode("".join(enc))
File "C:\Users\Cookie1\Anaconda3\envs\py3\lib\base64.py", line 118, in urlsafe
_b64encode
return b64encode(s).translate(_urlsafe_encode_translation)
File "C:\Users\Cookie1\Anaconda3\envs\py3\lib\base64.py", line 58, in b64encod
e
encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'
答案 0 :(得分:1)
You are passing in text, not a binary function get_userid_get()
{
$username = $this->get('username');
if (!$username) {
$this->response("No username specified", 400);
exit;
}
$result = $this->user_model->get_userid($username);
if ($result) {
$this->response($result, 200);
exit;
} else {
$this->response("Invalid username", 404);
exit;
}}
object. The bytes
function expects bytes, not text.
Generate bytes instead:
base64.urlsafe_b64encode()
I used a few iterator tricks to produce the integers that from itertools import cycle
def encode(key, clear):
"""encode custom """
key, clear = cycle(key.encode()), clear.encode()
enc = bytes((c + k) % 256 for c, k in zip(clear, key))
return base64.urlsafe_b64encode(enc)
accepts.
Note that it is more common to use XOR to produce encrypted bytes when creating a single-key encryption:
bytes()
That's because XOR is trivially reversed by using the same key; clear XOR key produces the encrypted text, and encrypted XOR key produces the cleartext again.