import base64
import random
# 提供一个编码方式,每次执行得到不同的结果
def s_encode(key,source):
temp_array = source.encode('utf-8')
source = base64.b64encode(temp_array).decode('utf-8')
ch_array = list(source)
key_chars = list(key)
num = random.randint(0, 0xff)
builder = []
if num > 15:
builder.append(format(num, 'x'))
else:
builder.append('0' + format(num, 'x'))
num2 = int(''.join(builder), 16)
for i in range(len(ch_array)):
if (ord(ch_array[i]) + num2) > 0xff:
num2 = ((ord(ch_array[i]) + num2) - 0xff) ^ ord(key_chars[i % 13])
else:
num2 = (ord(ch_array[i]) + num2) ^ ord(key_chars[i % 13])
if num2 > 15:
builder.append(format(num2, 'x'))
else:
builder.append('0' + format(num2, 'x'))
return ''.join(builder).upper()
def s_decode(key,source):
key_chars = list(key)
builder = []
ch_array = list(source)
for i in range(0, len(ch_array) - 2, 2):
str1 = ch_array[i + 2] + ch_array[i + 3]
str2 = format(ord(key_chars[(i // 2) % 13]), 'x')
str3 = ch_array[i] + ch_array[i + 1]
num2 = (int(str1, 16) ^ int(str2, 16)) - int(str3, 16)
if num2 < 0:
num2 += 0xff
builder.append(chr(num2))
decode_str = base64.b64decode(''.join(builder)).decode('utf-8')
return decode_str
def main():
#key = 'yA36zA48dEhfrvghGRg57h5UlDv3'
#key = '0102030405060708091011121314'
key = 'DE13B1B580436E63DE13B1B58043'
#source='this is a python sample!'
source='This is a python coding sample'
en_source=s_encode(key,source)
print(f'key[{len(key)}]={key}')
print(f'source={source}')
print(f'en_source[{len(en_source)}]={en_source}')
dec_source=s_decode(key,en_source)
print(f'dec_source={dec_source}')
print(f'source==dec_source={source==dec_source}')
if __name__ == '__main__':
main()