def encrypt(self, text): """ 对明文进行加密 :param text: 需要加密的明文 :return: """ from Crypto.Cipher import AES # 16位随机字符串添加到明文开头 text = get_random_string(length=16) + force_text( struct.pack("I", socket.htonl(len(text)))) + text # 使用自定义的填充方式对明文进行补位填充 text = pkcs7.encode(text) # 加密 allowed_chars = string.digits + string.ascii_letters + string.punctuation iv = get_random_string(length=16, allowed_chars=allowed_chars) cryptor = AES.new(self.key, self.mode, iv) cipher_text = cryptor.encrypt(text) # 加密后的字符串转化为16进制字符串 cipher_text = force_bytes(iv) + cipher_text return str2hex(cipher_text)
def aes(app, length=16, allowed_chars=None): """ AES key """ if length not in (16, 24, 32): raise CommandError("The key length can only be 16, 24 or 32") if allowed_chars is None: allowed_chars = string.digits + string.ascii_letters + string.punctuation key = get_random_string(length=length, allowed_chars=allowed_chars) key_bytes = force_bytes(key) aes_key = base64.urlsafe_b64encode(key_bytes).rstrip(b"=") print("AES KEY:", aes_key)
def make_password(password, salt=None, hasher='default'): """ 密码加密 :param password: :param salt: :param hasher: :return: """ if password is None: return UNUSABLE_PASSWORD_PREFIX + get_random_string( UNUSABLE_PASSWORD_SUFFIX_LENGTH) hasher = get_hasher(hasher) if not salt: salt = hasher.salt() return hasher.encode(password, salt)
def salt(self): return get_random_string(2)
def salt(self): """ 随机盐 """ return get_random_string()