python-vaultwarden2 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
vaultwarden2/crypto.py ADDED
@@ -0,0 +1,634 @@
1
+ """Vaultwarden client-side cryptography, without any network access.
2
+
3
+ Most users never need this module: the clients encrypt and decrypt automatically. It is public for tooling
4
+ and for verifying the library's behaviour.
5
+
6
+ Covers key derivation (PBKDF2-SHA256, Argon2id), the server authentication hash, key stretching, and the
7
+ encrypted-string (``EncString``) formats Vaultwarden uses:
8
+
9
+ * type 0: AES-256-CBC without MAC (legacy, read only)
10
+ * type 2: AES-256-CBC + HMAC-SHA256 (``iv|ciphertext|mac``), the current format
11
+ * types 3 and 4: RSA-2048-OAEP with SHA-256 or SHA-1 (sharing organization keys)
12
+ * types 5 and 6: as 3 and 4 with a deprecated, ignored HMAC part
13
+
14
+ Type 7 (COSE, the newer "v2" cryptography of the official apps) is not supported; vaultwarden 1.37 does not use it.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import base64
20
+ import hashlib
21
+ import hmac
22
+ import os
23
+ from dataclasses import dataclass
24
+ from enum import IntEnum
25
+ from typing import TYPE_CHECKING, Self
26
+
27
+ from cryptography.exceptions import UnsupportedAlgorithm
28
+ from cryptography.hazmat.primitives import hashes, padding, serialization
29
+ from cryptography.hazmat.primitives.asymmetric import padding as asym_padding
30
+ from cryptography.hazmat.primitives.asymmetric import rsa
31
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
32
+ from cryptography.hazmat.primitives.kdf.argon2 import Argon2id
33
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDFExpand
34
+
35
+ from vaultwarden2.errors import CryptoError
36
+
37
+ if TYPE_CHECKING:
38
+ from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
39
+
40
+ KEY_SIZE = 32
41
+ IV_SIZE = 16
42
+ MAC_SIZE = 32
43
+
44
+
45
+ class KdfType(IntEnum):
46
+ """Key derivation function of an account.
47
+
48
+ Attributes:
49
+ PBKDF2_SHA256: PBKDF2 with SHA-256 (iterations only).
50
+ ARGON2ID: Argon2id (iterations, memory and parallelism).
51
+ """
52
+
53
+ PBKDF2_SHA256 = 0
54
+ ARGON2ID = 1
55
+
56
+
57
+ @dataclass(frozen=True, slots=True, kw_only=True)
58
+ class KdfParams:
59
+ """Key derivation settings of an account.
60
+
61
+ Attributes:
62
+ type: The algorithm.
63
+ iterations: PBKDF2 iterations, or the Argon2id time cost (passes).
64
+ memory: Argon2id memory in MiB; None for PBKDF2.
65
+ parallelism: Argon2id lanes; None for PBKDF2.
66
+ """
67
+
68
+ type: KdfType
69
+ iterations: int
70
+ memory: int | None = None
71
+ parallelism: int | None = None
72
+
73
+ @classmethod
74
+ def pbkdf2(cls, iterations: int = 600_000) -> Self:
75
+ """PBKDF2-SHA256 settings. The default is vaultwarden's and the official apps' (600000 iterations).
76
+
77
+ Args:
78
+ iterations: Number of iterations. vaultwarden accepts 100000 or more; this library allows up to 2000000.
79
+
80
+ Returns:
81
+ The settings.
82
+ """
83
+ return cls(type=KdfType.PBKDF2_SHA256, iterations=iterations)
84
+
85
+ @classmethod
86
+ def argon2id(cls, iterations: int = 6, memory: int = 32, parallelism: int = 4) -> Self:
87
+ """Argon2id settings. The defaults are those of the official apps (6 passes, 32 MiB, 4 lanes).
88
+
89
+ Args:
90
+ iterations: Time cost (passes), 2-10 for use with this library and the official apps.
91
+ memory: Memory in MiB, 16-1024.
92
+ parallelism: Lanes, 1-16.
93
+
94
+ Returns:
95
+ The settings.
96
+ """
97
+ return cls(type=KdfType.ARGON2ID, iterations=iterations, memory=memory, parallelism=parallelism)
98
+
99
+
100
+ def normalize_email(email: str) -> str:
101
+ """Normalize an email address the way the official apps do before using it as KDF salt.
102
+
103
+ Args:
104
+ email: The email address.
105
+
106
+ Returns:
107
+ The address without surrounding spaces, lowercased.
108
+ """
109
+ return email.strip().lower()
110
+
111
+
112
+ def make_master_key(password: str, email: str, kdf: KdfParams) -> bytes:
113
+ """Derive the 32-byte master key from the master password, salted with the email address.
114
+
115
+ Args:
116
+ password: The master password.
117
+ email: The account's email address (normalized before use).
118
+ kdf: The account's KDF settings.
119
+
120
+ Returns:
121
+ The master key.
122
+
123
+ Raises:
124
+ CryptoError: Argon2id settings without memory or parallelism, or an unsupported KDF type.
125
+ """
126
+ pw = password.encode()
127
+ salt = normalize_email(email).encode()
128
+ if kdf.type == KdfType.PBKDF2_SHA256:
129
+ return hashlib.pbkdf2_hmac('sha256', pw, salt, kdf.iterations, KEY_SIZE)
130
+ if kdf.type == KdfType.ARGON2ID:
131
+ if kdf.memory is None or kdf.parallelism is None:
132
+ raise CryptoError('Argon2id needs memory and parallelism')
133
+ return Argon2id(
134
+ salt=hashlib.sha256(salt).digest(),
135
+ length=KEY_SIZE,
136
+ iterations=kdf.iterations,
137
+ lanes=kdf.parallelism,
138
+ memory_cost=kdf.memory * 1024,
139
+ ).derive(pw)
140
+ raise CryptoError(f'unsupported KDF type {kdf.type}')
141
+
142
+
143
+ def master_password_hash(master_key: bytes, password: str) -> str:
144
+ """The server authentication hash, sent instead of the password at login.
145
+
146
+ Args:
147
+ master_key: The master key.
148
+ password: The master password.
149
+
150
+ Returns:
151
+ The base64 hash (PBKDF2-SHA256 of the master key, salted with the password, one iteration).
152
+ """
153
+ return base64.b64encode(hashlib.pbkdf2_hmac('sha256', master_key, password.encode(), 1, KEY_SIZE)).decode()
154
+
155
+
156
+ def _hkdf_expand(prk: bytes, info: bytes) -> bytes:
157
+ """HKDF-Expand with SHA-256 to 32 bytes.
158
+
159
+ Args:
160
+ prk: The pseudo-random key (here: the master key).
161
+ info: The context string (``enc`` or ``mac``).
162
+
163
+ Returns:
164
+ The derived key.
165
+ """
166
+ return HKDFExpand(algorithm=hashes.SHA256(), length=KEY_SIZE, info=info).derive(prk)
167
+
168
+
169
+ @dataclass(frozen=True, slots=True)
170
+ class SymmetricKey:
171
+ """An AES-256 key, optionally paired with an HMAC-SHA256 key. Key material never appears in ``repr()``.
172
+
173
+ Attributes:
174
+ enc_key: The 32-byte encryption key.
175
+ mac_key: The 32-byte MAC key, or None for legacy encryption-only keys.
176
+ """
177
+
178
+ enc_key: bytes
179
+ mac_key: bytes | None = None
180
+
181
+ def __post_init__(self) -> None:
182
+ """Reject keys of the wrong size.
183
+
184
+ Raises:
185
+ CryptoError: A key is not 32 bytes long.
186
+ """
187
+ if len(self.enc_key) != KEY_SIZE or (self.mac_key is not None and len(self.mac_key) != KEY_SIZE):
188
+ raise CryptoError('invalid symmetric key size')
189
+
190
+ def __repr__(self) -> str:
191
+ """Describe the key without its material.
192
+
193
+ Returns:
194
+ ``SymmetricKey(mac=yes)`` or ``SymmetricKey(mac=no)``.
195
+ """
196
+ return f'SymmetricKey(mac={"yes" if self.mac_key else "no"})'
197
+
198
+ @classmethod
199
+ def from_bytes(cls, data: bytes) -> Self:
200
+ """Build a key from raw bytes.
201
+
202
+ Args:
203
+ data: 64 bytes (encryption key followed by MAC key) or 32 bytes (encryption key only).
204
+
205
+ Returns:
206
+ The key.
207
+
208
+ Raises:
209
+ CryptoError: The length is neither 64 nor 32.
210
+ """
211
+ if len(data) == 2 * KEY_SIZE:
212
+ return cls(data[:KEY_SIZE], data[KEY_SIZE:])
213
+ if len(data) == KEY_SIZE:
214
+ return cls(data)
215
+ raise CryptoError(f'invalid symmetric key length {len(data)}')
216
+
217
+ @classmethod
218
+ def generate(cls) -> Self:
219
+ """Create a new random encryption + MAC key.
220
+
221
+ Returns:
222
+ The key.
223
+ """
224
+ return cls(os.urandom(KEY_SIZE), os.urandom(KEY_SIZE))
225
+
226
+ @classmethod
227
+ def stretch(cls, master_key: bytes) -> Self:
228
+ """Stretch a master key into encryption and MAC keys (HKDF-Expand with ``enc`` and ``mac``).
229
+
230
+ Args:
231
+ master_key: The 32-byte master key.
232
+
233
+ Returns:
234
+ The stretched key, used to wrap the user key.
235
+ """
236
+ return cls(_hkdf_expand(master_key, b'enc'), _hkdf_expand(master_key, b'mac'))
237
+
238
+ def to_bytes(self) -> bytes:
239
+ """The raw key bytes.
240
+
241
+ Returns:
242
+ The encryption key, followed by the MAC key if present.
243
+ """
244
+ return self.enc_key + (self.mac_key or b'')
245
+
246
+
247
+ class EncStringType(IntEnum):
248
+ """Encrypted-string formats.
249
+
250
+ Attributes:
251
+ AES_CBC256_B64: AES-256-CBC without MAC (legacy).
252
+ AES_CBC256_HMAC_SHA256_B64: AES-256-CBC with HMAC-SHA256, the current format.
253
+ RSA2048_OAEP_SHA256_B64: RSA-OAEP with SHA-256.
254
+ RSA2048_OAEP_SHA1_B64: RSA-OAEP with SHA-1 (used for organization keys).
255
+ RSA2048_OAEP_SHA256_HMAC_SHA256_B64: As RSA-OAEP-SHA256, with a deprecated MAC part.
256
+ RSA2048_OAEP_SHA1_HMAC_SHA256_B64: As RSA-OAEP-SHA1, with a deprecated MAC part.
257
+ COSE_ENCRYPT0_B64: v2 cryptography (COSE); recognised but not supported.
258
+ """
259
+
260
+ AES_CBC256_B64 = 0
261
+ AES_CBC256_HMAC_SHA256_B64 = 2
262
+ RSA2048_OAEP_SHA256_B64 = 3
263
+ RSA2048_OAEP_SHA1_B64 = 4
264
+ RSA2048_OAEP_SHA256_HMAC_SHA256_B64 = 5
265
+ RSA2048_OAEP_SHA1_HMAC_SHA256_B64 = 6
266
+ COSE_ENCRYPT0_B64 = 7
267
+
268
+
269
+ _RSA_TYPES = {
270
+ EncStringType.RSA2048_OAEP_SHA256_B64,
271
+ EncStringType.RSA2048_OAEP_SHA1_B64,
272
+ EncStringType.RSA2048_OAEP_SHA256_HMAC_SHA256_B64,
273
+ EncStringType.RSA2048_OAEP_SHA1_HMAC_SHA256_B64,
274
+ }
275
+
276
+
277
+ def _b64d(value: str) -> bytes:
278
+ """Strict base64 decoding.
279
+
280
+ Args:
281
+ value: The base64 text.
282
+
283
+ Returns:
284
+ The decoded bytes.
285
+
286
+ Raises:
287
+ CryptoError: The text is not valid base64.
288
+ """
289
+ try:
290
+ return base64.b64decode(value, validate=True)
291
+ except ValueError as e:
292
+ raise CryptoError('invalid base64 in EncString') from e
293
+
294
+
295
+ @dataclass(frozen=True, slots=True)
296
+ class EncString:
297
+ """A parsed encrypted string: ``<type>.<iv>|<ciphertext>|<mac>`` (symmetric) or ``<type>.<ciphertext>`` (RSA).
298
+
299
+ Attributes:
300
+ type: The format.
301
+ data: The ciphertext.
302
+ iv: The initialisation vector (symmetric formats), else None.
303
+ mac: The HMAC (type 2), else None.
304
+ """
305
+
306
+ type: EncStringType
307
+ data: bytes
308
+ iv: bytes | None = None
309
+ mac: bytes | None = None
310
+
311
+ @classmethod
312
+ def parse(cls, value: str) -> Self:
313
+ """Parse the string form.
314
+
315
+ Args:
316
+ value: The encrypted string, for example ``2.<iv>|<ciphertext>|<mac>``.
317
+
318
+ Returns:
319
+ The parsed value.
320
+
321
+ Raises:
322
+ CryptoError: Malformed, unsupported (type 7 or unknown) or with wrong IV/MAC sizes.
323
+ """
324
+ head, sep, rest = value.partition('.')
325
+ if not sep or not head.isdigit():
326
+ raise CryptoError('malformed EncString')
327
+ try:
328
+ enc_type = EncStringType(int(head))
329
+ except ValueError as e:
330
+ raise CryptoError(f'unsupported EncString type {head}') from e
331
+ parts = rest.split('|')
332
+ if enc_type == EncStringType.AES_CBC256_B64 and len(parts) == 2:
333
+ iv, data = (_b64d(p) for p in parts)
334
+ mac = None
335
+ elif enc_type == EncStringType.AES_CBC256_HMAC_SHA256_B64 and len(parts) == 3:
336
+ iv, data, mac = (_b64d(p) for p in parts)
337
+ elif enc_type in _RSA_TYPES and len(parts) in {1, 2}:
338
+ return cls(enc_type, _b64d(parts[0]))
339
+ elif enc_type == EncStringType.COSE_ENCRYPT0_B64:
340
+ raise CryptoError('COSE (type 7) EncStrings are not supported yet')
341
+ else:
342
+ raise CryptoError(f'malformed EncString of type {enc_type.value}')
343
+ if len(iv) != IV_SIZE or (mac is not None and len(mac) != MAC_SIZE):
344
+ raise CryptoError('malformed EncString (iv/mac size)')
345
+ return cls(enc_type, data, iv, mac)
346
+
347
+ def __str__(self) -> str:
348
+ """Serialize to the string form.
349
+
350
+ Returns:
351
+ The encrypted string.
352
+ """
353
+ parts = [self.iv, self.data, self.mac] if self.iv is not None else [self.data]
354
+ return f'{self.type.value}.' + '|'.join(base64.b64encode(p).decode() for p in parts if p is not None)
355
+
356
+
357
+ def is_enc_string(value: object) -> bool:
358
+ """Whether a value looks like a symmetric (type 0 or 2) encrypted string.
359
+
360
+ Args:
361
+ value: Any value.
362
+
363
+ Returns:
364
+ True for strings like ``2.xxx|yyy|zzz``.
365
+ """
366
+ return isinstance(value, str) and len(value) > 2 and value[0] in '02' and value[1] == '.' and '|' in value
367
+
368
+
369
+ def encrypt(plaintext: bytes | str, key: SymmetricKey) -> EncString:
370
+ """Encrypt with AES-256-CBC + HMAC-SHA256 (type 2), with a fresh random IV.
371
+
372
+ Args:
373
+ plaintext: The data; strings are UTF-8 encoded.
374
+ key: A key with MAC part.
375
+
376
+ Returns:
377
+ The encrypted string.
378
+
379
+ Raises:
380
+ CryptoError: The key has no MAC part.
381
+ """
382
+ if key.mac_key is None:
383
+ raise CryptoError('encryption needs a key with a MAC part')
384
+ data = plaintext.encode() if isinstance(plaintext, str) else plaintext
385
+ iv = os.urandom(IV_SIZE)
386
+ padder = padding.PKCS7(128).padder()
387
+ padded = padder.update(data) + padder.finalize()
388
+ encryptor = Cipher(algorithms.AES(key.enc_key), modes.CBC(iv)).encryptor()
389
+ ct = encryptor.update(padded) + encryptor.finalize()
390
+ mac = hmac.digest(key.mac_key, iv + ct, 'sha256')
391
+ return EncString(EncStringType.AES_CBC256_HMAC_SHA256_B64, ct, iv, mac)
392
+
393
+
394
+ def decrypt(value: EncString | str, key: SymmetricKey) -> bytes:
395
+ """Decrypt a type 0 or type 2 encrypted string. The MAC is verified before decrypting.
396
+
397
+ Args:
398
+ value: The encrypted string, parsed or as text.
399
+ key: The key. Type 2 needs a key with MAC part; type 0 is only accepted for encryption-only keys.
400
+
401
+ Returns:
402
+ The plaintext bytes.
403
+
404
+ Raises:
405
+ CryptoError: Wrong key, tampered data (MAC mismatch), invalid ciphertext or an RSA format.
406
+ """
407
+ enc = EncString.parse(value) if isinstance(value, str) else value
408
+ if enc.iv is None:
409
+ raise CryptoError(f'EncString type {enc.type.value} is not symmetric')
410
+ if enc.type == EncStringType.AES_CBC256_HMAC_SHA256_B64:
411
+ if key.mac_key is None or enc.mac is None:
412
+ raise CryptoError('MAC key or MAC missing')
413
+ if not hmac.compare_digest(hmac.digest(key.mac_key, enc.iv + enc.data, 'sha256'), enc.mac):
414
+ raise CryptoError('MAC mismatch (wrong key or tampered data)')
415
+ elif key.mac_key is not None:
416
+ # Type 0 strings carry no MAC; the official apps only accept them with enc-only keys.
417
+ raise CryptoError('unauthenticated EncString (type 0) for a key with MAC')
418
+ try:
419
+ decryptor = Cipher(algorithms.AES(key.enc_key), modes.CBC(enc.iv)).decryptor()
420
+ padded = decryptor.update(enc.data) + decryptor.finalize()
421
+ unpadder = padding.PKCS7(128).unpadder()
422
+ return unpadder.update(padded) + unpadder.finalize()
423
+ except ValueError as e: # bad block length or padding
424
+ raise CryptoError('invalid ciphertext') from e
425
+
426
+
427
+ def decrypt_str(value: EncString | str, key: SymmetricKey) -> str:
428
+ """Decrypt and decode as UTF-8.
429
+
430
+ Args:
431
+ value: The encrypted string, parsed or as text.
432
+ key: The key.
433
+
434
+ Returns:
435
+ The plaintext text.
436
+
437
+ Raises:
438
+ CryptoError: Decryption failed, or the plaintext is not valid UTF-8.
439
+ """
440
+ try:
441
+ return decrypt(value, key).decode()
442
+ except UnicodeDecodeError as e:
443
+ raise CryptoError('decrypted value is not valid UTF-8') from e
444
+
445
+
446
+ def decrypt_user_key(protected_key: str, master_key: bytes) -> SymmetricKey:
447
+ """Unwrap the account's user key with the master key.
448
+
449
+ Type 2 uses the stretched master key; legacy type 0 uses the master key directly.
450
+
451
+ Args:
452
+ protected_key: The protected user key from the server.
453
+ master_key: The master key.
454
+
455
+ Returns:
456
+ The user key.
457
+
458
+ Raises:
459
+ CryptoError: Wrong master key (wrong password) or malformed key.
460
+ """
461
+ enc = EncString.parse(protected_key)
462
+ wrapping = SymmetricKey.stretch(master_key) if enc.type == EncStringType.AES_CBC256_HMAC_SHA256_B64 else SymmetricKey(master_key)
463
+ return SymmetricKey.from_bytes(decrypt(enc, wrapping))
464
+
465
+
466
+ def load_private_key(encrypted_private_key: str, user_key: SymmetricKey) -> RSAPrivateKey:
467
+ """Decrypt the account's RSA private key (PKCS#8 DER).
468
+
469
+ Args:
470
+ encrypted_private_key: The encrypted private key from the server.
471
+ user_key: The user key.
472
+
473
+ Returns:
474
+ The private key.
475
+
476
+ Raises:
477
+ CryptoError: Decryption failed, or the result is not an RSA private key.
478
+ """
479
+ try:
480
+ key = serialization.load_der_private_key(decrypt(encrypted_private_key, user_key), password=None)
481
+ except (ValueError, TypeError, UnsupportedAlgorithm) as e:
482
+ raise CryptoError('account private key cannot be loaded') from e
483
+ if not isinstance(key, rsa.RSAPrivateKey):
484
+ raise CryptoError('account private key is not RSA')
485
+ return key
486
+
487
+
488
+ def rsa_decrypt(value: EncString | str, private_key: RSAPrivateKey) -> bytes:
489
+ """Decrypt an RSA-OAEP encrypted string (types 3 to 6).
490
+
491
+ Args:
492
+ value: The encrypted string, parsed or as text.
493
+ private_key: The RSA private key.
494
+
495
+ Returns:
496
+ The plaintext bytes.
497
+
498
+ Raises:
499
+ CryptoError: Not an RSA format, or decryption failed.
500
+ """
501
+ enc = EncString.parse(value) if isinstance(value, str) else value
502
+ if enc.type not in _RSA_TYPES:
503
+ raise CryptoError(f'EncString type {enc.type.value} is not RSA')
504
+ sha1 = enc.type in {EncStringType.RSA2048_OAEP_SHA1_B64, EncStringType.RSA2048_OAEP_SHA1_HMAC_SHA256_B64}
505
+ algo: hashes.HashAlgorithm = hashes.SHA1() if sha1 else hashes.SHA256() # noqa: S303 - mandated by the vault format
506
+ try:
507
+ return private_key.decrypt(enc.data, asym_padding.OAEP(mgf=asym_padding.MGF1(algorithm=algo), algorithm=algo, label=None))
508
+ except ValueError as e:
509
+ raise CryptoError('RSA decryption failed') from e
510
+
511
+
512
+ def rsa_encrypt(plaintext: bytes, public_key: rsa.RSAPublicKey) -> EncString:
513
+ """Encrypt with RSA-OAEP-SHA1 (type 4), as the official apps do for shared keys.
514
+
515
+ Args:
516
+ plaintext: The data, for example an organization key.
517
+ public_key: The recipient's RSA public key.
518
+
519
+ Returns:
520
+ The encrypted string.
521
+ """
522
+ algo = hashes.SHA1() # noqa: S303 - mandated by the vault format
523
+ data = public_key.encrypt(plaintext, asym_padding.OAEP(mgf=asym_padding.MGF1(algorithm=algo), algorithm=algo, label=None))
524
+ return EncString(EncStringType.RSA2048_OAEP_SHA1_B64, data)
525
+
526
+
527
+ def generate_key_pair(user_key: SymmetricKey) -> tuple[str, str]:
528
+ """Create an RSA-2048 key pair for an account or organization.
529
+
530
+ Args:
531
+ user_key: The key that protects the private key.
532
+
533
+ Returns:
534
+ ``(public_key, encrypted_private_key)``: the base64 SPKI public key and the private key encrypted with
535
+ ``user_key``.
536
+ """
537
+ private = rsa.generate_private_key(public_exponent=65537, key_size=2048)
538
+ public_der = private.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
539
+ private_der = private.private_bytes(serialization.Encoding.DER, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())
540
+ return base64.b64encode(public_der).decode(), str(encrypt(private_der, user_key))
541
+
542
+
543
+ def encrypt_buffer(data: bytes, key: SymmetricKey) -> bytes:
544
+ """Encrypt binary data (attachments) into the vault's encrypted-file format: ``type | iv | mac | ciphertext``.
545
+
546
+ Args:
547
+ data: The file content.
548
+ key: A key with MAC part.
549
+
550
+ Returns:
551
+ The encrypted buffer.
552
+ """
553
+ enc = encrypt(data, key)
554
+ if enc.iv is None or enc.mac is None: # pragma: no cover - encrypt() always sets both
555
+ raise CryptoError('internal: missing iv/mac')
556
+ return bytes([enc.type.value]) + enc.iv + enc.mac + enc.data
557
+
558
+
559
+ def decrypt_buffer(buffer: bytes, key: SymmetricKey) -> bytes:
560
+ """Decrypt a buffer in the vault's encrypted-file format (type 2 only).
561
+
562
+ Args:
563
+ buffer: The encrypted buffer.
564
+ key: The key.
565
+
566
+ Returns:
567
+ The plaintext bytes.
568
+
569
+ Raises:
570
+ CryptoError: Malformed buffer, unsupported type, wrong key or tampered data.
571
+ """
572
+ header = 1 + IV_SIZE + MAC_SIZE
573
+ if len(buffer) < header + 16 or buffer[0] != EncStringType.AES_CBC256_HMAC_SHA256_B64:
574
+ raise CryptoError('malformed or unsupported encrypted buffer')
575
+ iv, mac, data = buffer[1 : 1 + IV_SIZE], buffer[1 + IV_SIZE : header], buffer[header:]
576
+ return decrypt(EncString(EncStringType.AES_CBC256_HMAC_SHA256_B64, data, iv, mac), key)
577
+
578
+
579
+ def uri_checksum(uri: str) -> str:
580
+ """The checksum the official apps store (encrypted) next to each login URI.
581
+
582
+ Args:
583
+ uri: The URI.
584
+
585
+ Returns:
586
+ base64(SHA-256(uri)).
587
+ """
588
+ return base64.b64encode(hashlib.sha256(uri.encode()).digest()).decode()
589
+
590
+
591
+ def ssh_public_key_and_fingerprint(private_key: str) -> tuple[str, str]:
592
+ """Derive the public key and fingerprint of an SSH private key.
593
+
594
+ Args:
595
+ private_key: The private key in OpenSSH or PEM format, unencrypted.
596
+
597
+ Returns:
598
+ ``(public_key, fingerprint)``: the OpenSSH public key line and the ``SHA256:...`` fingerprint.
599
+
600
+ Raises:
601
+ CryptoError: The key cannot be parsed (encrypted or unsupported format).
602
+ """
603
+ try:
604
+ key = serialization.load_ssh_private_key(private_key.encode(), password=None)
605
+ except (ValueError, TypeError, UnsupportedAlgorithm):
606
+ try:
607
+ key = serialization.load_pem_private_key(private_key.encode(), password=None) # type: ignore[assignment]
608
+ except (ValueError, TypeError, UnsupportedAlgorithm) as e:
609
+ raise CryptoError('cannot parse SSH private key (encrypted or unsupported format)') from e
610
+ public = key.public_key().public_bytes(serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH)
611
+ blob = base64.b64decode(public.split()[1])
612
+ fingerprint = 'SHA256:' + base64.b64encode(hashlib.sha256(blob).digest()).decode().rstrip('=')
613
+ return public.decode(), fingerprint
614
+
615
+
616
+ def load_public_key(public_key_b64: str) -> rsa.RSAPublicKey:
617
+ """Load an RSA public key as the server stores it.
618
+
619
+ Args:
620
+ public_key_b64: The base64 SPKI (DER) public key.
621
+
622
+ Returns:
623
+ The public key.
624
+
625
+ Raises:
626
+ CryptoError: Not valid, or not an RSA key.
627
+ """
628
+ try:
629
+ key = serialization.load_der_public_key(base64.b64decode(public_key_b64))
630
+ except ValueError as e:
631
+ raise CryptoError('invalid public key') from e
632
+ if not isinstance(key, rsa.RSAPublicKey):
633
+ raise CryptoError('public key is not RSA')
634
+ return key