# Migrating from version 3 Version 4 is a new product with the same name. Version 3 (`cryptography-suite` 3.0.0 on PyPI) was an educational toolkit of primitives, demos, and pipelines; it is retired, receives no security fixes, and has known weaknesses recorded in the [Phase 1 security findings](../v4/baseline/security-findings.md). Do not use it to protect real data. ## What changed | Version 3 | Version 4 | | --- | --- | | Many primitives and algorithm choices exposed to callers | One API, `Protector`, with no algorithm, key-size, nonce, or KDF choices | | Keys handled by the application | Keys held by providers, usually a key service; data keys never leave the SDK | | Several ad hoc file formats | One specified envelope format with test vectors and a conformance suite | | The `cryptography-suite` command | The `cryptosuite` command, with stable exit codes and JSON status | | Demos, pipelines, visualization, code generation | Removed | There is no compatibility layer: v4 does not import v3 code or keep v3 names. It does read v3's encrypted files, but only to move them into v4 envelopes. ## Which format your files are in | You used | Format | Notes | | --- | --- | --- | | `encrypt_file` of 3.0.0 | `raw-aes` | Salt, nonce, and AES-GCM output, with no header. | | `aes_encrypt` of 3.0.0 | `password-aes-v3` | The same bytes as Base64 text. | | `encrypt_file` of the unreleased 3.x line | `csf-v2` | Starts with `CSF!`. | | An older CSF file | `csf-v1` | Its header is not authenticated. | `raw-aes` and `password-aes-v3` do not record which key derivation they used: you declare it. 3.0.0 used Argon2id when pyca/cryptography provided it, and scrypt otherwise, unless you passed `kdf=` yourself. If you changed the `CRYPTOSUITE_ARGON2_*` environment variables, declare the same values in `LegacyKdf`. ## Migrate a file Migration needs a policy that names the formats and a deadline. Nothing is detected: you name the format, and the permission ends on the date you set. ```python import io from datetime import UTC, datetime, timedelta from cryptography_suite import EncryptionContext, Policy, Protector from cryptography_suite.legacy import LegacyKdf from cryptography_suite.migration import migrate_legacy from cryptography_suite.providers.hpke import HpkeRecipientProvider, generate_private_key policy = Policy.migration( deadline=datetime.now(UTC) + timedelta(days=90), legacy_formats=["raw-aes"], ) provider = HpkeRecipientProvider() key = provider.add_identity("archive", generate_private_key()) protector = Protector(provider=provider, policy=policy, primary_key=key) context = EncryptionContext({"tenant": "acme"}, purpose="archive") ``` To show the call, this builds a file as 3.0.0's `encrypt_file` with scrypt wrote it: ```python import os from cryptography.hazmat.primitives.ciphers.aead import AESGCM from cryptography.hazmat.primitives.kdf.scrypt import Scrypt salt, nonce = os.urandom(16), os.urandom(12) v3_key = Scrypt(salt=salt, length=32, n=2**14, r=8, p=1).derive(b"v3 password") legacy_file = salt + nonce + AESGCM(v3_key).encrypt(nonce, b"board minutes", None) ``` A dry run does everything, including the key-service calls and the verification, and publishes nothing: ```python receipt = migrate_legacy( protector, io.BytesIO(legacy_file), None, # dry run legacy_format="raw-aes", password=b"v3 password", context=context, kdf=LegacyKdf("scrypt"), ) print(receipt.verification, receipt.plaintext_bytes) # verified 13 ``` Then publish, with a sink such as `file_sink`, once you have a backup of the source: ```python from pathlib import Path from cryptography_suite.streaming import file_sink root = Path("migrated").resolve() root.mkdir() receipt = migrate_legacy( protector, io.BytesIO(legacy_file), file_sink(output_root=root, relative_destination="minutes.cse", policy=policy), legacy_format="raw-aes", password=b"v3 password", context=context, kdf=LegacyKdf("scrypt"), backup_confirmed=True, ) assert protector.open((root / "minutes.cse").read_bytes(), context=context) == b"board minutes" Path("minutes.receipt.json").write_text(receipt.to_json()) ``` What happens, and what is guaranteed: - The legacy file is decrypted as a stream straight into a new v4 envelope; no plaintext is written anywhere. - The legacy authentication tag is checked at the end of the file, and a second reader reopens the new envelope through the public API. Only if both succeed, and the plaintext matches, is the envelope published. - A wrong password, a damaged file, a failed verification, or a cancellation publishes nothing. - The source is never modified or deleted. Delete it through your own retention process once you have checked the receipt. The receipt (`cs-migration-receipt/1`) records digests and sizes of the source and the envelope, the recipients, the policy, the key derivation, and any warnings, such as an unauthenticated `csf-v1` header. It contains no password, plaintext, context value, or path. Keep it with the envelope. ## With the command line ```console $ cryptosuite --provider-config keys.json --policy migration-policy.json \ migrate --legacy-format raw-aes --legacy-kdf scrypt \ --input minutes.enc --output minutes.cse --receipt minutes.receipt.json \ --context-file context.json --secret-fd 3 3< identity.pem Legacy password: ``` That is a dry run; add `--execute --backup-confirmed` to publish. The password is asked for on the terminal, or read from `--password-fd`; it is never taken from an argument or the environment. The private key is needed because the new envelope is opened again to verify it. The policy file is `Policy.migration(...).to_json()`. ## Keys and key stores v3 also left keys behind: a `LocalKeyStore` directory of `.pem` keys with `.json` metadata, and key files from `serialize_private_key`, `serialize_public_key`, and `to_pem`. v4 never exports key material and keeps local keys only as HPKE recipients, so keys are inventoried and checked, not converted. > **Warning:** `LocalKeyStore.add_key(..., password=...)` of 3.0.0 wrote the > password into the key's `.json` file, next to the key it protects. Anyone > who can read such a directory can decrypt its keys. Treat every key of a > 3.0.0 keystore as stored unencrypted, and replace it. ### Inventory a key store `inventory_keystore` describes each key without decrypting any of them. To show the result, this builds a key store as 3.0.0 wrote it: ```python import json from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import ed25519 keystore = Path("v3-keys") keystore.mkdir() signing_key = ed25519.Ed25519PrivateKey.generate() (keystore / "3f2a9c41d07e5b18.pem").write_bytes( signing_key.private_bytes( serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.BestAvailableEncryption(b"v3 password"), ) ) (keystore / "3f2a9c41d07e5b18.json").write_text( json.dumps({"name": "release signing", "type": "ed25519", "password": "v3 password"}) ) ``` ```python from cryptography_suite.migration import inventory_keystore key_policy = Policy.migration( deadline=datetime.now(UTC) + timedelta(days=90), legacy_formats=["local-keystore", "pem-der"], ) inventory = inventory_keystore(keystore, policy=key_policy) for entry in inventory.entries: print(entry.key_id, entry.v4_use, entry.findings) # 3f2a9c41d07e5b18 none ('metadata-unverified', 'password-in-metadata', 'weak-key-encryption') Path("keystore-inventory.json").write_text(inventory.to_json()) ``` Each entry reports the algorithm and fingerprint (verified for unencrypted keys, claimed by the metadata otherwise), whether v4 can use the key, and findings: | Finding | Meaning | | --- | --- | | `password-in-metadata` | The password is stored beside the key (3.0.0). Replace the key. | | `unencrypted-private-key` | The key is stored unencrypted. | | `weak-key-encryption` | The key file is encrypted with fewer than 600,000 PBKDF2 iterations; v3 used 2,048. | | `unsupported-key-encryption` | The key file is encrypted with a scheme v3 did not write. | | `metadata-missing`, `metadata-invalid`, `metadata-unverified` | The metadata is absent, malformed, or could not be checked against an encrypted key. | | `metadata-mismatch` | The metadata disagrees with the key: its type, fingerprint, or encryption. | | `unknown-metadata-fields` | The metadata has fields v3 did not write. | `v4_use` is `hpke-recipient` for an X25519 or P-384 key that v3 did not use to sign, `unknown` for an encrypted key whose metadata does not say, and `none` otherwise. Entries v4 cannot read safely, such as links, oversized files, or names with unexpected characters, are quarantined with a reason. The names stored in the metadata are left out unless you pass `include_names=True`. v3 keystore keys are Ed25519, ECDSA, and RSA keys used for signatures and RSA decryption. v4 has no local provider for them: keep them only as long as you need to verify old signatures or decrypt old data, or import them into your key service with its own tools. ### Import a key file A key v3 encrypted to, an X25519 key, can stay in use as a v4 HPKE recipient, so a public key you already published keeps working: ```python from cryptography.hazmat.primitives.asymmetric import x25519 from cryptography_suite.migration import KeyPurpose, import_legacy_key # A key file as 3.0.0's serialize_private_key wrote it. ecies_key = x25519.X25519PrivateKey.generate() v3_key_file = ecies_key.private_bytes( serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.BestAvailableEncryption(b"v3 password"), ) recipients = HpkeRecipientProvider() key_receipt = import_legacy_key( recipients, "partner", v3_key_file, policy=key_policy, purpose=KeyPurpose.HPKE_RECIPIENT, password=b"v3 password", ) partner = Protector(provider=recipients, policy=Policy(), primary_key=key_receipt.key) sealed = partner.seal(b"for the partner", context=context) assert partner.open(sealed, context=context) == b"for the partner" print(key_receipt.wrapping_algorithm) # cs4-hpke-x25519-hkdf-sha256-aes-256-gcm ``` A private key becomes an identity and a public key a recipient that can only be sealed to. The rules: - Only X25519 and EC P-384 keys are accepted; anything else is `CAPABILITY_UNSUPPORTED`. Declare `KeyPurpose.HPKE_RECIPIENT` only for a key that was used for key agreement or decryption, never for one that signed. v3 used EC keys only to sign, so a P-384 import carries a warning. - PEM and DER PKCS #8 and SubjectPublicKeyInfo are read; the structure comes from the PEM label or the DER shape. The password is required exactly when the key is encrypted. - An unencrypted private key also needs the `pem-der-unencrypted` grant in the policy. - The policy's provider and algorithm lists apply: a FIPS policy accepts P-384 keys and refuses X25519. - Nothing is written or exported. The receipt (`cs-key-import-receipt/1`) records the key's fingerprint, its v4 reference, and its public key text. ### With the command line ```console $ cryptosuite --policy migration-policy.json migrate \ --legacy-format local-keystore --input ./keys --receipt inventory.json $ cryptosuite --policy migration-policy.json migrate \ --legacy-format pem-der --input partner.pem --key-id partner \ --receipt partner-import.json Legacy password: ``` The second command checks the key and reports its `key_version` and `public_key_text`, which go into a provider configuration. The password is asked for only when the key is encrypted.