加密分为对称加密和非对称加密, 就是salt是否相同.
一般常用的就是 公钥加密, 私钥再去解密.
也有直接做hash的(无法解密).
但是本文不整那么多花里胡哨的.... 就使用异或运算来对密码加密
本文没得啥高大上的算法, 核心就是一个异或运算....
异或运算: 相同为0, 相异为1.
异或之后的值再对相同的对象异或 就能得到原来的值. 听起来有点绕口. 差不多就是下面这样的
C = A ^ B
A = C ^ B
根据这个原理, 我们就能制作一个带salt的加密工具了.
但是考虑到相同的密码和相同的salt会得到相同的结果, 所以我们的加密函数 就再加个 随机数来干扰.
为了方便验证, 我们还加入crc32来校验字符串是否完整.
所以伪代码加密逻辑就是下面这样的
password = password ^ salt
password += crc32(password)
解密就是反过来就行, 这里就不多说了, 直接看测试吧
脚本见文末.
import encrypt_ddcw
encrypt_ddcw.encrypt(b'123456')
encrypt_ddcw.encrypt(b'123456')
解密就是反向操作.
import encrypt_ddcw
aa = encrypt_ddcw.encrypt(b'aaaaa')
bb = encrypt_ddcw.encrypt(b'666666')
encrypt_ddcw.decrypt(aa)
encrypt_ddcw.decrypt(bb)
以后就能有属于自己的加解密工具了-_-
1. 加密的时候加点随机数就不容易不猜出密码.
2. 虽然没得ssl那么强, 但是足够简单, 能够自己定制.
3. 加上校验位能够辅助判断目标字符串是否完整.
ddcw_tool工具也包含了这两函数
import struct,binascii,random,hashlib
def encrypt(password,salt=b'thisissalt'):
"""
先crc32 然后异或随机数, 然后异或salt 然后返回带crc32
"""
if not isinstance(password,bytes) and not isinstance(password,bytearray):
password = password.encode()
if not isinstance(salt,bytes) and not isinstance(salt,bytearray):
salt = salt.encode()
password += struct.pack('<L',binascii.crc32(password))
rstr = hashlib.sha256(str(random.random()).encode()).digest()
rstr_size = random.randint(4,16)
rstr = bytearray(rstr[:rstr_size])
password = bytearray(password)
for x in range(len(password)):
password[x] ^= rstr[x%len(rstr)]
password = struct.pack('<B',rstr_size) + rstr + password
salt = bytearray(salt)
password = bytearray(password)
for x in range(len(password)):
password[x] ^= salt[x%len(salt)]
return password + struct.pack('<L',binascii.crc32(password))
def decrypt(password,salt=b'thisissalt'):
if len(password) <= 8:
return b''
if not isinstance(salt,bytes) and not isinstance(salt,bytearray):
salt = salt.encode()
password = bytearray(password)
salt = bytearray(salt)
crc32 = password[-4:]
password = password[:-4]
if binascii.crc32(password) != struct.unpack('<L',crc32)[0]:
return b''
salt = bytearray(salt)
password = bytearray(password)
for x in range(len(password)):
password[x] ^= salt[x%len(salt)]
rstr_size = struct.unpack('<B',password[:1])[0]
rstr = password[1:1+rstr_size]
password = password[1+rstr_size:]
rstr = bytearray(rstr)
password = bytearray(password)
for x in range(len(password)):
password[x] ^= rstr[x%len(rstr)]
crc32 = password[-4:]
password = password[:-4]
if binascii.crc32(password) == struct.unpack('<L',crc32)[0]:
return password
else:
return b''
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。