Files
purepycrypto/docs/errors.md
T
dvs 0d69391aa9 Release v3.2.0: pure-Python cryptography library (English docs/comments/errors)
- Zero-dependency pure-Python cryptography: SHA-2 / SHA-3 / SHAKE / BLAKE2b,
  HMAC, PBKDF2 / HKDF / scrypt / Argon2id, AES (ECB/CBC/CTR/CFB/OFB/GCM),
  AES-GCM-SIV, ChaCha20-Poly1305 / XChaCha20-Poly1305, X25519, Ed25519,
  RSA (keygen / OAEP / PSS / PEM), ASN.1 DER
- Unified error system: PPYC_ERR fatal exception vs (code, message, suggestion)
  non-fatal 3-tuple return
- Interactive TUI (Chinese / English i18n) + non-interactive CLI
- v3.2.0 adds the encoding, rand and kdf2 modules
- Documentation, code comments and error messages fully in English;
  the interactive TUI keeps its Chinese interface
- Tests: RFC / FIPS / NIST test vectors, 639 passing
2026-09-27 09:40:12 +08:00

9.0 KiB
Raw Blame History

Error System Manual (PPYC_ERR)

As of purepycrypto v3.2.0, the library uses a unified error system. This document is the authoritative reference for error codes and handling.


1. Design Principles

The library strictly divides errors into two categories, semantically clear and never mixed:

Type Handling Applicable scenarios
Fatal error Raise PPYC_ERR The program can no longer run safely: internal invariant broken (library bug), fatal environment problem, unable to construct an object during initialization
Non-fatal error Return a 3-tuple (error_code, error_message, suggestion) Expected failures: invalid input, failed validation, authentication failure, missing file, parse failure

Core idea: expected failures should not be expressed with exceptions — the caller can handle them gracefully by checking the return value; whereas a genuine crash should let the exception bubble up to expose the problem.


2. Fatal Error: PPYC_ERR

from purepycrypto import PPYC_ERR, PPYC_ERR_INTERNAL

try:
    ...
except PPYC_ERR as e:
    print(e.code)        # 'PPYC_ERR_INTERNAL'
    print(e.message)     # human-readable reason
    print(e.suggestion)  # human-readable fix suggestion
    print(str(e))        # '[PPYC_ERR_INTERNAL] reason  Suggestion: ...'

Construction

raise PPYC_ERR(code, message, suggestion="")
# or the convenience function
from purepycrypto import raise_ppyc
raise_ppyc(PPYC_ERR_INTERNAL, "state machine inconsistent", "please file an issue")

Attributes

Attribute Type Description
code str error code, in the form PPYC_ERR_xxx
message str reason description
suggestion str fix suggestion (may be empty)
as_tuple() method returns (code, message, suggestion)

Legacy Exception Name Compatibility

The following historical exception names remain available; all are subclasses of PPYC_ERR and carry code/message/suggestion:

Legacy name Default code
CryptoError PPYC_ERR_INTERNAL
DecryptionError PPYC_ERR_AUTH_FAILED
Ed25519Error PPYC_ERR_INVALID_ARG
PPYCError (alias of PPYC_ERR)

3. Non-Fatal Errors: 3-Tuple Return

from purepycrypto import err, ok, is_ok, is_err, OK_TUPLE

# error
return err(PPYC_ERR_INVALID_KEY_LEN, "AES key must be 16/24/32 bytes", "pass a correct length")
#   -> ('PPYC_ERR_INVALID_KEY_LEN', 'AES key must be 16/24/32 bytes', 'pass a correct length')

# success (validation-style API)
return OK_TUPLE        # (None, None, None)

Caller Checks

result = some_api(...)

# method 1: generic check (works for any API)
if is_err(result):
    code, msg, hint = result
    print(code, msg, hint)

# method 2: using aes.gcm_decrypt as an example (returns plaintext bytes on success, a tuple on failure)
out = aes.gcm_decrypt(nonce, ct, tag, aad)
if isinstance(out, tuple) and out[0] is not None:
    code, msg, hint = out
    ...   # handle the error
else:
    plaintext = out

Helper Functions

Function Description
err(code, message, suggestion="") construct an error tuple (validates the PPYC_ERR_ prefix)
ok(value) semantically marks "success"; equivalent to returning value directly
OK_TUPLE (None, None, None), the success return of validation-style APIs
is_ok(result) determines success (None or (None,None,None) or an ordinary value)
is_err(result) determines whether it is an error tuple ((PPYC_ERR_xxx, msg, hint))
PPYCResult type alias Tuple[Optional[str], Optional[str], Optional[str]]

4. Complete Error-Code Table

Import methods:

from purepycrypto import PPYC_ERR_INVALID_KEY_LEN     # import a single one directly
from purepycrypto import ALL_ERROR_CODES               # all (tuple)

4.1 General

Error code Meaning
PPYC_ERR_UNKNOWN uncategorized error
PPYC_ERR_INTERNAL internal inconsistency (should raise PPYC_ERR)
PPYC_ERR_UNSUPPORTED unsupported feature / value
PPYC_ERR_NOT_IMPLEMENTED not yet implemented

