Hi, I need some help with encoding and decoding data. It was working fine with python 2,
But I found it’s very buggy in python 3. not sure why it happens.
The decoded data is only a few characters different, but one error can stop the script from running.
Here is my current code.
import os
import random, base64
from hashlib import sha1
from base64 import encode,decode
def crypt2021(data, key):
x = 0
box = list(range(256))
for i in range(256):
x = (x + box[i] + ord(key[i % len(key)])) % 256
box[i], box = box, box[i]
x = y = 0
out =
for char in data:
x = (x + 1) % 256
y = (y + box) % 256
box, box[y] = box[y], box
out.append(chr(ord(char) ^ box[(box + box[y]) % 256]))
return ''.join(out)
def tencode2021(data, key, encode=base64.b64encode, salt_length=16):
salt = ‘’
for n in range(salt_length):
salt += chr(random.randrange(256))
data = salt + crypt2021(data, sha1((key + salt).encode(‘utf-8’)).hexdigest())
return data
def tdecode2021(data, key, decode=base64.b64decode, salt_length=16):
salt = data[:salt_length]
return crypt2021(data[salt_length:],sha1((key + salt).encode(‘utf-8’)).hexdigest())
#read file
tempEncodeMel = ‘D:/Tool2023/scripts/testData’
fdAAA = open(tempEncodeMel,encoding=“utf-8”)
readDataLines = fdAAA.read()
fdAAA.close()
password = str(‘1111’)
#encode
encoded_data = tencode2021(data=readDataLines, key=password)
#write file
tempEncodeMel = ‘D:/Tool2023/scripts/encodeMel’
fwBBB = open(tempEncodeMel,‘w’,encoding=“utf-8”)
fwBBB.write(encoded_data)
fwBBB.close()
#read encode file
decodeData = ‘D:/Tool2023/scripts/encodeMel’
fdCCC = open(decodeData,encoding=“utf-8”)
loadDataLines = fdCCC.read()
fdCCC.close()
#decode
password = str(‘1111’)
decoded_data = tdecode2021(data=loadDataLines, key=password)
#write decode data to file
writeOutData = ‘D:/Tool2023/scripts/checkDecode.mel’
fwDDD = open(writeOutData,‘w’,encoding=“utf-8”)
fwDDD.write(decoded_data)
fwDDD.close()
#compare data
if decoded_data == readDataLines:
print(‘success’)
else:
print(‘fail’)
########################################################
Compare data. This is the original data.
/==========================
=============================/
This is after the decode.
/===============:==========
=============================/
Some of line is a little different
the funny thing is if you encode and decode data without writing and reading to a file, then everything works.
Does anyone experience something similar?Processing: testData…
I can not upload files here, so I save them in my dropbox
https://www.dropbox.com/sh/jesy74zmy4fidrf/AAB6iASiGm7LR3PaC-7Os9O8a?dl=0