过期令牌生成器返回InvalidToken

时间:2017-11-30 18:47:02

标签: python django python-cryptography

我正在尝试创建一个到期令牌生成器。但是,当我使用generate_token然后在get_token_value中使用令牌时,我会继续cryptography.fernet.InvalidToken我猜这是两个函数中编码的问题,但是我是不太确定我错过了什么?

发生器

from datetime import datetime, timedelta

import cryptography
from cryptography.fernet import Fernet
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.utils.encoding import force_bytes, force_text
class ExpiringTokenGenerator(object):
    FERNET_KEY = Fernet.generate_key()
    fernet = Fernet(FERNET_KEY)

    DATE_FORMAT = '%Y-%m-%d %H-%M-%S'
    EXPIRATION_DAYS = 1

    def _get_time(self):
        """Returns a string with the current UTC time"""
        return datetime.utcnow().strftime(self.DATE_FORMAT)

    def _parse_time(self, d):
        """Parses a string produced by _get_time and returns a datetime object"""
        return datetime.strptime(d, self.DATE_FORMAT)

    def generate_token(self, text):
        """Generates an encrypted token"""
        full_text = str(text) + '|' + self._get_time()
        token = self.fernet.encrypt(bytes(full_text, 'utf-8'))

        return token

    def get_token_value(self, token):
        """Gets a value from an encrypted token.
        Returns None if the token is invalid or has expired.
        """
        try:
            value = self.fernet.decrypt(bytes(token, 'utf-8'))
            separator_pos = value.rfind('|')

            text = value[: separator_pos]
            token_time = self._parse_time(value[separator_pos + 1: ])
            print(token_time)
            if token_time + timedelta(self.EXPIRATION_DAYS) < datetime.utcnow():
                return None

        except cryptography.fernet.InvalidToken:
            return None

        return text

    def is_valid_token(self, token):
        return self.get_token_value(token) != None


invoice_activation_token = ExpiringTokenGenerator()

1 个答案:

答案 0 :(得分:0)

如果先将full_text作为字节输入,该怎么办?那会有用吗?

from datetime import datetime
from cryptography.fernet import Fernet

FERNET_KEY = Fernet.generate_key()
fernet = Fernet(FERNET_KEY)
get_time = datetime.utcnow().strftime('%Y-%m-%d %H-%M-%S')
text = 'abc'
full_text = bytes(str(text) + '|' + get_time, encoding='utf-8')
token = fernet.encrypt(full_text)
value = fernet.decrypt(token)

print('Token:', token)
print('Value:', value)

返回:

Token: b'gAAAAABaIIPXtLrJ6YoJWUq9o9i5Q-1dCJ9Iae4mczFhHmW-UUQUKkgsPcm0MxzIJbBbIeziY3W-b2joT37kG-RxueEhwlx-x8n4B224thTWuebY1FfYXjI='
Value: b'abc|2017-11-30 22-19-03'