1
mirror of https://github.com/Yubico/python-fido2 synced 2024-11-18 10:46:07 +01:00
python-fido2/fido2/utils.py

143 lines
4.5 KiB
Python
Raw Normal View History

2018-03-02 13:15:13 +01:00
# Copyright (c) 2013 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Various utility functions.
This module contains various functions used throughout the rest of the project.
"""
2018-03-02 13:15:13 +01:00
from base64 import urlsafe_b64decode, urlsafe_b64encode
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hmac, hashes
from io import BytesIO
2021-01-31 16:29:05 +01:00
from typing import Union
import struct
2018-03-02 13:15:13 +01:00
__all__ = [
2019-10-01 09:25:29 +02:00
"websafe_encode",
"websafe_decode",
"sha256",
"hmac_sha256",
"bytes2int",
"int2bytes",
2018-03-02 13:15:13 +01:00
]
def sha256(data: bytes) -> bytes:
"""Produces a SHA256 hash of the input.
:param data: The input data to hash.
:return: The resulting hash.
"""
2018-03-02 13:15:13 +01:00
h = hashes.Hash(hashes.SHA256(), default_backend())
h.update(data)
return h.finalize()
def hmac_sha256(key, data):
"""Performs an HMAC-SHA256 operation on the given data, using the given key.
:param key: The key to use.
:param data: The input data to hash.
:return: The resulting hash.
"""
2018-03-02 13:15:13 +01:00
h = hmac.HMAC(key, hashes.SHA256(), default_backend())
h.update(data)
return h.finalize()
def bytes2int(value: bytes) -> int:
"""Parses an arbitrarily sized integer from a byte string.
:param value: A byte string encoding a big endian unsigned integer.
:return: The parsed int.
"""
return int.from_bytes(value, "big")
def int2bytes(value: int, minlen: int = -1) -> bytes:
"""Encodes an int as a byte string.
:param value: The integer value to encode.
:param minlen: An optional minimum length for the resulting byte string.
:return: The value encoded as a big endian byte string.
"""
ba = []
2019-10-01 09:25:29 +02:00
while value > 0xFF:
ba.append(0xFF & value)
value >>= 8
ba.append(value)
ba.extend([0] * (minlen - len(ba)))
return bytes(reversed(ba))
2021-01-31 16:29:05 +01:00
def websafe_decode(data: Union[str, bytes]) -> bytes:
"""Decodes a websafe-base64 encoded string.
See: "Base 64 Encoding with URL and Filename Safe Alphabet" from Section 5
in RFC4648 without padding.
:param data: The input to decode.
:return: The decoded bytes.
"""
2021-01-31 16:29:05 +01:00
if isinstance(data, str):
2019-10-01 09:25:29 +02:00
data = data.encode("ascii")
data += b"=" * (-len(data) % 4)
2018-03-02 13:15:13 +01:00
return urlsafe_b64decode(data)
2021-01-31 16:29:05 +01:00
def websafe_encode(data: bytes) -> str:
"""Encodes a byte string into websafe-base64 encoding.
:param data: The input to encode.
:return: The encoded string.
"""
2019-10-01 09:25:29 +02:00
return urlsafe_b64encode(data).replace(b"=", b"").decode("ascii")
2018-03-02 13:15:13 +01:00
class ByteBuffer(BytesIO):
"""BytesIO-like object with the ability to unpack values."""
2021-01-31 16:29:05 +01:00
def unpack(self, fmt: str):
"""Reads and unpacks a value from the buffer.
:param fmt: A struct format string yielding a single value.
:return: The unpacked value.
"""
s = struct.Struct(fmt)
return s.unpack(self.read(s.size))[0]
def read(self, size=-1):
"""Like BytesIO.read(), but checks the number of bytes read and raises an error
if fewer bytes were read than expected.
"""
2021-08-20 10:51:26 +02:00
data = super().read(size)
if size > 0 and len(data) != size:
raise ValueError(
"Not enough data to read (need: %d, had: %d)." % (size, len(data))
)
return data