1# Copyright 2013 Donald Stufft and individual contributors
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14from __future__ import annotations
15
16from nacl import exceptions as exc
17from nacl._sodium import ffi, lib
18from nacl.exceptions import ensure
19
20crypto_sign_BYTES: int = lib.crypto_sign_bytes()
21# crypto_sign_SEEDBYTES = lib.crypto_sign_seedbytes()
22crypto_sign_SEEDBYTES: int = lib.crypto_sign_secretkeybytes() // 2
23crypto_sign_PUBLICKEYBYTES: int = lib.crypto_sign_publickeybytes()
24crypto_sign_SECRETKEYBYTES: int = lib.crypto_sign_secretkeybytes()
25
26crypto_sign_curve25519_BYTES: int = lib.crypto_box_secretkeybytes()
27
28crypto_sign_ed25519ph_STATEBYTES: int = lib.crypto_sign_ed25519ph_statebytes()
29
30
31def crypto_sign_keypair() -> tuple[bytes, bytes]:
32 """
33 Returns a randomly generated public key and secret key.
34
35 :rtype: (bytes(public_key), bytes(secret_key))
36 """
37 pk = ffi.new("unsigned char[]", crypto_sign_PUBLICKEYBYTES)
38 sk = ffi.new("unsigned char[]", crypto_sign_SECRETKEYBYTES)
39
40 rc = lib.crypto_sign_keypair(pk, sk)
41 ensure(rc == 0, "Unexpected library error", raising=exc.RuntimeError)
42
43 return (
44 ffi.buffer(pk, crypto_sign_PUBLICKEYBYTES)[:],
45 ffi.buffer(sk, crypto_sign_SECRETKEYBYTES)[:],
46 )
47
48
49def crypto_sign_seed_keypair(seed: bytes) -> tuple[bytes, bytes]:
50 """
51 Computes and returns the public key and secret key using the seed ``seed``.
52
53 :param seed: bytes
54 :rtype: (bytes(public_key), bytes(secret_key))
55 """
56 if len(seed) != crypto_sign_SEEDBYTES:
57 raise exc.ValueError("Invalid seed")
58
59 pk = ffi.new("unsigned char[]", crypto_sign_PUBLICKEYBYTES)
60 sk = ffi.new("unsigned char[]", crypto_sign_SECRETKEYBYTES)
61
62 rc = lib.crypto_sign_seed_keypair(pk, sk, seed)
63 ensure(rc == 0, "Unexpected library error", raising=exc.RuntimeError)
64
65 return (
66 ffi.buffer(pk, crypto_sign_PUBLICKEYBYTES)[:],
67 ffi.buffer(sk, crypto_sign_SECRETKEYBYTES)[:],
68 )
69
70
71def crypto_sign(message: bytes, sk: bytes) -> bytes:
72 """
73 Signs the message ``message`` using the secret key ``sk`` and returns the
74 signed message.
75
76 :param message: bytes
77 :param sk: bytes
78 :rtype: bytes
79 """
80 signed = ffi.new("unsigned char[]", len(message) + crypto_sign_BYTES)
81 signed_len = ffi.new("unsigned long long *")
82
83 rc = lib.crypto_sign(signed, signed_len, message, len(message), sk)
84 ensure(rc == 0, "Unexpected library error", raising=exc.RuntimeError)
85
86 return ffi.buffer(signed, signed_len[0])[:]
87
88
89def crypto_sign_open(signed: bytes, pk: bytes) -> bytes:
90 """
91 Verifies the signature of the signed message ``signed`` using the public
92 key ``pk`` and returns the unsigned message.
93
94 :param signed: bytes
95 :param pk: bytes
96 :rtype: bytes
97 """
98 message = ffi.new("unsigned char[]", len(signed))
99 message_len = ffi.new("unsigned long long *")
100
101 if (
102 lib.crypto_sign_open(message, message_len, signed, len(signed), pk)
103 != 0
104 ):
105 raise exc.BadSignatureError("Signature was forged or corrupt")
106
107 return ffi.buffer(message, message_len[0])[:]
108
109
110def crypto_sign_ed25519_pk_to_curve25519(public_key_bytes: bytes) -> bytes:
111 """
112 Converts a public Ed25519 key (encoded as bytes ``public_key_bytes``) to
113 a public Curve25519 key as bytes.
114
115 Raises a ValueError if ``public_key_bytes`` is not of length
116 ``crypto_sign_PUBLICKEYBYTES``
117
118 :param public_key_bytes: bytes
119 :rtype: bytes
120 """
121 if len(public_key_bytes) != crypto_sign_PUBLICKEYBYTES:
122 raise exc.ValueError("Invalid curve public key")
123
124 curve_public_key_len = crypto_sign_curve25519_BYTES
125 curve_public_key = ffi.new("unsigned char[]", curve_public_key_len)
126
127 rc = lib.crypto_sign_ed25519_pk_to_curve25519(
128 curve_public_key, public_key_bytes
129 )
130 ensure(rc == 0, "Unexpected library error", raising=exc.RuntimeError)
131
132 return ffi.buffer(curve_public_key, curve_public_key_len)[:]
133
134
135def crypto_sign_ed25519_sk_to_curve25519(secret_key_bytes: bytes) -> bytes:
136 """
137 Converts a secret Ed25519 key (encoded as bytes ``secret_key_bytes``) to
138 a secret Curve25519 key as bytes.
139
140 Raises a ValueError if ``secret_key_bytes``is not of length
141 ``crypto_sign_SECRETKEYBYTES``
142
143 :param secret_key_bytes: bytes
144 :rtype: bytes
145 """
146 if len(secret_key_bytes) != crypto_sign_SECRETKEYBYTES:
147 raise exc.ValueError("Invalid curve secret key")
148
149 curve_secret_key_len = crypto_sign_curve25519_BYTES
150 curve_secret_key = ffi.new("unsigned char[]", curve_secret_key_len)
151
152 rc = lib.crypto_sign_ed25519_sk_to_curve25519(
153 curve_secret_key, secret_key_bytes
154 )
155 ensure(rc == 0, "Unexpected library error", raising=exc.RuntimeError)
156
157 return ffi.buffer(curve_secret_key, curve_secret_key_len)[:]
158
159
160def crypto_sign_ed25519_sk_to_pk(secret_key_bytes: bytes) -> bytes:
161 """
162 Extract the public Ed25519 key from a secret Ed25519 key (encoded
163 as bytes ``secret_key_bytes``).
164
165 Raises a ValueError if ``secret_key_bytes``is not of length
166 ``crypto_sign_SECRETKEYBYTES``
167
168 :param secret_key_bytes: bytes
169 :rtype: bytes
170 """
171 if len(secret_key_bytes) != crypto_sign_SECRETKEYBYTES:
172 raise exc.ValueError("Invalid secret key")
173
174 return secret_key_bytes[crypto_sign_SEEDBYTES:]
175
176
177def crypto_sign_ed25519_sk_to_seed(secret_key_bytes: bytes) -> bytes:
178 """
179 Extract the seed from a secret Ed25519 key (encoded
180 as bytes ``secret_key_bytes``).
181
182 Raises a ValueError if ``secret_key_bytes``is not of length
183 ``crypto_sign_SECRETKEYBYTES``
184
185 :param secret_key_bytes: bytes
186 :rtype: bytes
187 """
188 if len(secret_key_bytes) != crypto_sign_SECRETKEYBYTES:
189 raise exc.ValueError("Invalid secret key")
190
191 return secret_key_bytes[:crypto_sign_SEEDBYTES]
192
193
194class crypto_sign_ed25519ph_state:
195 """
196 State object wrapping the sha-512 state used in ed25519ph computation
197 """
198
199 __slots__ = ["state"]
200
201 def __init__(self) -> None:
202 self.state: bytes = ffi.new(
203 "unsigned char[]", crypto_sign_ed25519ph_STATEBYTES
204 )
205
206 rc = lib.crypto_sign_ed25519ph_init(self.state)
207
208 ensure(rc == 0, "Unexpected library error", raising=exc.RuntimeError)
209
210
211def crypto_sign_ed25519ph_update(
212 edph: crypto_sign_ed25519ph_state, pmsg: bytes
213) -> None:
214 """
215 Update the hash state wrapped in edph
216
217 :param edph: the ed25519ph state being updated
218 :type edph: crypto_sign_ed25519ph_state
219 :param pmsg: the partial message
220 :type pmsg: bytes
221 :rtype: None
222 """
223 ensure(
224 isinstance(edph, crypto_sign_ed25519ph_state),
225 "edph parameter must be a ed25519ph_state object",
226 raising=exc.TypeError,
227 )
228 ensure(
229 isinstance(pmsg, bytes),
230 "pmsg parameter must be a bytes object",
231 raising=exc.TypeError,
232 )
233 rc = lib.crypto_sign_ed25519ph_update(edph.state, pmsg, len(pmsg))
234 ensure(rc == 0, "Unexpected library error", raising=exc.RuntimeError)
235
236
237def crypto_sign_ed25519ph_final_create(
238 edph: crypto_sign_ed25519ph_state, sk: bytes
239) -> bytes:
240 """
241 Create a signature for the data hashed in edph
242 using the secret key sk
243
244 :param edph: the ed25519ph state for the data
245 being signed
246 :type edph: crypto_sign_ed25519ph_state
247 :param sk: the ed25519 secret key (secret and public part)
248 :type sk: bytes
249 :return: ed25519ph signature
250 :rtype: bytes
251 """
252 ensure(
253 isinstance(edph, crypto_sign_ed25519ph_state),
254 "edph parameter must be a ed25519ph_state object",
255 raising=exc.TypeError,
256 )
257 ensure(
258 isinstance(sk, bytes),
259 "secret key parameter must be a bytes object",
260 raising=exc.TypeError,
261 )
262 ensure(
263 len(sk) == crypto_sign_SECRETKEYBYTES,
264 (f"secret key must be {crypto_sign_SECRETKEYBYTES} bytes long"),
265 raising=exc.TypeError,
266 )
267 signature = ffi.new("unsigned char[]", crypto_sign_BYTES)
268 rc = lib.crypto_sign_ed25519ph_final_create(
269 edph.state, signature, ffi.NULL, sk
270 )
271 ensure(rc == 0, "Unexpected library error", raising=exc.RuntimeError)
272
273 return ffi.buffer(signature, crypto_sign_BYTES)[:]
274
275
276def crypto_sign_ed25519ph_final_verify(
277 edph: crypto_sign_ed25519ph_state, signature: bytes, pk: bytes
278) -> bool:
279 """
280 Verify a prehashed signature using the public key pk
281
282 :param edph: the ed25519ph state for the data
283 being verified
284 :type edph: crypto_sign_ed25519ph_state
285 :param signature: the signature being verified
286 :type signature: bytes
287 :param pk: the ed25519 public part of the signing key
288 :type pk: bytes
289 :return: True if the signature is valid
290 :rtype: boolean
291 :raises exc.BadSignatureError: if the signature is not valid
292 """
293 ensure(
294 isinstance(edph, crypto_sign_ed25519ph_state),
295 "edph parameter must be a ed25519ph_state object",
296 raising=exc.TypeError,
297 )
298 ensure(
299 isinstance(signature, bytes),
300 "signature parameter must be a bytes object",
301 raising=exc.TypeError,
302 )
303 ensure(
304 len(signature) == crypto_sign_BYTES,
305 (f"signature must be {crypto_sign_BYTES} bytes long"),
306 raising=exc.TypeError,
307 )
308 ensure(
309 isinstance(pk, bytes),
310 "public key parameter must be a bytes object",
311 raising=exc.TypeError,
312 )
313 ensure(
314 len(pk) == crypto_sign_PUBLICKEYBYTES,
315 (f"public key must be {crypto_sign_PUBLICKEYBYTES} bytes long"),
316 raising=exc.TypeError,
317 )
318 rc = lib.crypto_sign_ed25519ph_final_verify(edph.state, signature, pk)
319 if rc != 0:
320 raise exc.BadSignatureError("Signature was forged or corrupt")
321
322 return True