OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Calculate a reproducible SHA-256 digest of exact UTF-8 text

Python

Compare text artifacts without silently changing line endings or normalization.

Python code excerpt: Calculate a reproducible SHA-256 digest of exact UTF-8 text. Version 1.0.0. Read the full recipe for code, sources and recorded test scope.

Compare text artifacts without silently changing line endings or normalization. This stdin-based Python CLI processes one bounded JSON request and returns the documented JSON result. It does not execute jobs or contact external services. Inspect its limits before adapting it to an application.

Before you start

  • Python 3.12 standard library; no third-party packages. Verified with the recorded pinned runtime.
  • One UTF-8 JSON object on stdin, no command-line arguments. Maximum encoded request size is 20000 bytes.

Build and check

  1. Save the source as sha256-utf8-text-python.py.
  2. Save the example JSON below as request.json.
  3. Run python3 sha256-utf8-text-python.py < request.json.
  4. Compare the parsed JSON result with the expected output. Invalid input exits 2 with empty stdout and a generic stderr message.

Limits to understand

  • SHA-256 is not encryption, a password hash, or proof of authenticity.
  • The 20000-byte limit applies to the entire JSON input, not just the text's UTF-8 representation.
  • The program preserves characters it receives; it cannot undo normalization or newline conversion performed upstream. An existing U+FEFF character in the text is preserved, not removed.
  • Input exactly {"text":string}. Encode exact text as UTF-8 without BOM; never normalize Unicode, whitespace or newline characters.
  • Output {"sha256": lowercase hexadecimal SHA-256 digest, "utf8_bytes":integer}. Empty text is valid.
  • Document that a digest is not encryption, a password hash or proof of authenticity.
  • The complete encoded input is limited to 20000 bytes; one additional byte can be read to detect overflow.
  • This is a bounded local helper. Passing the recorded cases does not verify every input, every Python version or an external integration.

Run it

python3 sha256-utf8-text-python.py < request.json

Example input

{"text": "abc"}

Expected output

{"sha256":"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad","utf8_bytes":3}
INSPECT THE SCRIPT

Inspect, copy and run the documented checks.

This browser preview builds code locally. It does not contact an API or run the code.

Default example ready.

Python example
import hashlib
import json
import math
import sys


class InvalidInput(ValueError):
    pass


def reject_constant(_value):
    raise InvalidInput()


def finite_float(value):
    number = float(value)
    if not math.isfinite(number):
        raise InvalidInput()
    return number


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise InvalidInput()
        result[key] = value
    return result


def validate_unicode(value):
    if isinstance(value, str):
        value.encode('utf-8', errors='strict')
    elif isinstance(value, list):
        for item in value:
            validate_unicode(item)
    elif isinstance(value, dict):
        for key, item in value.items():
            validate_unicode(key)
            validate_unicode(item)


def main():
    try:
        if len(sys.argv) != 1:
            raise InvalidInput()
        raw = sys.stdin.buffer.read(20001)
        if len(raw) > 20000:
            raise InvalidInput()
        document = raw.decode('utf-8', errors='strict')
        value = json.loads(
            document,
            object_pairs_hook=unique_object,
            parse_constant=reject_constant,
            parse_float=finite_float,
        )
        validate_unicode(value)
        if not isinstance(value, dict) or set(value) != {'text'}:
            raise InvalidInput()
        if not isinstance(value['text'], str):
            raise InvalidInput()
        encoded = value['text'].encode('utf-8', errors='strict')
        result = {
            'sha256': hashlib.sha256(encoded).hexdigest(),
            'utf8_bytes': len(encoded),
        }
        output = json.dumps(result, separators=(',', ':')) + '\n'
    except Exception:
        sys.stderr.write('Invalid input.\n')
        return 2

    sys.stdout.write(output)
    return 0


if __name__ == '__main__':
    sys.exit(main())
What to verify after running
  • Run the documented example and compare the JSON result.
  • Confirm malformed requests exit 2 without copying input data into diagnostic messages.
  • 20 independent CLI cases passed on this exact source, including an unexpected-argument check.

Request or format preview

Illustrative preview. No provider response, price or balance is fetched.

Change a setting to inspect the preview.

Official sources and related profiles

    Code license: MIT. Keep the license notice with your copy.

    Example version 1.0.0 · Documentation reviewed 2026-11-15.

    20 recorded CLI cases passed in rootless Docker on the pinned Python 3.12 runtime, with 512 MiB RAM, 1 CPU, no network, and read-only source. Other runtimes and all possible inputs are not verified.