python加密解密

发布时间 2023-07-12 16:36:36作者: 宏图英雄

#!/usr/bin/env python 
# -*- coding:utf-8 -*-

# 调用方式: EnDecrypt(user,psw,b=0)
# user 为编号 ;当b=1 加密 psw 为输入的未加密的密码; 当b=0 解密 psw 为系统的已加密的密码
# EnDecrypt('0016', '7E43D384AE8E', b=0)   为解密(b=0)后密码的明码为 123456
# EnDecrypt('0016', '123456', b=1)         加密得到密码:7E43D384AE8E
#
import re, math
import numpy as np

def TransChar(achar):   # 16进制字符串 转化 对应ASCII 的10进制数
    pattern = re.compile(r"[0-9]")
    res = pattern.match(achar)
    if res:
        result = ord(achar) - ord('0')
    else:
        result = 10 + ord(achar) - ord('A')
    return result

def HexToStr(D):
    Result =''
    for I in range(0,math.floor(len(D) / 2)):
        CharValue =np.array(TransChar(D[2 * I ]) * 16 + TransChar(D[2 * I+1]), dtype="uint16")
        Result =Result + chr(CharValue)
    return Result

def str_to_hex(s):     #将字符串转为16进制编码
    return ''.join([hex(ord(c)).replace('0x', '').upper() for c in s])

def Encrypt(S,Key):
    result = ''
    for I in range(0, len(S)):
        temp = ord(S[I]) ^ (Key >> 8)
        Key = np.array((temp + Key) * 11 + 12, dtype="uint16")
        # print(I, chr(temp),Key)
        if chr(temp) == chr(0):
            result += S[I]
        else:
            result += chr(temp)
    Z=[hex(ord(c)).replace('0x', '').upper() for c in result]    #将每个字符串转为16进制编码
    Result=[ '0'+a if len(a)==1 else a for a in Z ]              #遍历列表,如果长度只有一位,前面补‘0’,使得每个字符都以两位码形式存在
    return ''.join(Result)

def Decrypt(S,Key):
    S=HexToStr(S)
    Result = ''
    for I in range(0, len(S)):
        if chr(ord(S[I]) ^ (Key >> 8)) == chr(0):
            Result += S[I]
            Key = np.array((ord(str(0)) + Key) * 11 + 12, dtype="uint16")
        else:
            Result += chr(ord(S[I]) ^ (Key >> 8))
            Key = np.array((ord(S[I]) + Key) * 11 + 12, dtype="uint16")
        #print('I ord(S[I]) ^ (Key >> 8)',I,S[I],ord(S[I]), (Key >> 8),ord(S[I]) ^ (Key >> 8), Result, Key)
    return Result

def EnDecrypt(user,psw,b=0):
    # user 为编号 ;当b=1 加密 psw 为输入的未加密的密码; 当b=0 解密 psw 为系统的已加密的密码
    power = 20328+ord(user[-1]) #取最末尾一个ASCII字符
    if b == 1:
        password = Encrypt(psw,power)
    else:
        password = Decrypt(psw, power)
    return password


s='22~& /2'
psw = '********'
psw2 = '*****************'
# print(EnDecrypt(s,psw,0))
print(EnDecrypt(s, psw2, 0))