示例#1
0
文件: helpers.py 项目: ibrewster/api
def decrypt_token(action: str, token: str):
    """
    Decrypts a token and returns the data in a list of strings
    Throws exception when the action does not fit or the token expired

    :param action: a unique identifier for the action associated with this token
    :param token: the crypted token
    :return: list of strings which contains the data given on creating the token
    """

    # F**k you urlsafe_b64encode & padding and f**k you overzealous http implementations
    token = token.replace('%3d', '=')
    token = token.replace('%3D', '=')

    ciphertext = base64.urlsafe_b64decode(token.encode())
    plaintext = Fernet(CRYPTO_KEY).decrypt(ciphertext).decode("utf-8")

    token_action, expiry, *result = plaintext.split(',')

    if token_action != action:
        raise ApiException([Error(ErrorCode.TOKEN_INVALID)])

    if (float(expiry) < time.time()):
        raise ApiException([Error(ErrorCode.TOKEN_EXPIRED)])

    return result
示例#2
0
def decryptSingleImage(encryptedimagePath: str, password: str, single=True):
    encryptedimage = None
    with open(encryptedimagePath, 'r') as file:
        encryptedimage = file.read()

    passKey = keys.getPasswordGeneratedKey(password)
    try:
        image = Fernet(passKey).decrypt(encryptedimage.encode())
        image = image.decode()
        # print(image[:20])
    except InvalidToken:
        print("\tWrong Password! Try Again")
        sys.exit(0)

    shape, image = image.split(',')
    shape = list(map(int, shape.strip().split()))
    image = list(map(int, image.strip().split()))
    image = np.resize(np.array(image), shape)

    __writeDecryptedImage(encryptedimagePath, image, single)
示例#3
0
    def extractCredentials(self, request):  # noqa camelCase
        """IExtractionPlugin implementation. Extracts login name from the
        request's "X-Queue-Auth-Token" header. This header contains an
        encrypted token with it's expiration date, together with the user name.

        Returns a dict with {'login': <username>} if:
        - current layer is ISenaiteQueueLayer,
        - the token can be decrypted,
        - the decrypted token contains both expiration and username and
        - the the token has not expired (expiration date)

        Returns an empty dict otherwise
        :param request: the HTTPRequest object to extract credentials from
        :return: a dict {"login": <username>} or empty dict
        """
        # Check if request provides ISenaiteQueueLayer
        if not ISenaiteQueueLayer.providedBy(request):
            return {}

        # Read the magical header that contains the encrypted info
        auth_token = request.getHeader("X-Queue-Auth-Token")
        if not auth_token:
            return {}

        # Decrypt the auth_token
        key = api.get_registry_record("senaite.queue.auth_key")
        token = Fernet(str(key)).decrypt(auth_token)

        # Check if token is valid
        tokens = token.split(":")
        if len(tokens) < 2 or not api.is_floatable(tokens[0]):
            return {}

        # Check if token has expired
        expiration = api.to_float(tokens[0])
        if expiration < time.time():
            return {}

        user_id = "".join(tokens[1:])
        return {"login": user_id}
示例#4
0
coins = 7
user_credits_message = jsonpickle.encode({
	'Coins' : coins
	}).encode('utf-8')

user_encrypted_message = Fernet(user.session_key).encrypt(user_credits_message)
response = user.send_message_to(bank, user_encrypted_message)

print('[MAIN] Response:', response)

response = Fernet(user.session_key).decrypt(response)
response = response.decode('utf-8')

if 'success' in response:
	user.finalize_coins(coins, float(response.split(': ')[1]))
elif 'failure' in response:
	print('[MAIN] Failure response from bank')

# ===

if not user.has_first_payment_with(vendor):

	# Create new session key for new connection (this time with Vendor) and send it to him
	symmetric_key = Fernet.generate_key()
	user.set_vendor_session_key(symmetric_key)
	user.send_session_key_to(vendor, RSA.encrypt(vendor.public_key, symmetric_key))

	# Also create new session key Bank - Vendor
	vendor.send_session_key_to(bank)	
	# ack = vendor.send_message_to(bank, user_encrypted_payment_message)