4.2 Argument Validation

Error code Meaning
PPYC_ERR_INVALID_ARG invalid argument (general)
PPYC_ERR_INVALID_TYPE invalid type (e.g. not bytes)
PPYC_ERR_INVALID_LENGTH invalid length (general)
PPYC_ERR_INVALID_HEX invalid hexadecimal format
PPYC_ERR_OUT_OF_RANGE value out of range
PPYC_ERR_MESSAGE_TOO_LONG message too long (exceeds the encoding limit)
PPYC_ERR_INPUT_TOO_LARGE input exceeds the algorithm limit

4.3 Key / nonce / IV

Error code Meaning
PPYC_ERR_INVALID_KEY invalid key (general)
PPYC_ERR_INVALID_KEY_LEN invalid key length
PPYC_ERR_INVALID_NONCE invalid nonce
PPYC_ERR_INVALID_NONCE_LEN invalid nonce length
PPYC_ERR_INVALID_IV invalid IV
PPYC_ERR_INVALID_IV_LEN invalid IV length
PPYC_ERR_INVALID_SALT invalid salt

4.4 Authentication / Decryption

Error code Meaning
PPYC_ERR_AUTH_FAILED authentication failure (AEAD tag / signature verification fails)
PPYC_ERR_DECRYPT_FAILED decryption failure
PPYC_ERR_INVALID_PADDING invalid padding (PKCS#7 etc.)
PPYC_ERR_INVALID_SIGNATURE invalid signature / verification fails
PPYC_ERR_INVALID_TAG invalid authentication tag

4.5 Encoding / Parsing

Error code Meaning
PPYC_ERR_INVALID_ENCODING invalid encoding format (DER / PEM)
PPYC_ERR_PARSE_FAILED parse failure
PPYC_ERR_INVALID_POINT invalid curve point (decoding / low order)
PPYC_ERR_INVALID_KEY_MATERIAL invalid key material

4.6 File / IO

Error code Meaning
PPYC_ERR_FILE_NOT_FOUND file not found
PPYC_ERR_IO read/write failure
PPYC_ERR_PERMISSION insufficient permission

4.7 Environment / Dependencies

Error code Meaning
PPYC_ERR_NO_MULTIPROCESS multiprocessing unavailable
PPYC_ERR_ENV runtime environment problem

4.8 Algorithm / Parameter Domain

Error code Meaning
PPYC_ERR_INVALID_PARAM invalid algorithm parameter
PPYC_ERR_INVALID_KDF_PARAM invalid KDF parameter (t/m/p/N/r/iterations/dklen)
PPYC_ERR_INVALID_RSA_BITS invalid RSA bit size
PPYC_ERR_INVALID_ALGO invalid algorithm name
PPYC_ERR_INVALID_MODE invalid mode (ECB/CBC/GCM…)
PPYC_ERR_INVALID_OPERATION invalid operation (enc/dec…)

4.9 CLI / TUI

Error code Meaning
PPYC_ERR_CLI_USAGE command-line usage error
PPYC_ERR_CLI_INPUT invalid interactive input
PPYC_ERR_EOF input stream ended (pipe / redirect)

5. Real Examples

5.1 Library Call (checking the return value)

from purepycrypto import AES, is_err, PPYC_ERR_AUTH_FAILED

aes = AES(key)
result = aes.gcm_encrypt(nonce, plaintext, aad)
if is_err(result):
    print("encryption parameter error:", result)
else:
    ct, tag = result

5.2 Command Line (automatic exit-code mapping)

$ purepycrypto hash --algo nope --text abc --hex
[✗] PPYC_ERR_INVALID_ALGO: unknown algorithm: nope
    Suggestion: available: sha256 / sha512 / blake2b
$ echo $?     # 2 (PPYC_ERR uniformly returns 2)

CLI exit code conventions:

Exit code Meaning
0 success
1 other (e.g. argparse usage error, verification FAIL)
2 PPYC_ERR (fatal error)
3 file not found
4 argument error (ValueError / TypeError)

5.3 TUI (graceful EOF handling)

$ echo "" | purepycrypto
...
  Select > 
[✗] PPYC_ERR_EOF: 输入流已结束(EOF)
    建议: 交互式 TUI 需要终端输入;脚本化请用命令行模式 purepycrypto <子命令>

6. Authoring Conventions (for contributors)

  1. Single source of error definitions: the library defines error codes and exception classes only in purepycrypto/_ppyc_error.py; all other modules use from ._ppyc_error import ... and must not invent error-code string literals.
  2. Error-code prefix enforced: err() validates the PPYC_ERR_ prefix and raises PPYC_ERR if it does not match.
  3. docstrings must have a "Returns" section: describe the normal return value, as well as the 3-tuple on error and the possible error codes.
  4. raise ValueError must not be used: for parameter validation use return err(...); for internal contradictions use raise PPYC_ERR(...).
  5. Authentication failures go through tuples: AEAD tag verification and signature verification failures → return err(PPYC_ERR_AUTH_FAILED, ...).

This manual is released together with purepycrypto. Error-code constants are in purepycrypto/_ppyc_error.py.