• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# This file is dual licensed under the terms of the Apache License, Version
2# 2.0, and the BSD License. See the LICENSE file in the root of this repository
3# for complete details.
4
5from __future__ import absolute_import, division, print_function
6
7import os
8
9from cryptography import exceptions, utils
10from cryptography.hazmat.backends.openssl import aead
11from cryptography.hazmat.backends.openssl.backend import backend
12
13
14class ChaCha20Poly1305(object):
15    _MAX_SIZE = 2 ** 32
16
17    def __init__(self, key):
18        if not backend.aead_cipher_supported(self):
19            raise exceptions.UnsupportedAlgorithm(
20                "ChaCha20Poly1305 is not supported by this version of OpenSSL",
21                exceptions._Reasons.UNSUPPORTED_CIPHER,
22            )
23        utils._check_byteslike("key", key)
24
25        if len(key) != 32:
26            raise ValueError("ChaCha20Poly1305 key must be 32 bytes.")
27
28        self._key = key
29
30    @classmethod
31    def generate_key(cls):
32        return os.urandom(32)
33
34    def encrypt(self, nonce, data, associated_data):
35        if associated_data is None:
36            associated_data = b""
37
38        if len(data) > self._MAX_SIZE or len(associated_data) > self._MAX_SIZE:
39            # This is OverflowError to match what cffi would raise
40            raise OverflowError(
41                "Data or associated data too long. Max 2**32 bytes"
42            )
43
44        self._check_params(nonce, data, associated_data)
45        return aead._encrypt(backend, self, nonce, data, associated_data, 16)
46
47    def decrypt(self, nonce, data, associated_data):
48        if associated_data is None:
49            associated_data = b""
50
51        self._check_params(nonce, data, associated_data)
52        return aead._decrypt(backend, self, nonce, data, associated_data, 16)
53
54    def _check_params(self, nonce, data, associated_data):
55        utils._check_byteslike("nonce", nonce)
56        utils._check_bytes("data", data)
57        utils._check_bytes("associated_data", associated_data)
58        if len(nonce) != 12:
59            raise ValueError("Nonce must be 12 bytes")
60
61
62class AESCCM(object):
63    _MAX_SIZE = 2 ** 32
64
65    def __init__(self, key, tag_length=16):
66        utils._check_byteslike("key", key)
67        if len(key) not in (16, 24, 32):
68            raise ValueError("AESCCM key must be 128, 192, or 256 bits.")
69
70        self._key = key
71        if not isinstance(tag_length, int):
72            raise TypeError("tag_length must be an integer")
73
74        if tag_length not in (4, 6, 8, 10, 12, 14, 16):
75            raise ValueError("Invalid tag_length")
76
77        self._tag_length = tag_length
78
79    @classmethod
80    def generate_key(cls, bit_length):
81        if not isinstance(bit_length, int):
82            raise TypeError("bit_length must be an integer")
83
84        if bit_length not in (128, 192, 256):
85            raise ValueError("bit_length must be 128, 192, or 256")
86
87        return os.urandom(bit_length // 8)
88
89    def encrypt(self, nonce, data, associated_data):
90        if associated_data is None:
91            associated_data = b""
92
93        if len(data) > self._MAX_SIZE or len(associated_data) > self._MAX_SIZE:
94            # This is OverflowError to match what cffi would raise
95            raise OverflowError(
96                "Data or associated data too long. Max 2**32 bytes"
97            )
98
99        self._check_params(nonce, data, associated_data)
100        self._validate_lengths(nonce, len(data))
101        return aead._encrypt(
102            backend, self, nonce, data, associated_data, self._tag_length
103        )
104
105    def decrypt(self, nonce, data, associated_data):
106        if associated_data is None:
107            associated_data = b""
108
109        self._check_params(nonce, data, associated_data)
110        return aead._decrypt(
111            backend, self, nonce, data, associated_data, self._tag_length
112        )
113
114    def _validate_lengths(self, nonce, data_len):
115        # For information about computing this, see
116        # https://tools.ietf.org/html/rfc3610#section-2.1
117        l_val = 15 - len(nonce)
118        if 2 ** (8 * l_val) < data_len:
119            raise ValueError("Data too long for nonce")
120
121    def _check_params(self, nonce, data, associated_data):
122        utils._check_byteslike("nonce", nonce)
123        utils._check_bytes("data", data)
124        utils._check_bytes("associated_data", associated_data)
125        if not 7 <= len(nonce) <= 13:
126            raise ValueError("Nonce must be between 7 and 13 bytes")
127
128
129class AESGCM(object):
130    _MAX_SIZE = 2 ** 32
131
132    def __init__(self, key):
133        utils._check_byteslike("key", key)
134        if len(key) not in (16, 24, 32):
135            raise ValueError("AESGCM key must be 128, 192, or 256 bits.")
136
137        self._key = key
138
139    @classmethod
140    def generate_key(cls, bit_length):
141        if not isinstance(bit_length, int):
142            raise TypeError("bit_length must be an integer")
143
144        if bit_length not in (128, 192, 256):
145            raise ValueError("bit_length must be 128, 192, or 256")
146
147        return os.urandom(bit_length // 8)
148
149    def encrypt(self, nonce, data, associated_data):
150        if associated_data is None:
151            associated_data = b""
152
153        if len(data) > self._MAX_SIZE or len(associated_data) > self._MAX_SIZE:
154            # This is OverflowError to match what cffi would raise
155            raise OverflowError(
156                "Data or associated data too long. Max 2**32 bytes"
157            )
158
159        self._check_params(nonce, data, associated_data)
160        return aead._encrypt(backend, self, nonce, data, associated_data, 16)
161
162    def decrypt(self, nonce, data, associated_data):
163        if associated_data is None:
164            associated_data = b""
165
166        self._check_params(nonce, data, associated_data)
167        return aead._decrypt(backend, self, nonce, data, associated_data, 16)
168
169    def _check_params(self, nonce, data, associated_data):
170        utils._check_byteslike("nonce", nonce)
171        utils._check_bytes("data", data)
172        utils._check_bytes("associated_data", associated_data)
173        if len(nonce) < 8 or len(nonce) > 128:
174            raise ValueError("Nonce must be between 8 and 128 bytes")
175