A-A+
自用 ATOM128 加密、解密算法
![Shrimp-虾米-原创文章](/wp-content/themes/Ality/img/007.gif)
【注意:此文章为博主原创文章!转载需注意,请带原文链接,至少也要是txt格式!】
自己瞎写的一款加密、解密算法,算是瞎写着玩。
class ATOM128:
encode_table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
decode_table = {v: k for k, v in enumerate(encode_table)}
@staticmethod
def atom_encode(data, shift=1, salt="1234"):
# Add salt to data
salted_data = salt + data
# Convert data to UTF-8 byte stream
binary_data = ''.join([format(byte, '08b') for byte in salted_data.encode('utf-8')])
padding_len = (6 - len(binary_data) % 6) % 6
binary_data += '0' * padding_len
encoded_data = ''
for i in range(0, len(binary_data), 6):
chunk = binary_data[i:i + 6]
index = int(chunk, 2)
index = (index + shift) % 64
encoded_data += ATOM128.encode_table[index]
padding_chars = '=' * (padding_len // 2)
return encoded_data + padding_chars
@staticmethod
def atom_decode(encoded_data, shift=1, salt_length=4):
try:
padding_count = encoded_data.count('=')
encoded_data = encoded_data.rstrip('=')
binary_data = ''
for char in encoded_data:
index = (ATOM128.decode_table[char] - shift + 64) % 64
binary_data += format(index, '06b')
binary_data = binary_data[:len(binary_data) - padding_count * 2]
# Convert binary data back to byte stream
bytes_data = []
for i in range(0, len(binary_data), 8):
byte = binary_data[i:i + 8]
bytes_data.append(int(byte, 2))
# Decode byte stream to UTF-8 string
decoded_string = bytes(bytes_data).decode('utf-8')
# Remove salt
return decoded_string[salt_length:]
except Exception as e:
return "Error: Decoding failed. The input is not valid ATOM-128 encoded data. Please try again! {}".format(e)
# Example Usage:
encoded = ATOM128.atom_encode("ABC从", shift=3, salt="ab啊cd")
decoded = ATOM128.atom_decode(encoded, shift=3, salt_length=5) # 注意salt_length表示上方加密salt值的长度
print("Encoded:", encoded)
print("Decoded:", decoded)
布施恩德可便相知重
微信扫一扫打赏
支付宝扫一扫打赏