[
  {
    "path": ".coveragerc",
    "content": "[run]\nomit=*/tests/*,*/proto/*"
  },
  {
    "path": ".devcontainer/devcontainer.json",
    "content": "{\n  \"image\": \"mcr.microsoft.com/devcontainers/python:3.14\",\n  \"features\": {\n  },\n  \"mounts\": [\n    \"source=${localEnv:HOME}/.ssh,target=/home/vscode/.ssh,type=bind,consistency=cached,readonly\"\n  ]\n}\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ngithub: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]\npatreon: # Replace with a single Patreon username\nopen_collective: # Replace with a single Open Collective username\nko_fi: # Replace with a single Ko-fi username\ntidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel\ncommunity_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry\nliberapay: # Replace with a single Liberapay username\nissuehunt: # Replace with a single IssueHunt username\notechie: # Replace with a single Otechie username\nlfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry\ncustom: [\"https://www.paypal.me/eldavoo\"]\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/can-t-decrypt.md",
    "content": "---\nname: Can't decrypt\nabout: The program can't decrypt my files\ntitle: ''\nlabels: ''\nassignees: ElDavoo\n\n---\n\n**Hexdump of your key file**\nAdd the hexdump of your key file here\n\n**Hexdump of the encrypted DB\nAdd the hexdump of the first 256 bytes of your DB here.\n\n**Screenshots**\nIf applicable, add screenshots to help explain your problem.\n\n**Program output using -v and -f**\n \n\n**Additional context**\nAdd any other context about the problem here.\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "This pull requests fixes the issue # (issue number)  "
  },
  {
    "path": ".github/copilot-instructions.md",
    "content": "# WhatsApp Crypt Tools - AI Coding Agent Instructions\n\n## Project Overview\n**wa-crypt-tools** is a Python utility for decrypting and encrypting WhatsApp backup files (.crypt12, .crypt14, .crypt15 formats). It supports three cryptographic versions with different key storage mechanisms and encryption parameters.\n\n## Architecture Patterns\n\n### Factory Pattern for Version Handling\nThe codebase uses two factory classes to abstract version-specific logic:\n\n1. **KeyFactory** ([src/wa_crypt_tools/lib/key/keyfactory.py](src/wa_crypt_tools/lib/key/keyfactory.py))\n   - Handles both file-based keys and hex string keys\n   - Dispatches to Key14 or Key15 based on key format\n   - Falls back gracefully with helpful error messages\n\n2. **DatabaseFactory** ([src/wa_crypt_tools/lib/db/dbfactory.py](src/wa_crypt_tools/lib/db/dbfactory.py))\n   - Detects crypt version (12/14/15) from file headers\n   - Uses protobuf messages for crypt15 header parsing\n   - Returns version-specific Database class (Database12/14/15)\n\nEach version class inherits from base `Database` and `Key` classes, implementing version-specific encryption/decryption logic.\n\n### Protobuf Integration for Crypt15\nCrypt15 uses protobuf messages to parse backup headers:\n- Definition files in [proto/](proto/) directory (backup_prefix.proto, C14_cipher.proto, C15_IV.proto, key_type.proto)\n- Generated Python files in [src/wa_crypt_tools/proto/](src/wa_crypt_tools/proto/)\n- **Critical dependency**: Requires protobuf ≥5.28.5 (failing imports suggest version mismatch)\n\n## Command-Line Tools\nAll entry points in [src/wa_crypt_tools/](src/wa_crypt_tools/):\n\n| Tool | Purpose |\n|------|---------|\n| **wadecrypt.py** | Decrypt crypt12/14/15 files; supports streaming with buffer control |\n| **waencrypt.py** | Encrypt databases (BETA); requires reference file or complex parameters |\n| **waguess.py** | Brute-force guess encryption keys |\n| **wainfo.py** | Print metadata about encrypted/key files |\n| **wacreatekey.py** | Generate new encryption keys |\n\nEach tool:\n- Configures logging via CustomFormatter ([src/wa_crypt_tools/lib/logformat.py](src/wa_crypt_tools/lib/logformat.py))\n- Uses argparse for CLI argument parsing\n- Sets up handlers for both root logger and `wa_crypt_tools.lib` logger\n\n## Key Technical Details\n\n### Decryption Process (wadecrypt.py)\n- Uses AES GCM cipher with HMAC-SHA256 authentication\n- Supports streaming/chunked reading to handle large files (buffer_size parameter)\n- Handles three footer detection scenarios: single-file backup, multi-file backup, and split checksum\n- Tests decompression using zlib; auto-detects ZIP vs. raw formats\n- Verifies HMAC and detects corruption\n\n### Critical Constants\nSee [src/wa_crypt_tools/lib/constants.py](src/wa_crypt_tools/lib/constants.py):\n- `ZLIB_HEADERS`: Expected uncompressed data starts with `x\\x01` or `PK`\n- `HEADER_SIZE`: 384 bytes required for reliable header detection\n- `DEFAULT_DATA_OFFSET`: 122 bytes (where encrypted data begins)\n- `SUPPORTED_CIPHER_VERSION`: Only `b'\\x00\\x01'` supported\n- `SUPPORTED_KEY_VERSIONS`: Keys support versions 1-3\n\n### Logging Format\nAll tools use custom colored logging: `filename:lineno : [LEVEL] message`\n- Enable debug with `-v` flag on CLI tools\n- Levels: INFO (default), DEBUG, WARNING, ERROR, CRITICAL\n\n## Testing\n\n### Test Structure\n- [tests/test_decrypt.py](tests/test_decrypt.py): Validates decryption against known test files using SHA512 hash\n- [tests/test_encrypt.py](tests/test_encrypt.py): Tests encryption round-trips\n- [tests/test_createkey.py](tests/test_createkey.py): Key generation and parsing\n- [tests/lib/](tests/lib/): Unit tests for constants, utilities\n- Test resources in [tests/res/](tests/res/): Contains test keys and encrypted databases\n\nRun tests:\n```bash\npython -m pytest\n```\n\n### Test Data Files\n- `tests/res/encrypted_backup.key`: Crypt15 E2E key (hex format)\n- `tests/res/key`: Crypt12/14 key (binary, Java serialized)\n- `tests/res/msgstore.db.crypt{12,14,15}`: Encrypted test databases\n\n## Critical Dependencies\n\n- **pycryptodomex ≥3.20.0**: AES-GCM encryption\n- **protobuf ≥5.28.5 <6.0.0**\n- **javaobj-py3 ≥0.4.4**: Parse Java serialized key objects (crypt12/14)\n\n**Troubleshooting imports**:\n- If protobuf import fails with \"cannot import name 'builder'\": Update protobuf to ≥3.20.0\n- If no proto modules found: Download from [proto/](proto/) or run proto code generation\n\n## Conventions & Patterns\n\n1. **Logging**: Always use module-level logger: `log = logging.getLogger(__name__)`\n2. **Error handling**: Use try/except with detailed log messages; avoid silent failures\n3. **Versioning**: Pass version-specific context through factory; never check string filenames\n4. **File I/O**: Use context managers (`with` statements); handle large files with streaming\n5. **Checksum validation**: Always verify HMAC/authentication tags at end of decryption\n\n## Extending the Codebase\n\n- **Adding new crypt version**: Create `DatabaseXX.py` and `KeyXX.py` in respective lib folders; update factories\n- **Modifying decryption logic**: Changes in base `Database` class affect all versions; test all three\n- **Adding proto messages**: Update .proto files, regenerate Python code, update imports in db15.py\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "# To get started with Dependabot version updates, you'll need to specify which\n# package ecosystems to update and where the package manifests are located.\n# Please see the documentation for all configuration options:\n# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates\n\nversion: 2\nupdates:\n  - package-ecosystem: \"pip\" # See documentation for possible values\n    directory: \"/\" # Location of package manifests\n    schedule:\n      interval: \"daily\"\n  - package-ecosystem: \"github-actions\"\n    directory: \"/\"\n    schedule:\n      # Check for updates to GitHub Actions every weekday\n      interval: \"daily\"\n"
  },
  {
    "path": ".github/workflows/codeql-analysis.yml",
    "content": "# For most projects, this workflow file will not need changing; you simply need\n# to commit it to your repository.\n#\n# You may wish to alter this file to override the set of languages analyzed,\n# or to provide custom queries or build logic.\n#\n# ******** NOTE ********\n# We have attempted to detect the languages in your repository. Please check\n# the `language` matrix defined below to confirm you have the correct set of\n# supported CodeQL languages.\n#\nname: \"CodeQL\"\n\non:\n  push:\n    branches: [ '*' ]\n  pull_request:\n    # The branches below must be a subset of the branches above\n    branches: [ main ]\n  workflow_call:\n\n\njobs:\n  analyze:\n    name: Analyze\n    runs-on: ubuntu-latest\n    permissions:\n      actions: read\n      contents: read\n      security-events: write\n\n    strategy:\n      fail-fast: false\n      matrix:\n        language: [ 'python' ]\n        # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]\n        # Learn more about CodeQL language support at https://git.io/codeql-language-support\n\n    steps:\n    - name: Checkout repository\n      uses: actions/checkout@v6\n\n    # Initializes the CodeQL tools for scanning.\n    - name: Initialize CodeQL\n      uses: github/codeql-action/init@v4\n      with:\n        languages: ${{ matrix.language }}\n        # If you wish to specify custom queries, you can do so here or in a config file.\n        # By default, queries listed here will override any specified in a config file.\n        # Prefix the list here with \"+\" to use these queries and those in the config file.\n        # queries: ./path/to/local/query, your-org/your-repo/queries@main\n\n    # Autobuild attempts to build any compiled languages  (C/C++, C#, or Java).\n    # If this step fails, then you should remove it and run the build manually (see below)\n    - name: Autobuild\n      uses: github/codeql-action/autobuild@v4\n\n    # ℹ️ Command-line programs to run using the OS shell.\n    # 📚 https://git.io/JvXDl\n\n    # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines\n    #    and modify them (or add more) to build your code if your project\n    #    uses a compiled language\n\n    #- run: |\n    #   make bootstrap\n    #   make release\n\n    - name: Perform CodeQL Analysis\n      uses: github/codeql-action/analyze@v4\n"
  },
  {
    "path": ".github/workflows/lint-test-coverage.yml",
    "content": "name: \"Lint, tests, coverage\"\n\non:\n    push:\n        branches:\n        - '*'\n    pull_request:\n        branches:\n        - main\n    workflow_call:\n\n\npermissions:\n  contents: read\n\njobs:\n  job:\n\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        python-version: [\"3.10\", \"3.11\", \"3.12\", \"3.13\", \"3.14\"]\n\n    steps:\n    - uses: actions/checkout@v6\n    - name: Set up Python ${{ matrix.python-version }}\n      uses: actions/setup-python@v6\n      with:\n        python-version: ${{ matrix.python-version }}\n        cache: 'pip'\n    - name: Install dependencies\n      run: |\n        python -m pip install --upgrade pip\n        python -m pip install flake8 pytest codecov pytest-cov coveralls\n        python -m pip install -e .[test]\n    - name: Lint with flake8\n      run: |\n        # stop the build if there are Python syntax errors or undefined names\n        flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics\n        # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide\n        flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics\n    - name: Test with pytest\n      run: |\n        python -m pytest --cov\n    - name: Coveralls\n      uses: coverallsapp/github-action@v2\n      if: github.event_name != 'pull_request'\n      env:\n        COVERALLS_REPO_TOKEN: ${{ secrets.COVERALLS_REPO_TOKEN }}\n        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}"
  },
  {
    "path": ".github/workflows/pypi.yml",
    "content": "name: Upload Python Package to PyPI when a Release is Created\n\non:\n  push:\n    tags:\n      - 'v*'\n\njobs:\n  codeql:\n    uses: ./.github/workflows/codeql-analysis.yml\n  tests:\n    uses: ./.github/workflows/lint-test-coverage.yml\n  release:\n    permissions: write-all\n    needs:\n      - codeql\n      - tests\n    name: Create Release\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v6\n      - name: Create Release\n        id: create_release\n        uses: actions/create-release@v1\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n        with:\n          tag_name: ${{ github.ref }}\n          release_name: Release ${{ github.ref }}\n          draft: false\n          prerelease: false\n  pypi-publish:\n    needs: release\n    name: Publish release to PyPI\n    runs-on: ubuntu-latest\n    environment:\n      name: pypi\n      url: https://pypi.org/p/wa-crypt-tools\n    permissions:\n      id-token: write\n\n    steps:\n      - uses: actions/checkout@v6\n      - name: Set up Python\n        uses: actions/setup-python@v6\n        with:\n          python-version: \"3.x\"\n      - name: Install dependencies\n        run: |\n          python -m pip install --upgrade pip build\n          pip install -r requirements.txt\n      - name: Build package\n        run: |\n          python -m build\n      - name: Publish package distributions to PyPI\n        uses: pypa/gh-action-pypi-publish@release/v1"
  },
  {
    "path": ".gitignore",
    "content": ".idea\ntest-files\nprotoc*\n\n# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\ncover/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\n.pybuilder/\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n#   For a library or package, you might want to ignore these files since the code is\n#   intended to run in multiple environments; otherwise, check them in:\n# .python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# poetry\n#   Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.\n#   This is especially recommended for binary packages to ensure reproducibility, and is more\n#   commonly ignored for libraries.\n#   https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control\n#poetry.lock\n\n# pdm\n#   Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.\n#pdm.lock\n#   pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it\n#   in version control.\n#   https://pdm.fming.dev/#use-with-ide\n.pdm.toml\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n# pytype static type analyzer\n.pytype/\n\n# Cython debug symbols\ncython_debug/\n\n# PyCharm\n#  JetBrains specific template is maintained in a separate JetBrains.gitignore that can\n#  be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore\n#  and can be added to the global gitignore or merged into this file.  For a more nuclear\n#  option (not recommended) you can uncomment the following to ignore the entire idea folder.\n#.idea/\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Changelog\n\n## Version 0.0.9\n\n- Code refactored as a library, with lots of files, classes and methods\n- decrypt14_15 renamed to wadecrypt\n- Guessing logic moved to waguess\n- New tools introduced:\n  - wacreatekey\n  - waencrypt, for encrypting backups\n  - wainfo, for printing infos\n\n## Version 0.0.8\n\nAs I uploaded the package to PyPI, the versioning scheme changed. It was too ugly to start from version 7.0.  \n\n- Uploaded package to PyPI\n\n## Old changelogs\n---\n\nNote: this script did not use to follow a versioning policy. Versions number were written just for reference.\nThis file may not be 100% correct: The true changelog is the git history.\n\n## Version 7.0\n\n- Support for crypt12 files (only msgstore tested)\n\n## Version 6.1\n\n- The AES authentication tag is now checked.  \n  This is the beginning of a new era as everything is checked properly.\n\n## Version 6.0\n\n- The MD5 checksum at the end of the file is now checked.\n\n## Version 5.4\n\n- Support for key version 3\n\n## Version 5.3\n\n- You can now specify a custom buffer size to be used.\n\n## Version 5.2\n\n- You can write the hex encoded key (crypt15) directly instead of specifying the key file.\n\n## Version 5.1\n\n- More command line switches \n(you can choose the approach and the default offsets for guessing mode)\n\n## Version 5.0\n\n- Unified the crypt14 and the crypt15 code bases.\n\n## Version 4.1\n\n- (Crypt15) Support for other DB files, like stickers, chat_settings, wallpapers...  \nNote: stickers and wallpapers are ZIP files that will not be decompressed automatically.\n\n## Version 4.0\n- (crypt15) No more guessing offsets! The database header is now completely parsed.\n  The guessing logic has been left as a fallback behaviour.\n  The structure of the program has been changed accordingly.\n- The proto file for msgstore.db.crypt15 are now complete\n\n## Version 3.0\n- crypt15 support (in a separate script, decrypt15.py)\n- added a proto file describing the header of a msgstore.db.crypt15 file\n\n## Version 2.2\n- The Java object from the \"key\" file is now correctly deserialized, instead of just ignoring the header.\n- The SHA256 of the googleIdSalt in the \"key\" file is now actually checked.\n- Added a utility to read \"password_data.key\" and give a hashcat representation of the file.\n- Moved the changelog to a separate file.\n\n## Version 2.1\n- Refactoring\n- Added new command line options\n\n## Version 2.0 is here!\nSince the file format keeps changing, I decided to completely reimplement the script.\nIt should be much more efficient, and it should handle small variations of offset **automatically**.\n\n## Version 1.1\n- Added support for crypt14, via fixed headers.\n\n## Version 1.0\n- Initial implementation by TripCode for crypt12 files."
  },
  {
    "path": "CITATION.cff",
    "content": "# This CITATION.cff file was generated with cffinit.\n# Visit https://bit.ly/cffinit to generate yours today!\n\ncff-version: 1.2.0\ntitle: wa-crypt-tools\nmessage: >-\n  Please don't say \"et al.\", I'm the only author.\ntype: software\nauthors:\n  - given-names: Davide\n    family-names: Palma\n    email: posta@davidepalma.it\n    orcid: 'https://orcid.org/0000-0003-1931-7836'\nrepository-code: 'https://github.com/ElDavoo/wa-crypt-tools'\nabstract: 'Manage WhatsApp .crypt12, .crypt14 and .crypt15 files.'\nkeywords:\n  - WhatsApp\n  - crypt12\n  - crypt14\n  - crypt15\nlicense: GPL-3.0-only\ndate-released: '2022-06-01'"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nWe as members, contributors, and leaders pledge to make participation in our\ncommunity a harassment-free experience for everyone, regardless of age, body\nsize, visible or invisible disability, ethnicity, sex characteristics, gender\nidentity and expression, level of experience, education, socio-economic status,\nnationality, personal appearance, race, religion, or sexual identity\nand orientation.\n\nWe pledge to act and interact in ways that contribute to an open, welcoming,\ndiverse, inclusive, and healthy community.\n\n## Our Standards\n\nExamples of behavior that contributes to a positive environment for our\ncommunity include:\n\n* Demonstrating empathy and kindness toward other people\n* Being respectful of differing opinions, viewpoints, and experiences\n* Giving and gracefully accepting constructive feedback\n* Accepting responsibility and apologizing to those affected by our mistakes,\n  and learning from the experience\n* Focusing on what is best not just for us as individuals, but for the\n  overall community\n\nExamples of unacceptable behavior include:\n\n* The use of sexualized language or imagery, and sexual attention or\n  advances of any kind\n* Trolling, insulting or derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or email\n  address, without their explicit permission\n* Other conduct which could reasonably be considered inappropriate in a\n  professional setting\n\n## Enforcement Responsibilities\n\nCommunity leaders are responsible for clarifying and enforcing our standards of\nacceptable behavior and will take appropriate and fair corrective action in\nresponse to any behavior that they deem inappropriate, threatening, offensive,\nor harmful.\n\nCommunity leaders have the right and responsibility to remove, edit, or reject\ncomments, commits, code, wiki edits, issues, and other contributions that are\nnot aligned to this Code of Conduct, and will communicate reasons for moderation\ndecisions when appropriate.\n\n## Scope\n\nThis Code of Conduct applies within all community spaces, and also applies when\nan individual is officially representing the community in public spaces.\nExamples of representing our community include using an official e-mail address,\nposting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported to the community leaders responsible for enforcement at\ngithub@davidepalma.it.\nAll complaints will be reviewed and investigated promptly and fairly.\n\nAll community leaders are obligated to respect the privacy and security of the\nreporter of any incident.\n\n## Enforcement Guidelines\n\nCommunity leaders will follow these Community Impact Guidelines in determining\nthe consequences for any action they deem in violation of this Code of Conduct:\n\n### 1. Correction\n\n**Community Impact**: Use of inappropriate language or other behavior deemed\nunprofessional or unwelcome in the community.\n\n**Consequence**: A private, written warning from community leaders, providing\nclarity around the nature of the violation and an explanation of why the\nbehavior was inappropriate. A public apology may be requested.\n\n### 2. Warning\n\n**Community Impact**: A violation through a single incident or series\nof actions.\n\n**Consequence**: A warning with consequences for continued behavior. No\ninteraction with the people involved, including unsolicited interaction with\nthose enforcing the Code of Conduct, for a specified period of time. This\nincludes avoiding interactions in community spaces as well as external channels\nlike social media. Violating these terms may lead to a temporary or\npermanent ban.\n\n### 3. Temporary Ban\n\n**Community Impact**: A serious violation of community standards, including\nsustained inappropriate behavior.\n\n**Consequence**: A temporary ban from any sort of interaction or public\ncommunication with the community for a specified period of time. No public or\nprivate interaction with the people involved, including unsolicited interaction\nwith those enforcing the Code of Conduct, is allowed during this period.\nViolating these terms may lead to a permanent ban.\n\n### 4. Permanent Ban\n\n**Community Impact**: Demonstrating a pattern of violation of community\nstandards, including sustained inappropriate behavior,  harassment of an\nindividual, or aggression toward or disparagement of classes of individuals.\n\n**Consequence**: A permanent ban from any sort of public interaction within\nthe community.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage],\nversion 2.0, available at\nhttps://www.contributor-covenant.org/version/2/0/code_of_conduct.html.\n\nCommunity Impact Guidelines were inspired by [Mozilla's code of conduct\nenforcement ladder](https://github.com/mozilla/diversity).\n\n[homepage]: https://www.contributor-covenant.org\n\nFor answers to common questions about this code of conduct, see the FAQ at\nhttps://www.contributor-covenant.org/faq. Translations are available at\nhttps://www.contributor-covenant.org/translations.\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# How to contribute\n\n## Test\n\nTest the program with your own databases, both crypt 12, crypt14 and crypt15. Report any errors.\n\n## Work on issues\n\nTake a look at the open issues and work on them\n\n## Submitting changes\n\nOpen a pull request\n\n## Coding conventions\n\nThose of PyCharm\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {one line to give the program's name and a brief idea of what it does.}\n    Copyright (C) {year}  {name of author}\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    {project}  Copyright (C) {year}  {fullname}\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "[![Coverage Status](https://coveralls.io/repos/github/ElDavoo/wa-crypt-tools/badge.svg?branch=main)](https://coveralls.io/github/ElDavoo/wa-crypt-tools?branch=main)\n\n![](1000.png)\n\n# WhatsApp Crypt Tools\nDecrypt and encrypt WhatsApp and WA Business' .crypt12, .crypt14 and .crypt15 files with ease!  \nFor decryption, you NEED **the key file** or the 64-characters long key.  \nThe key file is named \"key\" if the backup is crypt14 or  \n\"encrypted_backup.key\" if the backup is crypt15 (encrypted E2E backups).  \nThose who are looking for a more complete suite for\nWhatsApp forensics, check out [whapa.](https://github.com/B16f00t/whapa)\n\n# Quick install\n\n## Cloud - Google Colab\n\nIf you do not want to install programs in your computer, you can run this program\n[in Google Colab](https://colab.research.google.com/drive/17z5UWE9dBbyvVfOG-KzRWCmTqFA3j82u?usp=sharing)\n.  \n\n## Local - Jupyter\n\nIf you are familiar with Jupyter (read \n[here](https://www.earthdatascience.org/courses/intro-to-earth-data-science/open-reproducible-science/jupyter-python/get-started-with-jupyter-notebook-for-python)\nif you're not), you can use the\n[notebook version](notebook.ipynb)\nof the program.\n\n## Local - pip\n\nYou can install this script as a package through pip. Just run:\n```bash\npython -m pip install wa-crypt-tools\n```\nfor the stable version and \n```bash\npython -m pip install git+https://github.com/ElDavoo/wa-crypt-tools\n```\nfor the development version.  \n\nYou might have to create a virtual environment to avoid conflicts with other packages.  \n\n# Quick start\n\n## Decrypt a file with wadecrypt\n```\nusage: wadecrypt [-h] [-nm] [-bs BUFFER_SIZE] [-nd] [-v] [-f] [keyfile] [encrypted] [decrypted]\n```\n\nSo, for decrypting a crypt12/14/15, we give the program the key file, the encrypted file and the name of the output file.\n\n### Example\n\n```\n$ wadecrypt encrypted_backup.key msgstore.db.crypt15 msgstore.db\nkey15.py:51     : [I] Crypt15 / Raw key loaded\nwadecrypt.py:271        : [I] Done\n```\n\n## Encrypt a file with waencrypt (BETA)\n\n```\nusage: waencrypt [-h] [-f] [-v] [--enable-features [ENABLE_FEATURES ...]] [--max-feature MAX_FEATURE]\n                 [--multi-file] [--type {12,14,15}] [--iv IV] [--reference REFERENCE] [--noparse]\n                 [--wa-version WA_VERSION] [--jid JID] [--backup-version BACKUP_VERSION] [--no-compress]\n                 [keyfile] [decrypted] [encrypted]\n```\n\nEncryption is more complex and untested: it is advised to use another encrypted file \nfrom the same account, which we will call \"reference\".  \n\n### With a reference file (only database crypt15 tested)\n```\nwaencrypt --reference msgstore.db.crypt15 encrypted_backup.key msgstore.db msgstore-new.db.crypt15\nwaencrypt.py:57         : [W] This script is in beta stage\nwaencrypt.py:89         : [I] Done!\n```\n\n### Without a reference file\n\nYou need to supply the following parameters:  \n\n1) The feature list: Only for 2019+ databases. A list of numbered boolean\n   properties related to your database. There is currently no way to infer them\n   from a database file. In the example, we will just use my backup's feature list,\n   but don't expect it to work for you.  \n2) The max feature number, which is 39 at the time of writing\n3) The version of the app that encrypted the file: Use a reasonable value,\n   like 2.24.8.6 or something.  \n4) Jid: The last 2 numbers of your phone number  \n5) Backup version: Use 1.\n\nDefaults will be used if parameters are omitted.  \n\nTo sum it up:\n```\n$ waencrypt --enable-features 5 6 7 8 9 10 11 12 13 14 15 16\n 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 39 --type 15 --wa-version 2.26.1.2 --jid 00 --backup\n-version 1 encrypted_backup.key msgstore.db msgstore-new.db.crypt15 \nwaencrypt.py:57         : [W] This script is in beta stage\nwaencrypt.py:89         : [I] Done!\n```\n\nYou can get info about a backup file with the `wainfo` tool.\n\n# Tool list\nFor usage, run the tool with `-h` option.\n1) `wacreatekey` - Create key files\n2) `wadecrypt` - Decrypt backups\n3) `waencrypt` - Encrypt backups\n4) `waguess` - Hacky way to try decrypt backups\n5) `wainfo` - Get info about a backup \n\n# FAQ\n\n## Can I decrypt a backup without a key file?\n\nNO! What would be the point of encrypting a file otherwise?  \n\n## I forgot the password / 64-letters key, can you help me?\n\nSee above.\n\n## The program doesn't decrypt my backups and says the backups are corrupted\n\nYour backups are corrupted. You can try disabling all checks with the\n`-f` flag, but expect crashes and/or unreadable output.\n\n## The program doesn't decrypt and says the key is wrong\n\nThe key is wrong. You can try disabling all checks with the\n`-f` flag, but expect crashes and/or unreadable output.\n\n## What is the best setup for decrypting my own databases?\n\n1) Enable end-to-end backups and do NOT use a password, use the 64-letters key option.\n2) Use `wacreatekey` to create a `encrypted_backup.key` file\n3) Store your key file safely and use `wadecrypt` to decrypt your backups.\n\nIn this way, you will manage your own root key - otherwise WhatsApp might change \nyour key when appropriate.  \n\n## Can I use the password to decrypt the database?\n\nNo! The password is only used to talk with the WhatsApp servers and retrieve \nthe 64-letters key.  \nIn other words, the password is used to **protect the key**, it's not used \nto encrypt the backups.  \n\n## Can I decrypt .mcrypt1 files downloaded from Google Drive?\nYes, but the code is not documented, so please at this time read the code.  \n\n\n## I really think the program is broken, that my backups are intact and that the key is right\n\nSend me the needed files on Telegram and I will take a look.\n\nIf you (understandably) have privacy concerns, open an issue and attach:\n1) Output of the program (both with and without --force)\n2) Hexdump of keyfile\n3) Hexdump of first 512 bytes of encrypted DB\n\nBut it will be more difficult to help you.  \n\n## Where do I get the key(file)?\nOn a rooted Android device, you can just copy \n`/data/data/com.whatsapp/files/key` \n(or `/data/data/com.whatsapp/files/encrypted_backup.key` if backups are crypt15).  \nIf you enabled E2E backups, and you did not use a password \n(you have a copy of the 64-digit key, for example a screenshot), \nyou can just transcribe and use it in lieu of the key file parameter.  \n**There are other ways, but it is not in the scope of this project \nto tell you.  \nIssues asking for this will be closed as invalid.**  \n\n## How can I cite this software?\nThere was no paper or thesis written about this software, but you can cite this online repository.\nPlease don't say \"et al.\" as there is (for now) only one author.\n### CITATION.cff\nSee the [CITATION.cff](CITATION.cff) file for citation information.\n### BibTeX\n```\n@misc{wa-crypt-tools,\n  author = {ElDavoo},\n  title = {WhatsApp Crypt Tools},\n  year = {2022},\n  month = {06},\n  howpublished = {\\url{https://github.com/ElDavoo/wa-crypt-tools}\n}\n```\n### BibLaTeX\n```\n@online{wa-crypt-tools,\n  author = {ElDavoo},\n  title = {WhatsApp Crypt Tools},\n  year = {2022},\n  month = {06},\n  url = {https://github.com/ElDavoo/wa-crypt-tools}\n}\n```\n\n### I will happily accept pull requests for the currently open issues. :)\n\n### Last tested version (don't expect this to be updated)\nStable: \n2.24.16.76  \nBeta: \n2.24.26.11\n\n#### Business\nStable:  \n2.24.23.78\n\n#### Protobuf automatic fix\n\nYou can install the proto optional dependencies to use `protoletariat` and fix the proto imports automatically.\n\nFirst, after cloning the repository, do an editable installation of the package (possibily in a virtual environment) with:\n\n`pip install -e .[proto]`\n\nThis will also install the optional dependencies of the package.\n\nNext, download the protobuf compiler from its repository [here](https://github.com/protocolbuffers/protobuf/releases). \nYou can move the protoc program to the `wa-crypt-tools/proto` folder where the .proto files are.\n \nReplace the protobuf classes as needed and run `protoc` to generate the python classes. \nFrom the `wa-crypt-tools/proto` directory of the project, run:\n\n`./protoc --python_out=../src/wa_crypt_tools/proto --proto_path=. *.proto`\n\nAfter generating the protobuf python classes through `protoc`, from that same directory run:\n\n`protol --in-place --python-out ..\\src\\wa_crypt_tools\\proto protoc --proto-path=. *.proto`\n\nLinux:  \n\n`PATH=\"$(pwd):$PATH\" protol --in-place --python-out ../src/wa_crypt_tools/proto protoc --proto-path=. *.proto`\n\nNow all the generated python classes should have their imports fixed.\n\n---\n\n## Donations\n\nThank you so much to each one of you!\n- **🎉🎉🎉 [githubsterer](https://github.com/githubsterer) 🎉🎉🎉** \n- **🎉🎉🎉 [courious875](https://github.com/courious875) 🎉🎉🎉**  \n- **🎉 [pscriptos](https://github.com/pscriptos) 🎉**  \n\nAnyone else that I forgot to mention!  \n---\n\n#### Credits:\n - Original implementation for crypt12: [TripCode](https://github.com/TripCode)    \n - Some help at the beginning: [DjEdu28](https://github.com/DjEdu28)  \n - Actual crypt14/15 implementation with protobuf: [ElDavoo](https://github.com/ElDavoo)  \n - Help with crypt14/15 footer: [george-lam](https://github.com/georg-lam)  \n - Pip package implementation: [Mikel12455](https://github.com/Mikel12455)  \n - [kingbtcvl](https://github.com/kingbtcvl)  \n\n Anyone else that helped!  \n\n#### Research papers that used this software\n- [Injection Attacks Against End-to-End Encrypted Applications](https://ieeexplore.ieee.org/abstract/document/10646849)\n- [Forensic Analysis of WhatsApp Disappearing Message on\nUnrooted Android Using Mobile Device Forensics\nMethodology NIST SP 800-101r1](https://catalog.lib.kyushu-u.ac.jp/opac_download_md/7172316/pp516-524.pdf)\n- [ANALISIS FORENSIK APLIKASI PENIPUAN BERBASIS ANDROID MENGGUNAKAN METODE NIST] (https://jurnal.umt.ac.id/index.php/jika/article/view/10575) (bad boys you didn't cite me :P )\n\n### Stargazers over time\n\n[![Star History Chart](https://api.star-history.com/svg?repos=ElDavoo/wa-crypt-tools&type=Date)](https://star-history.com/#ElDavoo/wa-crypt-tools&Date)\n"
  },
  {
    "path": "SECURITY.md",
    "content": "# Security Policy\n\n## Supported Versions\n\nLatest\n\n## Reporting a Vulnerability\n\nOpen an issue or contact me in my profile's email\n"
  },
  {
    "path": "git-hooks/pre-commit",
    "content": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed.\n# Called by \"git commit\" with no arguments.  The hook should\n# exit with non-zero status after issuing an appropriate message if\n# it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-commit\".\n\nif git rev-parse --verify HEAD >/dev/null 2>&1\nthen\n        against=HEAD\nelse\n        # Initial commit: diff against an empty tree object\n        against=$(git hash-object -t tree /dev/null)\nfi\n\n# If you want to allow non-ASCII filenames set this variable to true.\nallownonascii=$(git config --type=bool hooks.allownonascii)\n\n# Redirect output to stderr.\nexec 1>&2\n\n# Cross platform projects tend to avoid non-ASCII filenames; prevent\n# them from being added to the repository. We exploit the fact that the\n# printable range starts at the space character and ends with tilde.\nif [ \"$allownonascii\" != \"true\" ] &&\n        # Note that the use of brackets around a tr range is ok here, (it's\n        # even required, for portability to Solaris 10's /usr/bin/tr), since\n        # the square bracket bytes happen to fall in the designated range.\n        test $(git diff --cached --name-only --diff-filter=A -z $against |\n          LC_ALL=C tr -d '[ -~]\\0' | wc -c) != 0\nthen\n        cat <<\\EOF\nError: Attempt to add a non-ASCII file name.\n\nThis can cause problems if you want to work with people on other platforms.\n\nTo be portable it is advisable to rename the file.\n\nIf you know what you are doing you can disable this check using:\n\n  git config hooks.allownonascii true\nEOF\n        exit 1\nfi\n\n# If there are whitespace errors, print the offending file names and fail.\ngit diff-index --check --cached $against --\n# Run the tests\nexec python3 -m pytest -q"
  },
  {
    "path": "notebook.ipynb",
    "content": "{\n  \"cells\": [\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"7cXVAM_dA3AS\"\n      },\n      \"source\": [\n        \"#WhatsApp Crypt14-15 Backup Decrypter\\n\",\n        \"Decrypts WhatsApp .crypt12, .crypt14 and .crypt15 files, given the key file or the 64-characters long key.\\n\",\n        \"\\n\",\n        \"The key file is named \\\"key\\\" if the backup is crypt14 or\\n\",\n        \"\\\"encrypted_backup.key\\\" if the backup is crypt15 (encrypted E2E backups).\\n\",\n        \"The output result is either a SQLite database or a ZIP file (in case of wallpapers and stickers).\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"qPWe755MTd8M\"\n      },\n      \"source\": [\n        \"###Key takeaways\\n\",\n        \"* You need root access in most devices https://github.com/ElDavoo/WhatsApp-Crypt14-Crypt15-Decrypter#where-do-i-get-the-keyfile\\n\",\n        \"\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"zJ-qUk9E5fpm\"\n      },\n      \"source\": [\n        \"## Upload your key file and crypt files before running\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"hWpc4SKqERuO\"\n      },\n      \"source\": [\n        \"###Installation\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"t8sD3dVEt_-v\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"!python -m pip install git+https://github.com/ElDavoo/wa-crypt-tools\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"Myz44qhTR8uk\"\n      },\n      \"source\": [\n        \"###Run this after uploaded the .crypt14/15 file here\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"execution_count\": null,\n      \"metadata\": {\n        \"id\": \"CK0eJ_0YyXsL\"\n      },\n      \"outputs\": [],\n      \"source\": [\n        \"#example of a file key name \\\"key\\\", an encrypted crypt14 inside default folder and an output with the decrypted file\\n\",\n        \"\\n\",\n        \"#parameters\\n\",\n        \"#        decrypter_script     keyfile_path/key_value    encrypted_file_path   decrypter_output_file_path\\n\",\n        \"!wadecrypt ./key ./msgstore.db.crypt14 ./msgstore.db\"\n      ]\n    }\n  ],\n  \"metadata\": {\n    \"colab\": {\n      \"collapsed_sections\": [\n        \"hWpc4SKqERuO\"\n      ],\n      \"provenance\": []\n    },\n    \"kernelspec\": {\n      \"display_name\": \"Python 3\",\n      \"name\": \"python3\"\n    },\n    \"language_info\": {\n      \"name\": \"python\"\n    }\n  },\n  \"nbformat\": 4,\n  \"nbformat_minor\": 0\n}\n"
  },
  {
    "path": "proto/C14_cipher.proto",
    "content": "edition = \"2023\";\n\n// crypt14 cipher files.\nmessage C14_cipher {\n    bytes cipher_version = 1; // is usually 0001\n    bytes key_version = 2; // Is usually \"1\"\n    bytes server_salt = 3; // The 32-bytes long server salt\n    bytes google_id = 4; // The 16-bytes long google id salt\n    bytes IV = 5; // The 16-bytes long IV\n}"
  },
  {
    "path": "proto/C15_IV.proto",
    "content": "edition = \"2023\";\n\n// In crypt15 files only the IV is stored.\nmessage C15_IV {\n    bytes IV = 1; // The 16-bytes long IV\n}"
  },
  {
    "path": "proto/backup_expiry.proto",
    "content": "edition = \"2023\";\n// This describes the metadata, e.g. the version, the ph number and various features.\nmessage BackupExpiry {\n    string app_version = 1; // Whatsapp version, for example \"2.22.4.14\"\n    // optional string device_model = 2; // Device model, unused\n    string jidSuffix = 3; // The last two numbers of the user's Jid (phone number)\n    // These bools are only written if the backup is a msgstore backup.\n    int32 backup_version = 4;\n    // Booleans that indicate various features\n    bool f_5 = 5; // call_log\n    bool f_6 = 6; // labeled_jid\n    bool f_7 = 7; // message_fts\n    bool f_8 = 8; // blank_me_jid\n    bool f_9 = 9; // message_link\n    bool f_10 = 10; // message_main\n    bool f_11 = 11; // message_text\n    bool f_12 = 12; // missed_calls\n    bool f_13 = 13; // receipt_user\n    bool f_14 = 14; // message_media\n    bool f_15 = 15; // message_vcard\n    bool f_16 = 16; // message_future\n    bool f_17 = 17; // message_quoted\n    bool f_18 = 18; // message_system\n    bool f_19 = 19; // receipt_device\n    bool f_20 = 20; // message_mention\n    bool f_21 = 21; // message_revoked\n    bool f_22 = 22; // broadcast_me_jid\n    bool f_23 = 23; // message_frequent\n    bool f_24 = 24; // message_location\n    bool f_25 = 25; // participant_user\n    bool f_26 = 26; // message_thumbnail\n    bool f_27 = 27; // message_send_count\n    bool f_28 = 28; // migration_jid_store\n    bool f_29 = 29; // payment_transaction\n    bool f_30 = 30; // migration_chat_store\n    bool f_31 = 31; // quoted_order_message\n    bool f_32 = 32; // media_migration_fixer\n    bool f_33 = 33; // quoted_order_message_v2\n    bool f_34 = 34; // message_main_verification\n    bool f_35 = 35; // quoted_ui_elements_reply_message\n    bool f_36 = 36; // alter_message_ephemeral_to_message_ephemeral_remove_column\n    bool f_37 = 37; // alter_message_ephemeral_setting_to_message_ephemeral_setting_remove_column\n    // optional int32 backup_export_file_size = 38; // The size of the backup file, unused\n    bool f_39 = 39; // cleaned_db, does not show in incremental backups\n}\n"
  },
  {
    "path": "proto/backup_prefix.proto",
    "content": "edition = \"2023\";\nimport \"C14_cipher.proto\";\nimport \"C15_IV.proto\";\nimport \"key_type.proto\";\nimport \"backup_expiry.proto\";\n\n/*\nThis file describes the header you can find near the start of an encrypted backup file.\n */\nmessage BackupPrefix {\n    Key_Type key_type = 1; // 0 if traditional (crypt14), 1 if end-to-end (crypt15)\n    oneof cipher_info {\n        C14_cipher c14_cipher = 2; // If DB is crypt14\n        C15_IV c15_iv = 3; // If DB is crypt15\n    }\n    // Version that generated backup and other infos\n    BackupExpiry info = 4;\n}"
  },
  {
    "path": "proto/key_type.proto",
    "content": "edition = \"2023\";\n\n// This enum describes if the key is self-managed by WhatsApp of if it is stored in the HSM.\n// In other words, traditional = 0, end-to-end = 1\nenum Key_Type {\n    WA_PROVIDED = 0;\n    HSM_CONTROLLED = 1;\n}"
  },
  {
    "path": "pyproject.toml",
    "content": "[build-system]\nrequires = [\"setuptools\", \"setuptools-scm\"]\nbuild-backend = \"setuptools.build_meta\"\n\n[project]\nname = \"wa-crypt-tools\"\nkeywords = [\"whatsapp\", \"crypt12\", \"crypt14\", \"crypt15\"]\nversion = \"0.1.0\"\nauthors = [\n    {name = \"Davide Palma\", email = \"pypi@davidepalma.it\"},\n]\ndescription = \"Manages WhatsApp .crypt12, .crypt14 and .crypt15 files, given the key.\"\nreadme = \"README.md\"\nrequires-python = \">=3.10\"\ndependencies = [\n    \"javaobj-py3 >= 0.4.4\",\n    \"pycryptodomex >= 3.20.0\",\n    \"protobuf >= 5.28.5,< 6.0.0\"\n]\nclassifiers = [\n    \"Environment :: Console\",\n    \"Intended Audience :: End Users/Desktop\",\n    \"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)\",\n    \"Operating System :: OS Independent\",\n    \"Topic :: Security :: Cryptography\",\n    \"Topic :: Software Development :: Libraries :: Python Modules\",\n    \"Topic :: Utilities\",\n    \"Programming Language :: Python :: 3\",\n    \"Programming Language :: Python :: 3.10\",\n    \"Programming Language :: Python :: 3.11\",\n    \"Programming Language :: Python :: 3.12\",\n    \"Programming Language :: Python :: 3.13\",\n    \"Programming Language :: Python :: 3.14\",\n]\n\n[project.scripts]\nwacreatekey = \"wa_crypt_tools.wacreatekey:main\"\nwadecrypt = \"wa_crypt_tools.wadecrypt:main\"\nwaencrypt = \"wa_crypt_tools.waencrypt:main\"\nwaguess = \"wa_crypt_tools.waguess:main\"\nwainfo = \"wa_crypt_tools.wainfo:main\"\n\n[project.optional-dependencies]\nproto = [\n    \"protoletariat\"\n]"
  },
  {
    "path": "requirements.txt",
    "content": "javaobj-py3==0.4.4\npycryptodomex==3.23.0\nprotobuf==5.29.5"
  },
  {
    "path": "src/wa_crypt_tools/__init__.py",
    "content": "import logging\nl = logging.getLogger(__name__)\n\nl.addHandler(logging.NullHandler())"
  },
  {
    "path": "src/wa_crypt_tools/lib/constants.py",
    "content": "class C:\n    # These constants are only used by the guessing logic.\n    # zlib magic header is 78 01 (Low Compression).\n    # The first two bytes of the decrypted data should be those,\n    # in case of single file backup, or PK in case of multi file.\n    ZLIB_HEADERS = [\n        b'x\\x01',\n        b'PK'\n    ]\n    ZIP_HEADER = b'PK\\x03\\x04'\n    # Size of bytes to test (number chosen arbitrarily, but values less than ~310 makes test_decompression fail)\n    HEADER_SIZE = 384\n    DEFAULT_DATA_OFFSET = 122\n    DEFAULT_IV_OFFSET = 8\n\n    # Encryption constants\n    DEFAULT_APP_VERSION = \"2.23.18.12\"\n    DEFAULT_JID_SUFFIX = \"00\"\n    DEFAULT_BACKUP_VERSION = 0\n    # The Props I got from a recent backup of mine\n    DEFAULT_FEATURE_LIST = [5, 6, 7, 8, 9,\n                            10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n                            20, 21, 22, 23, 24, 25, 26, 27, 28, 29,\n                            30, 31, 32, 33, 35, 36, 37, 39]\n    # Old backups might not have knowledge of the new features (in 2022 backups the max is 37)\n    DEFAULT_MAX_FEATURE = 39\n\n    # Constants for crypt12/14 key and db\n    SUPPORTED_CIPHER_VERSION = b'\\x00\\x01'\n    SUPPORTED_KEY_VERSIONS = [b'\\x01', b'\\x02', b'\\x03']"
  },
  {
    "path": "src/wa_crypt_tools/lib/db/db.py",
    "content": "import abc\nimport logging\n\nfrom wa_crypt_tools.lib.key.key import Key\nfrom wa_crypt_tools.lib.props import Props\n\nlog = logging.getLogger(__name__)\n\n\nclass Database(abc.ABC):\n    \"\"\"\n    An abstract class that represents a database.\n    \"\"\"\n    iv: bytes\n\n    @abc.abstractmethod\n    def __str__(self):\n        pass\n\n    @abc.abstractmethod\n    def decrypt(self, key: Key, encrypted: bytes) -> bytes:\n        pass\n\n    @abc.abstractmethod\n    def encrypt(self, key: Key, props: Props, decrypted: bytes) -> bytes:\n        pass\n\n    @abc.abstractmethod\n    def get_iv(self) -> bytes:\n        return self.iv\n"
  },
  {
    "path": "src/wa_crypt_tools/lib/db/db12.py",
    "content": "from hashlib import md5\nfrom os import urandom\nfrom pathlib import Path\nfrom re import findall\n\nfrom Cryptodome.Cipher import AES\n\nimport logging\n\nfrom wa_crypt_tools.lib.constants import C\nfrom wa_crypt_tools.lib.db.db import Database\nfrom wa_crypt_tools.lib.key.key14 import Key14\nfrom wa_crypt_tools.lib.props import Props\n\nlog = logging.getLogger(__name__)\n\n\nclass Database12(Database):\n    \"\"\"\n    Implementation of a crypt12 database.\n    \"\"\"\n\n    def __init__(self, key: Key14 = None, encrypted=None,\n                 cipher_version: bytes = None, key_version: bytes = None, serversalt: bytes = None,\n                 googleid: bytes = None, iv: bytes = None):\n        \"\"\"Checks if the file is a Crypt12 file.\n        Returns the cipher if it is, None otherwise.\"\"\"\n\n        \"\"\"\n        The crypt12 file format is similar to the crypt14 file format.\n        It is a \"raw\" header, which means it's not a protobuf message,\n        nor a serialized java object.\n        Structure:\n        Cipher version (2 bytes)\n        Key version (1 byte)\n        Server salt (32 bytes)\n        Google ID (16 bytes)\n        IV (16 bytes)\n        ( so we finally understood why the IV is at offset 51 ... )\n        \"\"\"\n        self.file_hash = md5()\n        if encrypted and key:\n            self.cipher_version = encrypted.read(2)\n            if self.cipher_version != key.get_cipher_version():\n                log.error(\"Cipher version mismatch: {} != {}\".format(self.cipher_version, key.get_cipher_version()))\n                raise ValueError\n            self.file_hash.update(self.cipher_version)\n\n            self.key_version = encrypted.read(1)\n            if self.key_version != key.get_key_version():\n                log.error(\"Key version mismatch: {} != {}\".format(self.key_version, key.get_key_version()))\n                raise ValueError\n            self.file_hash.update(self.key_version)\n\n            self.serversalt = encrypted.read(32)\n            if self.serversalt != key.get_serversalt():\n                log.error(\"Server salt mismatch: {} != {}\".format(self.serversalt, key.get_serversalt()))\n                raise ValueError\n            self.file_hash.update(self.serversalt)\n\n            self.googleid = encrypted.read(16)\n            if self.googleid != key.get_googleid():\n                log.error(\"Google ID mismatch: {} != {}\".format(self.googleid, key.get_googleid()))\n            self.file_hash.update(self.googleid)\n\n            self.iv = encrypted.read(16)\n            self.file_hash.update(self.iv)\n        elif encrypted:\n            self.cipher_version = encrypted.read(2)\n            # if test_bytes != key.get_cipher_version():\n            #    quit_12()\n            self.file_hash.update(self.cipher_version)\n\n            self.key_version = encrypted.read(1)\n            # if test_bytes != key.get_key_version():\n            #    quit_12()\n            self.file_hash.update(self.key_version)\n\n            self.serversalt = encrypted.read(32)\n            # if test_bytes != key.get_serversalt():\n            #    quit_12()\n            self.file_hash.update(self.serversalt)\n\n            self.googleid = encrypted.read(16)\n            # if test_bytes != key.get_googleid():\n            #    quit_12()\n            self.file_hash.update(self.googleid)\n\n            self.iv = encrypted.read(16)\n            self.file_hash.update(self.iv)\n        elif key:\n            self.cipher_version = key.get_cipher_version()\n            self.file_hash.update(self.cipher_version)\n            self.key_version = key.get_key_version()\n            self.file_hash.update(self.key_version)\n            self.serversalt = key.get_serversalt()\n            self.file_hash.update(self.serversalt)\n            self.googleid = key.get_googleid()\n            self.file_hash.update(self.googleid)\n            if iv:\n                self.iv = iv\n            else:\n                self.iv = urandom(16)\n            self.file_hash.update(self.iv)\n        else:\n            if cipher_version:\n                if cipher_version == C.SUPPORTED_CIPHER_VERSION:\n                    self.cipher_version = cipher_version\n                    self.file_hash.update(self.cipher_version)\n                else:\n                    log.error(\"Unsupported cipher version provided!\")\n                    raise ValueError\n            else:\n                self.cipher_version = C.SUPPORTED_CIPHER_VERSION\n                self.file_hash.update(self.cipher_version)\n\n            if key_version:\n                if key_version in C.SUPPORTED_KEY_VERSIONS:\n                    self.key_version = key_version\n                    self.file_hash.update(self.key_version)\n                else:\n                    log.error(\"Unsupported key version provided!\")\n            else:\n                self.key_version = C.SUPPORTED_KEY_VERSIONS[-1]\n                self.file_hash.update(self.key_version)\n\n            if serversalt:\n                self.serversalt = serversalt\n            else:\n                self.serversalt = urandom(32)\n            self.file_hash.update(self.serversalt)\n\n            if googleid:\n                self.googleid = googleid\n            else:\n                self.googleid = urandom(16)\n            self.file_hash.update(self.googleid)\n\n            if iv:\n                self.iv = iv\n            else:\n                self.iv = urandom(16)\n            self.file_hash.update(self.iv)\n\n    def __str__(self):\n        return f\"\"\"cipher_version: {self.cipher_version}\n                    key_version: {self.key_version}\n                    serversalt: {self.serversalt}\n                    googleid: {self.googleid}\n                    iv: {self.iv}\"\"\"\n\n    def decrypt(self, key: Key14, encrypted: bytes) -> bytes:\n        \"\"\"Decrypts the database using the provided key\"\"\"\n        userjid = encrypted[-4:]\n        # check the userjid\n        crypt12_footer = str(userjid)\n        jid = findall(r\"(?:-|\\d)(?:-|\\d)(\\d\\d)\", crypt12_footer)\n        if len(jid) != 1:\n            log.error(\"The phone number end is not 2 characters long\")\n        else:\n            log.debug(\"Your phone number ends with {}\".format(jid[0]))\n        checksum = encrypted[-20:-4]\n        authentication_tag = encrypted[-36:-20]\n        encrypted_data = encrypted[:-36]\n        is_multifile_backup = False\n\n        self.file_hash.update(encrypted_data)\n        self.file_hash.update(authentication_tag)\n\n        if self.file_hash.digest() != checksum:\n            # We are probably in a multifile backup, which does not have a checksum.\n            # TODO do crypt12 multifiles actually exist?\n            is_multifile_backup = True\n        else:\n            log.debug(\"Checksum OK ({}). Decrypting...\".format(self.file_hash.hexdigest()))\n\n        cipher = AES.new(key.get(), AES.MODE_GCM, self.iv)\n        try:\n            output_decrypted: bytes = cipher.decrypt(encrypted_data)\n        except ValueError as e:\n            log.fatal(\"Decryption failed: {}.\"\n                      \"\\n    This probably means your backup is corrupted.\".format(e))\n            raise e\n\n        # Verify the authentication tag\n        try:\n            if is_multifile_backup:\n                # In multifile backups, there is no checksum.\n                # This means, the last 16 bytes of the files are not the checksum,\n                # despite being called \"checksum\", but are the authentication tag.\n                # Same way, \"authentication tag\" is not the tag, but the last\n                # 16 bytes of the encrypted file.\n                output_decrypted += cipher.decrypt(authentication_tag)\n                cipher.verify(checksum)\n            else:\n                cipher.verify(authentication_tag)\n        except ValueError as e:\n            log.error(\"Authentication tag mismatch: {}.\"\n                      \"\\n    This probably means your backup is corrupted.\".format(e))\n\n        return output_decrypted\n\n    def encrypt(self, key: Key14, props: Props, decrypted: bytes) -> bytes:\n        file_hash = md5()\n        out = b\"\"\n        out += self.cipher_version\n        out += self.key_version\n        out += self.serversalt\n        out += self.googleid\n        out += self.iv\n        cipher = AES.new(key.get(), AES.MODE_GCM, self.iv)\n        encrypted = cipher.encrypt(decrypted)\n        out += encrypted\n        out += cipher.digest()\n        file_hash.update(out)\n        out += file_hash.digest()\n        jid = props.get_jid()\n        if len(jid) != 2:\n            log.error(\"The phone number end is not 2 characters long\")\n        out += \"--{}\".format(jid).encode()\n        return out\n\n    def get_iv(self) -> bytes:\n        return self.iv\n"
  },
  {
    "path": "src/wa_crypt_tools/lib/db/db14.py",
    "content": "import logging\nfrom hashlib import md5\nfrom os import urandom\nfrom re import findall\n\nfrom Cryptodome.Cipher import AES\nfrom google.protobuf.message import DecodeError\n\nfrom wa_crypt_tools.lib.db.db import Database\nfrom wa_crypt_tools.lib.key.key import Key\nfrom wa_crypt_tools.lib.key.key14 import Key14\nfrom wa_crypt_tools.lib.props import Props\n\nl = logging.getLogger(__name__)\n\n\nclass Database14(Database):\n\n    def __init__(self, key: Key14 = None, encrypted=None, file_hash=None,\n                 cipher_version: bytes = None, key_version: bytes = None, serversalt: bytes = None,\n                 googleid: bytes = None, iv: bytes = None,\n                 props: Props = None):\n        self.props = props\n        if encrypted and file_hash:\n            try:\n                from wa_crypt_tools.proto import backup_prefix_pb2 as prefix\n                from wa_crypt_tools.proto import key_type_pb2 as key_type\n            except ImportError as e:\n                l.error(\"Could not import the proto classes: {}\".format(e))\n                if str(e).startswith(\"cannot import name 'builder' from 'google.protobuf.internal'\"):\n                    l.error(\"You need to upgrade the protobuf library to at least 3.20.0.\\n\"\n                            \"    python -m pip install --upgrade protobuf\")\n                elif str(e).startswith(\"no module named\"):\n                    l.error(\"Please download them and put them in the \\\"proto\\\" sub folder.\")\n                raise e\n            except AttributeError as e:\n                l.error(\"Could not import the proto classes: {}\\n    \".format(e) +\n                        \"Your protobuf library is probably too old.\\n    \"\n                        \"Please upgrade to at least version 3.20.0 , by running:\\n    \"\n                        \"python -m pip install --upgrade protobuf\")\n                raise e\n\n            self.header = prefix.BackupPrefix()\n\n            l.debug(\"Parsing database header...\")\n\n            try:\n\n                # The first byte is the size of the upcoming protobuf message\n                protobuf_size = encrypted.read(1)\n                file_hash.update(protobuf_size)\n                protobuf_size = int.from_bytes(protobuf_size, byteorder='big')\n\n                # A 0x01 as a second byte indicates the presence of the feature table in the protobuf.\n                # It is optional and present only in msgstore database, although\n                # I found some old msgstore backups without it, so it is optional.\n                msgstore_features_flag = encrypted.peek(1)[0]\n                if msgstore_features_flag != 1:\n                    msgstore_features_flag = 0\n                else:\n                    file_hash.update(encrypted.read(1))\n                if not msgstore_features_flag:\n                    l.debug(\"No feature table found (not a msgstore DB or very old)\")\n                self.__msgstore_features_flag = msgstore_features_flag\n                try:\n\n                    protobuf_raw = encrypted.read(protobuf_size)\n                    file_hash.update(protobuf_raw)\n\n                    if self.header.ParseFromString(protobuf_raw) != protobuf_size:\n                        l.error(\"Protobuf message not fully read. Please report a bug.\")\n                    else:\n\n                        # Checking and printing WA version and phone number\n                        self.__version = findall(r\"\\d(?:\\.\\d{1,3}){3}\", self.header.info.app_version)\n                        if len(self.__version) != 1:\n                            l.error('WhatsApp version not found')\n                        else:\n                            l.debug(\"WhatsApp version: {}\".format(self.__version[0]))\n                        if len(self.header.info.jidSuffix) != 2:\n                            l.error(\"The phone number end is not 2 characters long\")\n                        l.debug(\"Your phone number ends with {}\".format(self.header.info.jidSuffix))\n\n                        if len(self.header.c15_iv.IV) != 0:\n                            # DB Header is crypt15\n                            # if type(key) is not Key15:\n                            #    l.error(\"You are using a crypt14 key file with a crypt15 backup.\")\n                            raise ValueError(\"Crypt15 file in crypt14 constructor!\")\n\n                        elif len(self.header.c14_cipher.IV) != 0:\n\n                            # DB Header is crypt14\n                            # if type(key) is not Key14:\n                            #    l.fatal(\"You are using a crypt15 key file with a crypt14 backup.\")\n\n                            # if key.cipher_version != p.c14_cipher.version.cipher_version:\n                            #    l.error(\"Cipher version mismatch: {} != {}\"\n                            #    .format(key.cipher_version, p.c14_cipher.cipher_version))\n\n                            # Fix bytes to string encoding\n                            # key.key_version = (key.key_version[0] + 48).to_bytes(1, byteorder='big')\n                            # if key.key_version != p.c14_cipher.key_version:\n                            #     if key.key_version > p.c14_cipher.key_version:\n                            #         l.error(\"Key version mismatch: {} != {} .\\n    \"\n                            #             .format(key.key_version, p.c14_cipher.key_version) +\n                            #             \"Your backup is too old for this key file.\\n    \" +\n                            #             \"Please try using a newer backup.\")\n                            #     elif key.key_version < p.c14_cipher.key_version:\n                            #         l.error(\"Key version mismatch: {} != {} .\\n    \"\n                            #             .format(key.key_version, p.c14_cipher.key_version) +\n                            #             \"Your backup is too new for this key file.\\n    \" +\n                            #             \"Please try using an older backup, or getting the new key.\")\n                            #     else:\n                            #         l.error(\"Key version mismatch: {} != {} (?)\"\n                            #             .format(key.key_version, p.c14_cipher.key_version))\n                            # if key.get_serversalt() != p.c14_cipher.server_salt:\n                            #     l.error(\"Server salt mismatch: {} != {}\".format(key.get_serversalt(), p.c14_cipher.server_salt))\n                            # if key.get_googleid() != p.c14_cipher.google_id:\n                            #     l.error(\"Google ID mismatch: {} != {}\".format(key.get_googleid(), p.c14_cipher.google_id))\n                            if len(self.header.c14_cipher.IV) != 16:\n                                l.error(\"IV is not 16 bytes long but is {} bytes long\".format(\n                                    len(self.header.c14_cipher.IV)))\n                            self.__iv = self.header.c14_cipher.IV\n\n                        else:\n                            l.error(\"Could not parse the IV from the protobuf message. Please report a bug.\")\n                            raise ValueError\n\n\n                except DecodeError as e:\n\n                    print(e)\n\n            except OSError as e:\n                l.fatal(\"Reading database header failed: {}\".format(e))\n        else:\n            if iv:\n                self.__iv = iv\n            else:\n                self.__iv = urandom(16)\n\n\n    def encrypt(self, key: Key, props: Props, decrypted: bytes) -> bytes:\n        \"\"\"Encrypts the database using the provided key\"\"\"\n        from wa_crypt_tools.proto import C14_cipher_pb2 as C14_cipher\n        from wa_crypt_tools.proto import key_type_pb2 as key_type\n\n        cipher = C14_cipher.C14_cipher()\n        # TODO which ones take priority? Key or self values?\n        cipher.cipher_version = key.get_cipher_version()\n        #FIXME\n        cipher.key_version = \"2\".encode()\n        cipher.server_salt = key.get_serversalt()\n        cipher.google_id = key.get_googleid()\n        cipher.IV = self.__iv\n        from wa_crypt_tools.proto import backup_prefix_pb2 as prefix\n        from wa_crypt_tools.proto import key_type_pb2 as key_type\n        prefix = prefix.BackupPrefix()\n        prefix.key_type = 0\n        prefix.c14_cipher.CopyFrom(cipher)\n\n        prefix.info.CopyFrom(props.get_proto())\n        prefix = prefix.SerializeToString()\n        out = b''\n        file_hash = md5()\n        out += len(prefix).to_bytes(1, byteorder='big')\n        file_hash.update(out)\n        if len(props.get_features()) > 0:\n            out += b'\\x01'\n            file_hash.update(b'\\x01')\n        out += prefix\n        file_hash.update(prefix)\n        cipher = AES.new(key.get(), AES.MODE_GCM, self.__iv)\n        encrypted_data, authentication_tag = cipher.encrypt_and_digest(decrypted)\n        out += encrypted_data\n        file_hash.update(encrypted_data)\n        out += authentication_tag\n        file_hash.update(authentication_tag)\n        out += file_hash.digest()\n        return out\n\n\n    def __str__(self):\n        return f\"\"\"cipher_version: {self.cipher_version}\n    key_version: {self.key_version}\n    serversalt: {self.serversalt}\n    googleid: {self.googleid}\n    iv: {self.iv}\"\"\"\n\n\n    def get_iv(self) -> bytes:\n        return self.__iv\n\n\n    def decrypt(self, key: Key14, encrypted: bytes) -> bytes:\n        \"\"\"Decrypts the database using the provided key\"\"\"\n        checksum = encrypted[-16:]\n        authentication_tag = encrypted[-32:-16]\n        encrypted_data = encrypted[:-32]\n        is_multifile_backup = False\n\n        self.file_hash.update(encrypted_data)\n        self.file_hash.update(authentication_tag)\n\n        if self.file_hash.digest() != checksum:\n            # We are probably in a multifile backup, which does not have a checksum.\n            is_multifile_backup = True\n        else:\n            l.debug(\"Checksum OK ({}). Decrypting...\".format(self.file_hash.hexdigest()))\n\n        cipher = AES.new(key.get(), AES.MODE_GCM, self.__iv)\n        try:\n            output_decrypted: bytes = cipher.decrypt(encrypted_data)\n        except ValueError as e:\n            l.fatal(\"Decryption failed: {}.\"\n                    \"\\n    This probably means your backup is corrupted.\".format(e))\n            raise e\n\n        # Verify the authentication tag\n        try:\n            if is_multifile_backup:\n                # In multifile backups, there is no checksum.\n                # This means, the last 16 bytes of the files are not the checksum,\n                # despite being called \"checksum\", but are the authentication tag.\n                # Same way, \"authentication tag\" is not the tag, but the last\n                # 16 bytes of the encrypted file.\n                output_decrypted += cipher.decrypt(authentication_tag)\n                cipher.verify(checksum)\n            else:\n                cipher.verify(authentication_tag)\n        except ValueError as e:\n            l.error(\"Authentication tag mismatch: {}.\"\n                    \"\\n    This probably means your backup is corrupted.\".format(e))\n\n        return output_decrypted\n"
  },
  {
    "path": "src/wa_crypt_tools/lib/db/db15.py",
    "content": "import logging\nfrom hashlib import md5\nfrom os import urandom\nfrom re import findall\n\nfrom Cryptodome.Cipher import AES\nfrom google.protobuf.message import DecodeError\n\nfrom wa_crypt_tools.lib.props import Props\n\nlog = logging.getLogger(__name__)\n\nfrom wa_crypt_tools.lib.db.db import Database\nfrom wa_crypt_tools.lib.key.key15 import Key15\n\n\nclass Database15(Database):\n    def __str__(self):\n        return \"Database15\"\n        # todo\n\n    def __init__(self, *, key: Key15 = None, encrypted=None, iv: bytes = None\n                 , props: Props = None):\n        self.file_hash = md5()\n        # just store it for now\n        self.props = props\n        if encrypted:\n            try:\n                from wa_crypt_tools.proto import backup_prefix_pb2 as prefix\n                from wa_crypt_tools.proto import key_type_pb2 as key_type\n            except ImportError as e:\n                log.error(\"Could not import the proto classes: {}\".format(e))\n                if str(e).startswith(\"cannot import name 'builder' from 'google.protobuf.internal'\"):\n                    log.error(\"You need to upgrade the protobuf library to at least 3.20.0.\\n\"\n                              \"    python -m pip install --upgrade protobuf\")\n                elif str(e).startswith(\"no module named\"):\n                    log.error(\"Please download them and put them in the \\\"proto\\\" sub folder.\")\n                raise e\n            except AttributeError as e:\n                log.error(\"Could not import the proto classes: {}\\n    \".format(e) +\n                          \"Your protobuf library is probably too old.\\n    \"\n                          \"Please upgrade to at least version 3.20.0 , by running:\\n    \"\n                          \"python -m pip install --upgrade protobuf\")\n                raise e\n\n            self.header = prefix.BackupPrefix()\n\n            log.debug(\"Parsing database header...\")\n\n            try:\n\n                # The first byte is the size of the upcoming protobuf message\n                protobuf_size = encrypted.read(1)\n                self.file_hash.update(protobuf_size)\n                protobuf_size = int.from_bytes(protobuf_size, byteorder='big')\n\n                # A 0x01 as a second byte indicates the presence of the feature table in the protobuf.\n                # It is optional and present only in msgstore database, although\n                # I found some old msgstore backups without it, so it is optional.\n                msgstore_features_flag = encrypted.peek(1)[0]\n                if msgstore_features_flag != 1:\n                    msgstore_features_flag = 0\n                else:\n                    self.file_hash.update(encrypted.read(1))\n                if not msgstore_features_flag:\n                    log.debug(\"No feature table found (not a msgstore DB or very old)\")\n\n                try:\n\n                    protobuf_raw = encrypted.read(protobuf_size)\n                    self.file_hash.update(protobuf_raw)\n\n                    if self.header.ParseFromString(protobuf_raw) != protobuf_size:\n                        log.error(\"Protobuf message not fully read. Please report a bug.\")\n                    else:\n\n                        # Checking and printing WA version and phone number\n                        version = findall(r\"\\d(?:\\.\\d{1,3}){3}\", self.header.info.app_version)\n                        if len(version) != 1:\n                            log.error('WhatsApp version not found')\n                        else:\n                            log.debug(\"WhatsApp version: {}\".format(version[0]))\n                        if len(self.header.info.jidSuffix) != 2:\n                            log.error(\"The phone number end is not 2 characters long\")\n                        log.debug(\"Your phone number ends with {}\".format(self.header.info.jidSuffix))\n\n                        if len(self.header.c15_iv.IV) != 0:\n                            # DB Header is crypt15\n                            # if type(key) is not Key15:\n                            #    l.error(\"You are using a crypt14 key file with a crypt15 backup.\")\n                            if len(self.header.c15_iv.IV) != 16:\n                                log.error(\n                                    \"IV is not 16 bytes long but is {} bytes long\".format(len(self.header.c15_iv.IV)))\n                            iv = self.header.c15_iv.IV\n\n                        elif len(self.header.c14_cipher.IV) != 0:\n                            raise ValueError(\"Crypt14 file in crypt15 constructor!\")\n                        else:\n                            log.error(\"Could not parse the IV from the protobuf message. Please report a bug.\")\n                            raise ValueError\n\n                except DecodeError as e:\n\n                    log.error(\"Could not parse the protobuf message: {}\".format(e))\n                    raise e\n\n            except OSError as e:\n                log.fatal(\"Reading database header failed: {}\".format(e))\n                raise e\n        else:\n            if iv:\n                if len(iv) != 16:\n                    log.error(\"IV is not 16 bytes long but is {} bytes long\".format(len(iv)))\n                self.iv = iv\n            else:\n                self.iv = urandom(16)\n\n    def decrypt(self, key: Key15, encrypted: bytes) -> bytes:\n        \"\"\"Decrypts the database using the provided key\"\"\"\n        checksum = encrypted[-16:]\n        authentication_tag = encrypted[-32:-16]\n        encrypted_data = encrypted[:-32]\n        is_multifile_backup = False\n\n        self.file_hash.update(encrypted_data)\n        self.file_hash.update(authentication_tag)\n\n        if self.file_hash.digest() != checksum:\n            # We are probably in a multifile backup, which does not have a checksum.\n            is_multifile_backup = True\n        else:\n            log.debug(\"Checksum OK ({}). Decrypting...\".format(self.file_hash.hexdigest()))\n\n        cipher = AES.new(key.get(), AES.MODE_GCM, self.iv)\n        try:\n            output_decrypted: bytes = cipher.decrypt(encrypted_data)\n        except ValueError as e:\n            log.fatal(\"Decryption failed: {}.\"\n                      \"\\n    This probably means your backup is corrupted.\".format(e))\n            raise e\n\n        # Verify the authentication tag\n        try:\n            if is_multifile_backup:\n                # In multifile backups, there is no checksum.\n                # This means, the last 16 bytes of the files are not the checksum,\n                # despite being called \"checksum\", but are the authentication tag.\n                # Same way, \"authentication tag\" is not the tag, but the last\n                # 16 bytes of the encrypted file.\n                output_decrypted += cipher.decrypt(authentication_tag)\n                cipher.verify(checksum)\n            else:\n                cipher.verify(authentication_tag)\n        except ValueError as e:\n            log.error(\"Authentication tag mismatch: {}.\"\n                      \"\\n    This probably means your backup is corrupted.\".format(e))\n\n        return output_decrypted\n\n    def encrypt(self, key: Key15, props: Props, decrypted: bytes) -> bytes:\n        \"\"\"Encrypts the database using the provided key\"\"\"\n        from wa_crypt_tools.proto import C15_IV_pb2 as C15_IV\n        cipher = C15_IV.C15_IV()\n        cipher.IV = self.iv\n        from wa_crypt_tools.proto import backup_prefix_pb2 as prefix\n        from wa_crypt_tools.proto import key_type_pb2 as key_type\n        prefix = prefix.BackupPrefix()\n        prefix.key_type = key_type.Key_Type.HSM_CONTROLLED\n        prefix.c15_iv.CopyFrom(cipher)\n\n        prefix.info.CopyFrom(props.get_proto())\n        prefix = prefix.SerializeToString()\n        out = b''\n        file_hash = md5()\n        out += len(prefix).to_bytes(1, byteorder='big')\n        file_hash.update(out)\n        out += b'\\x01'\n        file_hash.update(b'\\x01')\n        out += prefix\n        file_hash.update(prefix)\n        cipher = AES.new(key.get(), AES.MODE_GCM, self.iv)\n        encrypted_data, authentication_tag = cipher.encrypt_and_digest(decrypted)\n        out += encrypted_data\n        file_hash.update(encrypted_data)\n        out += authentication_tag\n        file_hash.update(authentication_tag)\n        out += file_hash.digest()\n        return out\n\n    def get_iv(self) -> bytes:\n        return self.iv\n"
  },
  {
    "path": "src/wa_crypt_tools/lib/db/dbfactory.py",
    "content": "import logging\n\nfrom google.protobuf.message import DecodeError\n\nfrom wa_crypt_tools.lib.constants import C\nfrom wa_crypt_tools.lib.db.db12 import Database12\nfrom wa_crypt_tools.lib.db.db14 import Database14\nfrom wa_crypt_tools.lib.db.db15 import Database15\nfrom wa_crypt_tools.lib.props import Props\nfrom wa_crypt_tools.lib.utils import header_info\n\nlog = logging.getLogger(__name__)\n\nfrom hashlib import md5\nfrom re import findall\n\n\nclass DatabaseFactory:\n    @staticmethod\n    def from_file(encrypted):\n        try:\n            from wa_crypt_tools.proto import backup_prefix_pb2 as prefix\n            from wa_crypt_tools.proto import key_type_pb2 as key_type\n        except ImportError as e:\n            log.error(\"Could not import the proto classes: {}\".format(e))\n            if str(e).startswith(\"cannot import name 'builder' from 'google.protobuf.internal'\"):\n                log.error(\"You need to upgrade the protobuf library to at least 3.20.0.\\n\"\n                          \"    python -m pip install --upgrade protobuf\")\n            elif str(e).startswith(\"no module named\"):\n                log.error(\"Please download them and put them in the \\\"proto\\\" sub folder.\")\n            raise e\n        except AttributeError as e:\n            log.error(\"Could not import the proto classes: {}\\n    \".format(e) +\n                      \"Your protobuf library is probably too old.\\n    \"\n                      \"Please upgrade to at least version 3.20.0 , by running:\\n    \"\n                      \"python -m pip install --upgrade protobuf\")\n            raise e\n\n        header = prefix.BackupPrefix()\n\n        log.debug(\"Parsing database header...\")\n\n        try:\n            file_hash = md5()\n            # The first byte is the size of the upcoming protobuf message\n            protobuf_size = encrypted.read(1)\n            file_hash.update(protobuf_size)\n            protobuf_size = int.from_bytes(protobuf_size, byteorder='big')\n\n            # A 0x01 as a second byte indicates the presence of the feature table in the protobuf.\n            # It is optional and present only in msgstore database, although\n            # I found some old msgstore backups without it, so it is optional.\n            msgstore_features_flag = encrypted.peek(1)[0]\n            if msgstore_features_flag != 1:\n                msgstore_features_flag = 0\n            else:\n                file_hash.update(encrypted.read(1))\n            if not msgstore_features_flag:\n                log.debug(\"No feature table found (not a msgstore DB or very old)\")\n\n            try:\n\n                protobuf_raw = encrypted.read(protobuf_size)\n                file_hash.update(protobuf_raw)\n\n                if header.ParseFromString(protobuf_raw) != protobuf_size:\n                    log.error(\"Protobuf message not fully read. Please report a bug.\")\n                else:\n\n                    # Checking and printing WA version and phone number\n                    version = findall(r\"\\d(?:\\.\\d{1,3}){3}\", header.info.app_version)\n                    if len(version) != 1:\n                        log.error('WhatsApp version not found')\n                    else:\n                        log.debug(\"WhatsApp version: {}\".format(version[0]))\n                    if len(header.info.jidSuffix) != 2:\n                        log.error(\"The phone number end is not 2 characters long\")\n                    log.debug(\"Your phone number ends with {}\".format(header.info.jidSuffix))\n\n                    if len(header.c15_iv.IV) != 0:\n                        # DB Header is crypt15\n                        # if type(key) is not Key15:\n                        #    l.error(\"You are using a crypt14 key file with a crypt15 backup.\")\n                        if len(header.c15_iv.IV) != 16:\n                            log.error(\"IV is not 16 bytes long but is {} bytes long\".format(len(header.c15_iv.IV)))\n                        iv = header.c15_iv.IV\n\n                    elif len(header.c14_cipher.IV) != 0:\n\n                        # DB Header is crypt14\n                        # if type(key) is not Key14:\n                        #    l.fatal(\"You are using a crypt15 key file with a crypt14 backup.\")\n\n                        # if key.cipher_version != p.c14_cipher.version.cipher_version:\n                        #    l.error(\"Cipher version mismatch: {} != {}\"\n                        #    .format(key.cipher_version, p.c14_cipher.cipher_version))\n\n                        # Fix bytes to string encoding key.key_version = (key.key_version[0] + 48).to_bytes(1,\n                        # byteorder='big') if key.key_version != p.c14_cipher.key_version: if key.key_version >\n                        # p.c14_cipher.key_version: l.error(\"Key version mismatch: {} != {} .\\n    \" .format(\n                        # key.key_version, p.c14_cipher.key_version) + \"Your backup is too old for this key file.\\n\n                        # \" + \"Please try using a newer backup.\") elif key.key_version < p.c14_cipher.key_version:\n                        # l.error(\"Key version mismatch: {} != {} .\\n    \" .format(key.key_version,\n                        # p.c14_cipher.key_version) + \"Your backup is too new for this key file.\\n    \" + \"Please try\n                        # using an older backup, or getting the new key.\") else: l.error(\"Key version mismatch: {} !=\n                        # {} (?)\" .format(key.key_version, p.c14_cipher.key_version)) if key.get_serversalt() !=\n                        # p.c14_cipher.server_salt: l.error(\"Server salt mismatch: {} != {}\".format(\n                        # key.get_serversalt(), p.c14_cipher.server_salt)) if key.get_googleid() !=\n                        # p.c14_cipher.google_id: l.error(\"Google ID mismatch: {} != {}\".format(key.get_googleid(),\n                        # p.c14_cipher.google_id))\n                        if len(header.c14_cipher.IV) != 16:\n                            log.error(\n                                \"IV is not 16 bytes long but is {} bytes long\".format(len(header.c14_cipher.IV)))\n                        iv = header.c14_cipher.IV\n\n                    else:\n                        log.error(\"Could not parse the IV from the protobuf message. Please report a bug.\")\n                        raise DecodeError\n\n                    # We are done here\n                    log.debug(header_info(header))\n\n                    props = Props(v_features=header.info)\n                    if header.c15_iv.IV:\n                        db = Database15(iv=iv, props=props)\n                        db.file_hash = file_hash\n                        return db\n                    elif header.c14_cipher.IV:\n                        db = Database14(iv=iv, props=props)\n                        db.file_hash = file_hash\n                        return db\n                    else:\n                        log.error(\"Could not parse the IV from the protobuf message. Please report a bug.\")\n                        raise DecodeError\n\n            except DecodeError:\n\n                # try again as a crypt12\n                log.debug(\"Could not parse the protobuf message as a crypt14/15. Trying as a crypt12...\")\n                try:\n                    encrypted.seek(0)\n                except OSError as e:\n                    log.fatal(\"Could not reset the file pointer: {}\".format(e))\n                    raise e\n                return Database12(encrypted=encrypted)\n\n        except OSError as e:\n            log.fatal(\"Reading database header failed: {}\".format(e))\n"
  },
  {
    "path": "src/wa_crypt_tools/lib/key/key.py",
    "content": "from __future__ import annotations\n\nimport abc\n\nclass Key(abc.ABC):\n    @abc.abstractmethod\n    def __init__(self, keyarray: bytes = None):\n        pass\n\n    @abc.abstractmethod\n    def __str__(self) -> str:\n        pass\n\n    @abc.abstractmethod\n    def get(self) -> bytes:\n        pass\n\n    @abc.abstractmethod\n    def dump(self) -> bytes:\n        pass\n"
  },
  {
    "path": "src/wa_crypt_tools/lib/key/key14.py",
    "content": "from hashlib import sha256\nfrom os import urandom\nfrom pathlib import Path\n\nfrom javaobj import JavaObjectMarshaller\n\nfrom wa_crypt_tools.lib.key.key import Key\nfrom wa_crypt_tools.lib.utils import create_jba\n\nimport logging\n\nlog = logging.getLogger(__name__)\n\n\nclass Key14(Key):\n    # These constants are only used with crypt12/14 keys.\n    __SUPPORTED_CIPHER_VERSION = b'\\x00\\x01'\n    __SUPPORTED_KEY_VERSIONS = [b'\\x01', b'\\x02', b'\\x03']\n\n    def __init__(self, keyarray: bytes = None,\n                 cipher_version: bytes = None, key_version: bytes = None,\n                 serversalt: bytes = None, googleid: bytes = None, hashedgoogleid: bytes = None,\n                 iv: bytes = None, key: bytes = None):\n        \"\"\"Extracts the fields from a crypt14 loaded key file.\"\"\"\n        # key file format and encoding explanation:\n        # The key file is actually a serialized byte[] object.\n\n        # After deserialization, we will have a byte[] object that we have to split in:\n        # 1) The cipher version (2 bytes). Known values are 0x0000 and 0x0001. So far we only support the latter.\n        # SUPPORTED_CIPHER_VERSION = b'\\x00\\x01'\n        # 2) The key version (1 byte). All the known versions are supported.\n        # SUPPORTED_KEY_VERSIONS = [b'\\x01', b'\\x02', b'\\x03']\n        # Looks like nothing actually changes between the versions.\n        # 3) Server salt (32 bytes)\n        # 4) googleIdSalt (unused?) (16 bytes)\n        # 5) hashedGoogleID (The SHA-256 hash of googleIdSalt) (32 bytes)\n        # 6) encryption IV (zeroed out, as it is read from the database) (16 bytes)\n        # 7) cipherKey (The actual AES-256 decryption key) (32 bytes)\n\n        if keyarray is None:\n            # Randomly generated key or with supplied parameters\n            if cipher_version is None:\n                self.__cipher_version = self.__SUPPORTED_CIPHER_VERSION\n            else:\n                if cipher_version != self.__SUPPORTED_CIPHER_VERSION:\n                    log.error(\"Invalid cipher version: {}\".format(cipher_version.hex()))\n                self.__cipher_version = cipher_version\n            if key_version is None:\n                self.__key_version = self.__SUPPORTED_KEY_VERSIONS[-1]\n            else:\n                if key_version not in self.__SUPPORTED_KEY_VERSIONS:\n                    log.error(\"Invalid key version: {}\".format(key_version.hex()))\n                self.__key_version = key_version\n            if serversalt is None:\n                self.__serversalt = urandom(32)\n            else:\n                if len(serversalt) != 32:\n                    raise ValueError(\"Invalid server salt length: {}\".format(serversalt.hex()))\n                self.__serversalt = serversalt\n            if googleid is None:\n                self.__googleid = urandom(16)\n            else:\n                if len(googleid) != 16:\n                    raise ValueError(\"Invalid google id length: {}\".format(googleid.hex()))\n                self.__googleid = googleid\n            if hashedgoogleid is None:\n                self.__hashedgoogleid = sha256(self.__googleid).digest()\n            else:\n                log.warning(\"Using supplied hashed google id\")\n                if len(hashedgoogleid) != 32:\n                    log.error(\"Invalid hashed google id length: {}\".format(hashedgoogleid.hex()))\n                self.__hashedgoogleid = hashedgoogleid\n            if iv is None:\n                self.__padding = b'\\x00' * 16\n            else:\n                if len(iv) != 16:\n                    log.error(\"Invalid IV length: {}\".format(iv.hex()))\n                if iv != b'\\x00' * 16:\n                    log.warning(\"IV should be empty\")\n                self.__padding = iv\n            if key is None:\n                self.__key = urandom(32)\n            else:\n                if len(key) != 32:\n                    log.error(\"Invalid key length: {}\".format(key.hex()))\n                self.__key = key\n            return\n        # Check if the keyfile has a supported cipher version\n        self.__cipher_version = keyarray[:len(self.__SUPPORTED_CIPHER_VERSION)]\n        if self.__SUPPORTED_CIPHER_VERSION != self.__cipher_version:\n            log.error(\"Invalid keyfile: Unsupported cipher version {}\"\n                      .format(keyarray[:len(self.__SUPPORTED_CIPHER_VERSION)].hex()))\n        index = len(self.__SUPPORTED_CIPHER_VERSION)\n\n        # Check if the keyfile has a supported key version\n        version_supported = False\n        for v in self.__SUPPORTED_KEY_VERSIONS:\n            if v == keyarray[index:index + len(self.__SUPPORTED_KEY_VERSIONS[0])]:\n                version_supported = True\n                self.__key_version = v\n                break\n        if not version_supported:\n            log.error('Invalid keyfile: Unsupported key version {}'\n                      .format(keyarray[index:index + len(self.__SUPPORTED_KEY_VERSIONS[0])].hex()))\n\n        self.__serversalt = keyarray[3:35]\n\n        # Check the SHA-256 of the salt\n        self.__googleid = keyarray[35:51]\n        expected_digest = sha256(self.__googleid).digest()\n        actual_digest = keyarray[51:83]\n        if expected_digest != actual_digest:\n            log.error(\"Invalid keyfile: Invalid SHA-256 of salt.\\n    \"\n                      \"Expected: {}\\n    Got:{}\".format(expected_digest, actual_digest))\n\n        self.__hashedgoogleid = actual_digest\n\n        self.__padding = keyarray[83:99]\n\n        # Check if IV is made of zeroes\n        for byte in self.__padding:\n            if byte:\n                log.error(\"Invalid keyfile: IV is not zeroed out but is: {}\".format(self.__padding.hex()))\n                break\n\n        self.__key = keyarray[99:]\n\n        log.info(\"Crypt12/14 key loaded\")\n\n    def get(self) -> bytes:\n        return self.__key\n\n    def get_serversalt(self) -> bytes:\n        return self.__serversalt\n\n    def get_googleid(self) -> bytes:\n        return self.__googleid\n\n    def get_cipher_version(self) -> bytes:\n        return self.__cipher_version\n\n    def get_key_version(self) -> bytes:\n        return self.__key_version\n\n    def __str__(self) -> str:\n        \"\"\"Returns a string representation of the key\"\"\"\n        try:\n            string: str = \"Key14(\"\n            if self.__key is not None:\n                string += \"key: {}\".format(self.__key.hex())\n            if self.__serversalt is not None:\n                string += \" , serversalt: {}\".format(self.__serversalt.hex())\n            if self.__googleid is not None:\n                string += \" , googleid: {}\".format(self.__googleid.hex())\n            if self.__key_version is not None:\n                string += \" , key_version: {}\".format(self.__key_version.hex())\n            if self.__cipher_version is not None:\n                string += \" , cipher_version: {}\".format(self.__cipher_version.hex())\n            return string + \")\"\n        except Exception as e:\n            return \"Exception printing key: {}\".format(e)\n\n    def __repr__(self) -> str:\n        # TODO\n        return self.__str__()\n\n    def dump(self) -> bytes:\n        \"\"\"Dumps the key to a file\"\"\"\n        out: bytes = b''\n        out += self.__cipher_version\n        out += self.__key_version\n        out += self.__serversalt\n        out += self.__googleid\n        out += self.__hashedgoogleid\n        out += self.__padding\n        out += self.__key\n        return JavaObjectMarshaller().dump(create_jba(out))\n\n    def file_dump(self, file: Path):\n        with open(file, 'wb') as f:\n            f.write(self.dump())\n"
  },
  {
    "path": "src/wa_crypt_tools/lib/key/key15.py",
    "content": "import hmac\nfrom hashlib import sha256\nfrom os import urandom\nfrom pathlib import Path\n\nfrom javaobj import JavaObjectMarshaller\n\nfrom wa_crypt_tools.lib.utils import create_jba, encryptionloop\n\nfrom wa_crypt_tools.lib.key.key import Key\nimport logging\n\nl = logging.getLogger(__name__)\n\n\nclass Key15(Key):\n    # This constant is only used with crypt15 keys.\n    BACKUP_ENCRYPTION = b'backup encryption'\n\n    def __init__(self, keyarray: bytes = None, key: bytes = None):\n        \"\"\"Extracts the key from a loaded crypt15 key file.\"\"\"\n        # encrypted_backup.key file format and encoding explanation:\n        # The E2E key file is actually a serialized byte[] object.\n\n        # After deserialization, we will have the root key (32 bytes).\n        # The root key is further encoded with three different strings, depending on what you want to do.\n        # These three ways are \"backup encryption\";\n        # \"metadata encryption\" and \"metadata authentication\", for Google Drive E2E encrypted metadata.\n        # We are only interested in the local backup encryption.\n\n        # Why the \\x01 at the end of the BACKUP_ENCRYPTION constant?\n        # Whatsapp uses a nested encryption function to encrypt many times the same data.\n        # The iteration counter is appended to the end of the encrypted data. However,\n        # since the loop is actually executed only one time, we will only have one interaction,\n        # and thus a \\x01 at the end.\n        # Take a look at utils/wa_hmacsha256_loop.java that is the original code.\n\n        if keyarray is None:\n            # Randomly generated key or with supplied parameters\n            if key is None:\n                self.__key = urandom(32)\n            else:\n                if len(key) != 32:\n                    l.error(\"Invalid key length: {}\".format(key.hex()))\n                self.__key = key\n            return\n\n        if not isinstance(keyarray, bytes):\n            raise ValueError(\"keyarray is not a byte array!\")\n\n        if len(keyarray) != 32:\n            raise ValueError(\"Invalid key length\")\n        l.debug(\"Root key: {}\".format(keyarray.hex()))\n        # Save the root key in the class\n        self.__key = keyarray\n\n        l.info(\"Crypt15 / Raw key loaded\")\n\n    def get(self) -> bytes:\n        \"\"\"\n        Returns the key used for encryption, that is not the root key.\n        \"\"\"\n        return encryptionloop(\n            first_iteration_data=self.__key,\n            message=b'backup encryption',\n            output_bytes=32)\n\n    def get_root(self) -> bytes:\n        \"\"\"\n        Returns the root key.\n        \"\"\"\n        return self.__key\n\n    def get_metadata_encryption(self) -> bytes:\n        \"\"\"\n        Returns the key used for metadata encryption\n        \"\"\"\n        return encryptionloop(\n            first_iteration_data=self.__key,\n            message=b'metadata encryption',\n            output_bytes=32)\n\n    def get_metadata_authentication(self) -> bytes:\n        \"\"\"\n        Returns the key used for metadata authentication\n        \"\"\"\n        return encryptionloop(\n            first_iteration_data=self.__key,\n            message=b'metadata authentication',\n            output_bytes=32)\n\n    def dump(self) -> bytes:\n        \"\"\"Dumps the key\"\"\"\n        return JavaObjectMarshaller().dump(create_jba(self.__key))\n\n    def file_dump(self, file: Path):\n        with open(file, 'wb') as f:\n            f.write(self.dump())\n\n    def __str__(self) -> str:\n        \"\"\"Returns a string representation of the key\"\"\"\n        try:\n            string: str = \"Key15(\"\n            if self.__key is not None:\n                string += \"key: {}\".format(self.__key.hex())\n            return string + \")\"\n        except Exception as e:\n            return \"Exception printing key: {}\".format(e)\n\n    def __repr__(self) -> str:\n        # TODO\n        return self.__str__()\n"
  },
  {
    "path": "src/wa_crypt_tools/lib/key/keyfactory.py",
    "content": "from pathlib import Path\n\nimport javaobj.v2 as javaobj\n\nfrom wa_crypt_tools.lib.key.key14 import Key14\nfrom wa_crypt_tools.lib.key.key15 import Key15\n\nimport logging\n\nfrom wa_crypt_tools.lib.utils import javaintlist2bytes, hexstring2bytes\n\nl = logging.getLogger(__name__)\nclass KeyFactory:\n    @staticmethod\n    def new(file: Path):\n        \"\"\"Tries to load the key from a file, or if it fails, from a hex string.\"\"\"\n        try:\n            return KeyFactory.from_file(file)\n        except OSError:\n            try:\n                return KeyFactory.from_hex(str(file))\n            except ValueError:\n                l.critical(\"The key file specified does not exist.\\n    \"\n                           \"If you tried to specify the key directly, note it should be \"\n                           \"64 characters long and not {} characters long.\".format(len(str(file))))\n\n    @staticmethod\n    def from_file(file: Path):\n        keyfile: bytes = b''\n\n        l.debug(\"Reading keyfile...\")\n\n        # Try to open the keyfile.\n        try:\n            key_file_stream = open(file, 'rb')\n            try:\n                # Deserialize the byte object written in the file\n                jarr: javaobj.beans.JavaArray = javaobj.load(key_file_stream).data\n                # Convert from a list of Int8 to a byte array\n                keyfile: bytes = javaintlist2bytes(jarr)\n\n            except (ValueError, RuntimeError) as e:\n                l.critical(\"The keyfile is not a valid Java object: {}\".format(e))\n\n        except OSError:\n            l.info(\"The keyfile could not be opened.\")\n            raise OSError\n\n        # We guess the key type from its length\n        if len(keyfile) == 131:\n            return Key14(keyarray=keyfile)\n        elif len(keyfile) == 32:\n            return Key15(keyarray=keyfile)\n        else:\n            l.critical(\"Unrecognized key file format.\")\n\n    @staticmethod\n    def from_hex(hexstring: str) -> Key15:\n        if hexstring is None or len(hexstring) != 64:\n            raise ValueError(\"The key is invalid or of the wrong length.\")\n        barr: bytes = hexstring2bytes(hexstring)\n        if barr is None or len(barr) != 32:\n            raise ValueError(\"The key is invalid or of the wrong length.\")\n        return Key15(keyarray=barr)"
  },
  {
    "path": "src/wa_crypt_tools/lib/logformat.py",
    "content": "import logging\n\n\nclass CustomFormatter(logging.Formatter):\n    grey = \"\\x1b[38;20m\"\n    yellow = \"\\x1b[33;20m\"\n    red = \"\\x1b[31;20m\"\n    bold_red = \"\\x1b[31;1m\"\n    reset = \"\\x1b[0m\"\n    format = \"%(filename)s:%(lineno)d \\t: [%(levelname).1s] %(message)s\"\n\n    FORMATS = {\n        logging.DEBUG: grey + format + reset,\n        logging.INFO: grey + format + reset,\n        logging.WARNING: yellow + format + reset,\n        logging.ERROR: red + format + reset,\n        logging.CRITICAL: bold_red + format + reset\n    }\n\n    def format(self, record):\n        log_fmt = self.FORMATS.get(record.levelno)\n        formatter = logging.Formatter(log_fmt)\n        return formatter.format(record)\n"
  },
  {
    "path": "src/wa_crypt_tools/lib/props.py",
    "content": "from __future__ import annotations\n\nfrom wa_crypt_tools.lib.constants import C\nfrom wa_crypt_tools.proto import backup_expiry_pb2 as backup_expiry\n\nclass Props:\n    def __init__(self, *, v_features=None, wa_version: str = C.DEFAULT_APP_VERSION, jid: str = C.DEFAULT_JID_SUFFIX,\n                 features: list[int] | None = C.DEFAULT_FEATURE_LIST, max_feature: int = C.DEFAULT_MAX_FEATURE,\n                 backup_version: int = C.DEFAULT_BACKUP_VERSION):\n        if v_features is not None:\n            self.props = v_features\n            return\n        self.props = backup_expiry.BackupExpiry()\n        self.props.app_version = wa_version\n        self.props.jidSuffix = jid\n        self.max_feature = max_feature\n        if features is None or len(features) == 0:\n            return\n        self.props.backup_version = backup_version\n        for f in range(5, max_feature + 1):\n            try:\n                self.disable_feature(f)\n            except AttributeError:\n                pass\n        for f in features:\n            self.enable_feature(f)\n\n    def enable_feature(self, feature: int):\n        feature_name = \"f_\" + str(feature)\n        setattr(self.props, feature_name, True)\n\n    def disable_feature(self, feature: int):\n        feature_name = \"f_\" + str(feature)\n        setattr(self.props, feature_name, False)\n\n    def get_feature(self, feature: int) -> bool:\n        feature_name = \"f_\" + str(feature)\n        return getattr(self.props, feature_name)\n\n    def get_features(self) -> list[int]:\n        features = []\n        for i in range(5, self.max_feature + 1):\n            try:\n                if self.get_feature(i):\n                    features.append(i)\n            except AttributeError:\n                pass\n        return features\n\n    def get_wa_version(self) -> str:\n        return self.props.version\n\n    def get_jid(self) -> str:\n        return self.props.jidSuffix\n\n    def get_proto(self):\n        return self.props\n\n    def __str__(self):\n        return str(self.props)"
  },
  {
    "path": "src/wa_crypt_tools/lib/utils.py",
    "content": "import base64\nimport hmac\nimport json\nimport math\nimport zlib\nfrom hashlib import sha256\n\nfrom Cryptodome.Cipher import AES\nfrom javaobj import JavaByteArray\nfrom javaobj.v2.beans import JavaArray, JavaClassDesc, ClassDescType\n\nimport logging\n\nfrom wa_crypt_tools.lib.constants import C\n\n# FIXME a \"utils\" file shouldn't have its own logger\nl = logging.getLogger(__name__)\n\n\ndef test_decompression(test_data: bytes) -> bool:\n    \"\"\"Returns true if the SQLite header is valid.\n    It is assumed that the data are valid.\n    (If it is valid, it also means the decryption and decompression were successful.)\"\"\"\n\n    # If we get a ZIP file header, return true\n    if test_data[:4] == C.ZIP_HEADER:\n        return True\n\n    try:\n        zlib_obj = zlib.decompressobj().decompress(test_data)\n        # These two errors should never happen\n        if len(zlib_obj) < 16:\n            l.error(\"Test decompression: chunk too small\")\n            return False\n        # Decoding can fail if first two bytes are a bad UTF-8 char\n        if zlib_obj[:15].decode('ascii') != 'SQLite format 3':\n            l.error(\"Test decompression: Decryption and decompression ok but not a valid SQLite database\")\n            return False\n        else:\n            return True\n    except (zlib.error, UnicodeDecodeError):\n        return False\n\n\ndef create_jba(out: bytes) -> JavaByteArray:\n    \"\"\"Creates a JavaByteArray object from a bytes array\"\"\"\n    # Create the classdesc\n    cd = JavaClassDesc(ClassDescType.NORMALCLASS)\n    cd.name = \"[B\"\n    cd.superclass = None\n    cd.serial_version_uid = -5984413125824719648\n    cd.desc_flags = 2\n\n    return JavaByteArray(out, classdesc=cd)\n\n\ndef hexstring2bytes(string: str) -> bytes:\n    \"\"\"Converts a hex string into a bytes array\"\"\"\n    if len(string) != 64:\n        l.critical(\"The key file specified does not exist.\\n    \"\n                   \"If you tried to specify the key directly, note it should be \"\n                   \"64 characters long and not {} characters long.\".format(len(string)))\n\n    barr = None\n    try:\n        barr = bytes.fromhex(string)\n    except ValueError as e:\n        l.critical(\"Couldn't convert the hex string.\\n    \"\n                   \"Exception: {}\".format(e))\n    if len(barr) != 32:\n        l.error(\"The key is not 32 bytes long but {} bytes long.\".format(len(barr)))\n    return barr\n\n\ndef javaintlist2bytes(barr: JavaArray) -> bytes:\n    \"\"\"Converts a javaobj bytearray which somehow became a list of signed integers back to a Python byte array\"\"\"\n    out: bytes = b''\n    for i in barr:\n        out += i.to_bytes(1, byteorder='big', signed=True)\n    return out\n\n\ndef encryptionloop(*, first_iteration_data: bytes, privateseed: bytes = b'\\x00' * 32, message: bytes,\n                   output_bytes: int):\n    # The private key and the seed are used to create the HMAC key\n    privatekey = hmac.new(privateseed, msg=first_iteration_data, digestmod=sha256).digest()\n\n    data = b''\n    output = b''\n    permutations = int(math.ceil(float(output_bytes) / float(32)))\n    i = 1\n    while i < permutations + 1:\n        hasher = hmac.new(privatekey, msg=data, digestmod=sha256)\n        if message is not None:\n            hasher.update(message)\n        hasher.update(i.to_bytes(1, byteorder='big'))\n        data = hasher.digest()\n        bytestowrite = min(output_bytes, len(data))\n        output += data[:bytestowrite]\n        i += 1\n    return output\n\n\ndef mcrypt1_metadata_decrypt(*, key, encoded: str):\n    \"\"\"\n    Decrypts the metadata of a mcrypt1 file.\n    :param key: The key used to decrypt the metadata\n    :param encoded: The metadata downloaded from Google Drive in base64\n    :return: The decrypted JSON\n    \"\"\"\n    # Base64 decoding\n    encoded = base64.b64decode(encoded)\n    # PKCS5Padding is not natively supported\n    unpad = lambda s: s[:-ord(s[len(s) - 1:])]\n    iv_size = encoded[0]\n    if iv_size != 16:\n        raise Exception(\"IV Size is not 16\")\n\n    iv = encoded[1:17]\n    mac_size = encoded[17]\n    if mac_size != 32:\n        raise Exception(\"MAC Size is not 32\")\n\n    mac = encoded[18:50]\n    encrypted_metadata = encoded[50:]\n    # Authentication part\n    hmac_auth = hmac.new(key.get_metadata_authentication(), digestmod='sha256')\n    hmac_auth.update(iv)\n    hmac_auth.update(encrypted_metadata)\n    hmac_auth = hmac_auth.digest()\n    if hmac_auth != mac:\n        raise ValueError(\"MAC does not match\")\n    # Decryption part\n    cipher = AES.new(key.get_metadata_encryption(), AES.MODE_CBC, iv)\n    decrypted_metadata = cipher.decrypt(encrypted_metadata)\n    decrypted_metadata = unpad(decrypted_metadata)\n    # Load the JSON\n    return json.loads(decrypted_metadata.decode('utf-8'))\n\n\ndef get_mcrypt1_name(*, key, name: str, md5: bytes) -> bytes:\n    hmac_n = hmac.new(key.get_root(), digestmod='sha256')\n    # Calculate SHA256 of the name\n    digest = sha256()\n    digest.update(name.encode('utf-8'))\n    # Pour it into the HMAC\n    hmac_n.update(digest.digest())\n    # If md5 is a string, convert it to bytes\n    if isinstance(md5, str):\n        md5 = bytes.fromhex(md5)\n    # Now pour the MD5 into the HMAC\n    hmac_n.update(md5)\n    media_hash = hmac_n.digest()\n    return media_hash\n\n\ndef header_info(header):\n    \"\"\"\n    shows all header, information including the feature vector\n    FIXME\n    \"\"\"\n    string: str = \"\"\n    if header.c15_iv.IV:\n        string += \"Crypt15 info:\\n\"\n        string += str(\"Header information in your crypt15 file:\")\n        string += str(\"IV: {}\\n\".format(header.c15_iv.IV.hex()))\n    if header.c14_cipher.IV:\n        string += str(\"Header information in your crypt14 file:\\n\")\n        string += str(\"Cipher version: {}\\n\".format(header.c14_cipher.cipher_version.hex()))\n        string += str(\"Key version: {}\\n\".format(header.c14_cipher.key_version.hex()))\n        string += str(\"Server salt: {}\\n\".format(header.c14_cipher.server_salt.hex()))\n        string += str(\"Google ID: {}\\n\".format(header.c14_cipher.google_id.hex()))\n        string += str(\"IV: {}\\n\".format(header.c14_cipher.IV.hex()))\n    string += str(\"Key type: {}\\n\".format(header.key_type))\n    string += str(\"WhatsApp version: {}\\n\".format(header.info.app_version))\n    #string += str(\"Device model: {}\".format(header.info.device_model))\n    string += str(\"The last two numbers of the user's Jid: {}\\n\".format(header.info.jidSuffix))\n    string += str(\"Backup version: {}\\n\".format(header.info.backup_version))\n    #string += str(\"Size of the backup file: {}\".format(header.backup_export_file_size))\n    features = [n for n in [*range(5, 38), 39] if getattr(header.info, \"f_\" + str(n)) == True]\n    if len(features) > 0:\n        string += str(\"Features: {}\\n\".format(features))\n        string += str(\"Max feature number: {}\\n\".format(max(features)))\n    else:\n        string += str(\"No feature table found (not a msgstore DB or very old)\\n\")\n\n    return string\n"
  },
  {
    "path": "src/wa_crypt_tools/proto/C14_cipher_pb2.py",
    "content": "\"\"\"Generated protocol buffer code.\"\"\"\nfrom google.protobuf import descriptor as _descriptor\nfrom google.protobuf import descriptor_pool as _descriptor_pool\nfrom google.protobuf import runtime_version as _runtime_version\nfrom google.protobuf import symbol_database as _symbol_database\nfrom google.protobuf.internal import builder as _builder\n_runtime_version.ValidateProtobufRuntimeVersion(_runtime_version.Domain.PUBLIC, 5, 29, 5, '', 'C14_cipher.proto')\n_sym_db = _symbol_database.Default()\nDESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\\n\\x10C14_cipher.proto\"m\\n\\nC14_cipher\\x12\\x16\\n\\x0ecipher_version\\x18\\x01 \\x01(\\x0c\\x12\\x13\\n\\x0bkey_version\\x18\\x02 \\x01(\\x0c\\x12\\x13\\n\\x0bserver_salt\\x18\\x03 \\x01(\\x0c\\x12\\x11\\n\\tgoogle_id\\x18\\x04 \\x01(\\x0c\\x12\\n\\n\\x02IV\\x18\\x05 \\x01(\\x0cb\\x08editionsp\\xe8\\x07')\n_globals = globals()\n_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)\n_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'C14_cipher_pb2', _globals)\nif not _descriptor._USE_C_DESCRIPTORS:\n    DESCRIPTOR._loaded_options = None\n    _globals['_C14_CIPHER']._serialized_start = 20\n    _globals['_C14_CIPHER']._serialized_end = 129"
  },
  {
    "path": "src/wa_crypt_tools/proto/C15_IV_pb2.py",
    "content": "\"\"\"Generated protocol buffer code.\"\"\"\nfrom google.protobuf import descriptor as _descriptor\nfrom google.protobuf import descriptor_pool as _descriptor_pool\nfrom google.protobuf import runtime_version as _runtime_version\nfrom google.protobuf import symbol_database as _symbol_database\nfrom google.protobuf.internal import builder as _builder\n_runtime_version.ValidateProtobufRuntimeVersion(_runtime_version.Domain.PUBLIC, 5, 29, 5, '', 'C15_IV.proto')\n_sym_db = _symbol_database.Default()\nDESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\\n\\x0cC15_IV.proto\"\\x14\\n\\x06C15_IV\\x12\\n\\n\\x02IV\\x18\\x01 \\x01(\\x0cb\\x08editionsp\\xe8\\x07')\n_globals = globals()\n_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)\n_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'C15_IV_pb2', _globals)\nif not _descriptor._USE_C_DESCRIPTORS:\n    DESCRIPTOR._loaded_options = None\n    _globals['_C15_IV']._serialized_start = 16\n    _globals['_C15_IV']._serialized_end = 36"
  },
  {
    "path": "src/wa_crypt_tools/proto/__init__.py",
    "content": ""
  },
  {
    "path": "src/wa_crypt_tools/proto/backup_expiry_pb2.py",
    "content": "\"\"\"Generated protocol buffer code.\"\"\"\nfrom google.protobuf import descriptor as _descriptor\nfrom google.protobuf import descriptor_pool as _descriptor_pool\nfrom google.protobuf import runtime_version as _runtime_version\nfrom google.protobuf import symbol_database as _symbol_database\nfrom google.protobuf.internal import builder as _builder\n_runtime_version.ValidateProtobufRuntimeVersion(_runtime_version.Domain.PUBLIC, 5, 29, 5, '', 'backup_expiry.proto')\n_sym_db = _symbol_database.Default()\nDESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\\n\\x13backup_expiry.proto\"\\xa5\\x04\\n\\x0cBackupExpiry\\x12\\x13\\n\\x0bapp_version\\x18\\x01 \\x01(\\t\\x12\\x11\\n\\tjidSuffix\\x18\\x03 \\x01(\\t\\x12\\x16\\n\\x0ebackup_version\\x18\\x04 \\x01(\\x05\\x12\\x0b\\n\\x03f_5\\x18\\x05 \\x01(\\x08\\x12\\x0b\\n\\x03f_6\\x18\\x06 \\x01(\\x08\\x12\\x0b\\n\\x03f_7\\x18\\x07 \\x01(\\x08\\x12\\x0b\\n\\x03f_8\\x18\\x08 \\x01(\\x08\\x12\\x0b\\n\\x03f_9\\x18\\t \\x01(\\x08\\x12\\x0c\\n\\x04f_10\\x18\\n \\x01(\\x08\\x12\\x0c\\n\\x04f_11\\x18\\x0b \\x01(\\x08\\x12\\x0c\\n\\x04f_12\\x18\\x0c \\x01(\\x08\\x12\\x0c\\n\\x04f_13\\x18\\r \\x01(\\x08\\x12\\x0c\\n\\x04f_14\\x18\\x0e \\x01(\\x08\\x12\\x0c\\n\\x04f_15\\x18\\x0f \\x01(\\x08\\x12\\x0c\\n\\x04f_16\\x18\\x10 \\x01(\\x08\\x12\\x0c\\n\\x04f_17\\x18\\x11 \\x01(\\x08\\x12\\x0c\\n\\x04f_18\\x18\\x12 \\x01(\\x08\\x12\\x0c\\n\\x04f_19\\x18\\x13 \\x01(\\x08\\x12\\x0c\\n\\x04f_20\\x18\\x14 \\x01(\\x08\\x12\\x0c\\n\\x04f_21\\x18\\x15 \\x01(\\x08\\x12\\x0c\\n\\x04f_22\\x18\\x16 \\x01(\\x08\\x12\\x0c\\n\\x04f_23\\x18\\x17 \\x01(\\x08\\x12\\x0c\\n\\x04f_24\\x18\\x18 \\x01(\\x08\\x12\\x0c\\n\\x04f_25\\x18\\x19 \\x01(\\x08\\x12\\x0c\\n\\x04f_26\\x18\\x1a \\x01(\\x08\\x12\\x0c\\n\\x04f_27\\x18\\x1b \\x01(\\x08\\x12\\x0c\\n\\x04f_28\\x18\\x1c \\x01(\\x08\\x12\\x0c\\n\\x04f_29\\x18\\x1d \\x01(\\x08\\x12\\x0c\\n\\x04f_30\\x18\\x1e \\x01(\\x08\\x12\\x0c\\n\\x04f_31\\x18\\x1f \\x01(\\x08\\x12\\x0c\\n\\x04f_32\\x18  \\x01(\\x08\\x12\\x0c\\n\\x04f_33\\x18! \\x01(\\x08\\x12\\x0c\\n\\x04f_34\\x18\" \\x01(\\x08\\x12\\x0c\\n\\x04f_35\\x18# \\x01(\\x08\\x12\\x0c\\n\\x04f_36\\x18$ \\x01(\\x08\\x12\\x0c\\n\\x04f_37\\x18% \\x01(\\x08\\x12\\x0c\\n\\x04f_39\\x18\\' \\x01(\\x08b\\x08editionsp\\xe8\\x07')\n_globals = globals()\n_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)\n_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'backup_expiry_pb2', _globals)\nif not _descriptor._USE_C_DESCRIPTORS:\n    DESCRIPTOR._loaded_options = None\n    _globals['_BACKUPEXPIRY']._serialized_start = 24\n    _globals['_BACKUPEXPIRY']._serialized_end = 573"
  },
  {
    "path": "src/wa_crypt_tools/proto/backup_prefix_pb2.py",
    "content": "\"\"\"Generated protocol buffer code.\"\"\"\nfrom google.protobuf import descriptor as _descriptor\nfrom google.protobuf import descriptor_pool as _descriptor_pool\nfrom google.protobuf import runtime_version as _runtime_version\nfrom google.protobuf import symbol_database as _symbol_database\nfrom google.protobuf.internal import builder as _builder\n_runtime_version.ValidateProtobufRuntimeVersion(_runtime_version.Domain.PUBLIC, 5, 29, 5, '', 'backup_prefix.proto')\n_sym_db = _symbol_database.Default()\nfrom . import C14_cipher_pb2 as C14__cipher__pb2\nfrom . import C15_IV_pb2 as C15__IV__pb2\nfrom . import key_type_pb2 as key__type__pb2\nfrom . import backup_expiry_pb2 as backup__expiry__pb2\nDESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\\n\\x13backup_prefix.proto\\x1a\\x10C14_cipher.proto\\x1a\\x0cC15_IV.proto\\x1a\\x0ekey_type.proto\\x1a\\x13backup_expiry.proto\"\\x95\\x01\\n\\x0cBackupPrefix\\x12\\x1b\\n\\x08key_type\\x18\\x01 \\x01(\\x0e2\\t.Key_Type\\x12!\\n\\nc14_cipher\\x18\\x02 \\x01(\\x0b2\\x0b.C14_cipherH\\x00\\x12\\x19\\n\\x06c15_iv\\x18\\x03 \\x01(\\x0b2\\x07.C15_IVH\\x00\\x12\\x1b\\n\\x04info\\x18\\x04 \\x01(\\x0b2\\r.BackupExpiryB\\r\\n\\x0bcipher_infob\\x08editionsp\\xe8\\x07')\n_globals = globals()\n_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)\n_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'backup_prefix_pb2', _globals)\nif not _descriptor._USE_C_DESCRIPTORS:\n    DESCRIPTOR._loaded_options = None\n    _globals['_BACKUPPREFIX']._serialized_start = 93\n    _globals['_BACKUPPREFIX']._serialized_end = 242"
  },
  {
    "path": "src/wa_crypt_tools/proto/key_type_pb2.py",
    "content": "\"\"\"Generated protocol buffer code.\"\"\"\nfrom google.protobuf import descriptor as _descriptor\nfrom google.protobuf import descriptor_pool as _descriptor_pool\nfrom google.protobuf import runtime_version as _runtime_version\nfrom google.protobuf import symbol_database as _symbol_database\nfrom google.protobuf.internal import builder as _builder\n_runtime_version.ValidateProtobufRuntimeVersion(_runtime_version.Domain.PUBLIC, 5, 29, 5, '', 'key_type.proto')\n_sym_db = _symbol_database.Default()\nDESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\\n\\x0ekey_type.proto*/\\n\\x08Key_Type\\x12\\x0f\\n\\x0bWA_PROVIDED\\x10\\x00\\x12\\x12\\n\\x0eHSM_CONTROLLED\\x10\\x01b\\x08editionsp\\xe8\\x07')\n_globals = globals()\n_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)\n_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'key_type_pb2', _globals)\nif not _descriptor._USE_C_DESCRIPTORS:\n    DESCRIPTOR._loaded_options = None\n    _globals['_KEY_TYPE']._serialized_start = 18\n    _globals['_KEY_TYPE']._serialized_end = 65"
  },
  {
    "path": "src/wa_crypt_tools/wacreatekey.py",
    "content": "#!/usr/bin/env python\n\"\"\"\nThis script decrypts WhatsApp's DB files encrypted with Crypt12, Crypt14 or Crypt15.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nfrom pathlib import Path\n\nfrom wa_crypt_tools.lib.key.key14 import Key14\nfrom wa_crypt_tools.lib.key.key15 import Key15\nfrom wa_crypt_tools.lib.logformat import CustomFormatter\nimport argparse\n\n__author__ = 'ElDavo'\n__copyright__ = 'Copyright (C) 2023'\n__license__ = 'GPLv3'\n__status__ = 'Production'\n\nimport logging\n\nlo = logging.getLogger(__name__)\n\n\ndef parsecmdline() -> argparse.Namespace:\n    \"\"\"Sets up the argument parser\"\"\"\n    parser = argparse.ArgumentParser(description='Create a key or encrypted_backup.key from a hex input.'\n                                                 'The only parameter a encrypted_backup.key stores is the key itself.')\n    parser.add_argument('-c14', '--crypt14', action='store_true', default=False, help='Create a traditional key file.')\n    parser.add_argument('-o', '--output', type=str,\n                        help='The output file')\n    parser.add_argument('-y', '--yes', action='store_true', help='Overwrite the output file if it exists.')\n    parser.add_argument('-v', '--verbose', action='store_true', help='Prints all messages')\n    parser.add_argument('--hex', type=str, nargs='?', help='The hex string to convert to a key')\n\n    parser.add_argument('-cv', '--cipher-version', type=int, help='The cipher version to use. Default: 1')\n    parser.add_argument('-kv', '--key-version', type=int, help='The key version to use. Default: 3')\n    parser.add_argument('-ss', '--server-salt', type=str, help='The server salt to use. Default: random')\n    parser.add_argument('-gi', '--googleid', type=str, help='The google id salt to use. Default: random')\n\n    return parser.parse_args()\n\n\ndef main():\n    args = parsecmdline()\n\n    # set wa_crypt_tools l to debug\n    lo.setLevel(logging.DEBUG if args.verbose else logging.INFO)\n    ch = logging.StreamHandler()\n    ch.setLevel(logging.DEBUG if args.verbose else logging.INFO)\n    ch.setFormatter(CustomFormatter())\n    lo.addHandler(ch)\n    # also add to \"wa_crypt_tools.lib\" logger\n    logging.getLogger(\"wa_crypt_tools.lib\").addHandler(ch)\n    logging.getLogger(\"wa_crypt_tools.lib\").setLevel(logging.DEBUG if args.verbose else logging.INFO)\n\n    hex_key = None\n    if args.hex is None:\n        lo.warning(\"Key not specified, a random key will be generated.\")\n    else:\n        try:\n            hex_key: bytes = bytes.fromhex(args.hex)\n        except ValueError:\n            lo.critical(\"Key is not in hexadecimal format\")\n            exit(1)\n\n\n    if args.output is None:\n        args.output = \"key\" if args.crypt14 else \"encrypted_backup.key\"\n\n    if args.crypt14:\n        if args.cipher_version is None:\n            args.cipher_version = 1\n        if args.key_version is None:\n            args.key_version = 3\n        if args.server_salt is None:\n            lo.warning(\"Server salt not specified, a random one will be generated.\")\n        if args.googleid is None:\n            lo.warning(\"Google id not specified, a random one will be generated.\")\n        try:\n            key: Key14 = Key14(cipher_version=args.cipher_version.to_bytes(2, \"big\"),\n                           key_version=args.key_version.to_bytes(1, \"big\"),\n                           serversalt=bytes.fromhex(args.server_salt) if args.server_salt is not None else None,\n                           googleid=bytes.fromhex(args.googleid) if args.googleid is not None else None,\n                           iv=None,\n                           key=hex_key)\n        except ValueError as e:\n            lo.critical(f\"Something was not right: {e}\")\n            exit(1)\n    else:\n        if args.cipher_version is not None:\n            lo.warning(\"Cipher version specified, but it is not used for crypt15 keys, ignoring.\")\n        if args.key_version is not None:\n            lo.warning(\"Key version specified, but it is not used for crypt15 keys, ignoring.\")\n        if args.server_salt is not None:\n            lo.warning(\"Server salt specified, but it is not used for crypt15 keys, ignoring.\")\n        if args.googleid is not None:\n            lo.warning(\"Google id specified, but it is not used for crypt15 keys, ignoring.\")\n        try:\n            key: Key15 = Key15(keyarray=hex_key)\n        except ValueError as e:\n            lo.critical(f\"Error while creating the key: {e}\")\n            exit(1)\n    # Check if the output file exists\n    output_file = Path(args.output)\n    print(os.getcwd())\n    if output_file.is_file() and not args.yes:\n        lo.fatal(\"The output file already exists.\")\n        exit(1)\n\n    # Write the key file\n    key.file_dump(output_file)\n\n    lo.info(\"Key file \\\"{}\\\" created.\".format(args.output))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "src/wa_crypt_tools/wadecrypt.py",
    "content": "#!/usr/bin/env python\n\"\"\"\nThis script decrypts WhatsApp's DB files encrypted with Crypt12, Crypt14 or Crypt15.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom wa_crypt_tools.lib.logformat import CustomFormatter\nfrom wa_crypt_tools.lib.key.keyfactory import KeyFactory\nfrom wa_crypt_tools.lib.db.dbfactory import DatabaseFactory\nfrom wa_crypt_tools.lib.utils import test_decompression\n\n# AES import party!\n# pycryptodome and PyCryptodomex's implementations of AES are the same,\n# so we try to import one of these twos.\ntry:\n    # pycryptodomex\n    from Cryptodome.Cipher import AES\nexcept ModuleNotFoundError:\n    try:\n        # pycryptodome\n        # noinspection PyUnresolvedReferences\n        from Crypto.Cipher import AES\n\n        if not hasattr(AES, 'MODE_GCM'):\n            # pycrypto\n            raise ModuleNotFoundError(\"You installed pycrypto and not pycryptodome(x). \"\n                                      \"Pycrypto is old, deprecated and not supported. \\n\"\n                                      \"Run: python -m pip uninstall pycrypto\\n\"\n                                      \"And: python -m pip install pycryptodomex\\n\"\n                                      \"Or:  python -m pip install pycryptodome\")\n    except ModuleNotFoundError:\n        # crypto (or nothing)\n        raise ModuleNotFoundError(\"You need pycryptodome(x) to run these scripts!\\n\"\n                                  \"python -m pip install pycryptodome\\n\"\n                                  \"Or: python -m pip install pycryptodome\\n\"\n                                  \"You can also remove \\\"crypto\\\" if you have it installed\\n\"\n                                  \"python -m pip uninstall crypto\")\n# noinspection PyPackageRequirements\n# This is from javaobj-py3\n\n# noinspection PyPackageRequirements\n\nimport io\nfrom re import findall\nfrom sys import maxsize\nfrom time import sleep\nfrom datetime import date\n\nimport argparse\nimport zlib\n\n__author__ = 'ElDavo'\n__copyright__ = 'Copyright (C) 2023'\n__license__ = 'GPLv3'\n__status__ = 'Production'\n\nimport logging\n\nlog = logging.getLogger(__name__)\n\n\ndef parsecmdline() -> argparse.Namespace:\n    \"\"\"Sets up the argument parser\"\"\"\n    parser = argparse.ArgumentParser(description='Decrypts WhatsApp backup files'\n                                                 ' encrypted with crypt12, 14 or 15')\n    parser.add_argument('keyfile', nargs='?', type=str, default=\"encrypted_backup.key\",\n                        help='The WhatsApp encrypted_backup key file or the hex encoded key. '\n                             'Default: encrypted_backup.key')\n    parser.add_argument('encrypted', nargs='?', type=argparse.FileType('rb'), default=\"msgstore.db.crypt15\",\n                        help='The encrypted crypt12, 14 or 15 file. Default: msgstore.db.crypt15')\n    parser.add_argument('decrypted', nargs='?', type=argparse.FileType('wb'), default=\"msgstore.db\",\n                        help='The decrypted output file. Default: msgstore.db')\n    parser.add_argument('-nm', '--no-mem', action='store_true',\n                        help='Does not load files in RAM, stresses the disk more. '\n                             'Default: load files into RAM')\n    parser.add_argument('-bs', '--buffer-size', type=int, help='How many bytes of data to process at a time. '\n                                                               'Implies -nm. Default: {}'.format(\n        io.DEFAULT_BUFFER_SIZE))\n    parser.add_argument('-nd', '--no-decompress', action='store_true',\n                        help='Does not decompress the decrypted data. '\n                             'Default: decompresses the decrypted data')\n    parser.add_argument('-v', '--verbose', action='store_true', help='Prints all offsets and messages')\n    parser.add_argument('-f', '--force', action='store_true', help='Does nothing, but it is here for compatibility')\n\n    return parser.parse_args()\n\n\ndef chunked_decrypt(file_hash, cipher, encrypted, decrypted, buffer_size: int = 0, no_decompress: bool = False):\n    \"\"\"\n    Does the actual decryption chunking bytes, so the file does not get loaded into RAM.\n    \"\"\"\n\n    z_obj = zlib.decompressobj()\n\n    if cipher is None:\n        log.fatal(\"Could not create a decryption cipher\")\n\n    try:\n\n        if buffer_size < 17:\n            log.info(\"Invalid buffer size, will use default of {}\".format(io.DEFAULT_BUFFER_SIZE))\n            buffer_size = io.DEFAULT_BUFFER_SIZE\n\n        # Does the thing above but only with DEFAULT_BUFFER_SIZE bytes at a time.\n        # Less RAM used, more I/O used\n\n        is_zip = True\n\n        # Read the first data chunk (there must be at least one, otherwise the\n        # encrypted file is clearly malformed).\n        chunk = encrypted.read(buffer_size)\n\n        log.debug(\"Reading and decrypting...\")\n\n        if not chunk:\n            log.error(\"Encrypted file is empty or truncated.\")\n        else:\n            while True:\n                # We will need to manage two chunks at a time, because we might have\n                # the checksum in both the last chunk and the chunk before that.\n                # This makes the logic more complicated, but it's the only way to.\n\n                checksum = None\n\n                try:\n                    next_chunk = encrypted.read(buffer_size)\n                except MemoryError:\n                    log.fatal(\"Out of RAM, please use a smaller buffer size.\")\n                    break\n\n                if len(next_chunk) <= 36:\n                    # Last bytes read. Three cases:\n                    # 1. The checksum is entirely in the last chunk\n                    if len(next_chunk) == 36:\n                        checksum = next_chunk\n                    # 2. The checksum is entirely in the chunk before the last\n                    elif len(next_chunk) == 0:\n                        checksum = chunk[-36:]\n                        chunk = chunk[:-36]\n                    # 3. The checksum is split between the last two chunks\n                    else:\n                        checksum = chunk[-(36 - len(next_chunk)):] + next_chunk\n                        chunk = chunk[:-(36 - len(next_chunk))]\n\n                file_hash.update(chunk)\n\n                decrypted_chunk = cipher.decrypt(chunk)\n                if is_zip:\n                    try:\n                        if no_decompress:\n                            decrypted.write(decrypted_chunk)\n                        else:\n                            decrypted.write(z_obj.decompress(decrypted_chunk))\n                    except zlib.error:\n                        if test_decompression(decrypted_chunk):\n                            log.info(\"Decrypted data is a ZIP file that I will not decompress automatically.\")\n                        else:\n                            log.error(\"I can't recognize decrypted data. Decryption not successful.\\n    \"\n                                      \"The key probably does not match with the encrypted file.\")\n                        is_zip = False\n                        decrypted.write(decrypted_chunk)\n                else:\n                    decrypted.write(decrypted_chunk)\n\n                # The presence of the checksum tells us it's the last chunk\n                if checksum is not None:\n                    is_multifile_backup = False\n\n                    crypt12_footer = str(checksum[-4:])\n                    jid = findall(r\"(?:-|\\d)(?:-|\\d)(\\d\\d)\", crypt12_footer)\n                    if len(jid) == 1:\n                        # Confirmed to be crypt12\n                        checksum = checksum[:-4]\n                        log.debug(\"Your phone number ends with {}\".format(jid[0]))\n                    else:\n                        # Shift everything forward by 4 bytes\n                        chunk = checksum[:4]\n                        file_hash.update(chunk)\n                        decrypted_chunk = cipher.decrypt(chunk)\n                        if is_zip:\n                            try:\n                                if no_decompress:\n                                    decrypted.write(decrypted_chunk)\n                                else:\n                                    decrypted.write(z_obj.decompress(decrypted_chunk))\n                            except zlib.error:\n                                log.error(\"Backup is corrupted.\")\n                                decrypted.write(decrypted_chunk)\n                        else:\n                            decrypted.write(decrypted_chunk)\n                        checksum = checksum[4:]\n\n                    file_hash.update(checksum[:16])\n                    if file_hash.digest() != checksum[16:]:\n                        is_multifile_backup = True\n                    else:\n                        log.debug(\"Checksum OK ({})!\".format(file_hash.hexdigest()))\n                    try:\n                        if is_multifile_backup:\n                            decrypted.write(cipher.decrypt(checksum[:16]))\n                            cipher.verify(checksum[16:])\n                        else:\n                            cipher.verify(checksum[:16])\n                    except ValueError as e:\n                        log.error(\"Authentication tag mismatch: {}.\"\n                                  \"\\n    This probably means your backup is corrupted.\".format(e))\n                    break\n\n                # If there is no more data, we should already have seen a checksum.\n                if not next_chunk:\n                    log.error(\"The encrypted database file is truncated (no checksum found).\")\n                    break\n\n                # Move the sliding window forward.\n                chunk = next_chunk\n\n        if is_zip and not no_decompress and not z_obj.eof:\n            log.error(\"The encrypted database file is truncated (damaged).\")\n\n        decrypted.flush()\n\n    except OSError as e:\n        log.fatal(\"I/O error: {}\".format(e))\n\n    finally:\n        decrypted.close()\n        encrypted.close()\n\n\ndef main():\n    args = parsecmdline()\n\n    # set wa_crypt_tools l to debug\n    log.setLevel(logging.DEBUG if args.verbose else logging.INFO)\n    ch = logging.StreamHandler()\n    ch.setLevel(logging.DEBUG if args.verbose else logging.INFO)\n    ch.setFormatter(CustomFormatter())\n    log.addHandler(ch)\n    # also add to \"wa_crypt_tools.lib\" logger\n    logging.getLogger(\"wa_crypt_tools.lib\").addHandler(ch)\n    logging.getLogger(\"wa_crypt_tools.lib\").setLevel(logging.DEBUG if args.verbose else logging.INFO)\n    if args.buffer_size is not None:\n        if not 1 < args.buffer_size < maxsize:\n            log.fatal(\"Invalid buffer size\")\n    # Get the decryption key from the key file or the hex encoded string.\n    key = KeyFactory.new(args.keyfile)\n    log.debug(str(key))\n\n    db = DatabaseFactory.from_file(args.encrypted)\n    cipher = AES.new(key.get(), AES.MODE_GCM, db.get_iv())\n\n    if args.buffer_size is not None:\n        chunked_decrypt(db.file_hash, cipher, args.encrypted, args.decrypted, args.buffer_size, args.no_decompress)\n    elif args.no_mem:\n        chunked_decrypt(db.file_hash, cipher, args.encrypted, args.decrypted, io.DEFAULT_BUFFER_SIZE,\n                        args.no_decompress)\n    else:\n        output_decrypted: bytearray = db.decrypt(key, args.encrypted.read())\n        try:\n\n            z_obj = zlib.decompressobj()\n            if args.no_decompress:\n                output_file = output_decrypted\n            else:\n                output_file = z_obj.decompress(output_decrypted)\n                if not z_obj.eof:\n                    log.error(\"The encrypted database file is truncated (damaged).\")\n        except zlib.error:\n            output_file = output_decrypted\n            if test_decompression(output_file[:io.DEFAULT_BUFFER_SIZE]):\n                log.info(\"Decrypted data is a ZIP file that I will not decompress automatically.\")\n            else:\n                log.error(\"I can't recognize decrypted data. Decryption not successful.\\n    \"\n                        \"The key probably does not match with the encrypted file.\\n    \"\n                        \"Or the backup is simply empty. (check with --force)\")\n        args.decrypted.write(output_file)\n\n    if date.today().day == 1 and date.today().month == 4:\n        log.info(\"Done. Uploading messages to the developer's server...\")\n        sleep(0.5)\n        log.info(\"Uploaded. The developer will now read and publish your messages!\")\n    else:\n        log.info(\"Done\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "src/wa_crypt_tools/waencrypt.py",
    "content": "import argparse\nimport hashlib\nimport os\nimport zlib\nimport logging\n\nfrom wa_crypt_tools.lib.constants import C\nfrom wa_crypt_tools.lib.db.db import Database\nfrom wa_crypt_tools.lib.db.db12 import Database12\nfrom wa_crypt_tools.lib.db.db14 import Database14\nfrom wa_crypt_tools.lib.db.db15 import Database15\nfrom wa_crypt_tools.lib.db.dbfactory import DatabaseFactory\nfrom wa_crypt_tools.lib.key.key import Key\nfrom wa_crypt_tools.lib.key.keyfactory import KeyFactory\nfrom wa_crypt_tools.lib.logformat import CustomFormatter\nfrom wa_crypt_tools.lib.props import Props\n\nlog = logging.getLogger(__name__)\n\n\ndef parsecmdline() -> argparse.Namespace:\n    \"\"\"Parses the command line arguments.\"\"\"\n    \"\"\"Sets up the argument parser\"\"\"\n    parser = argparse.ArgumentParser(description='Encrypts a file in Crypt14 or Crypt15 format.')\n    parser.add_argument('keyfile', nargs='?', type=str, default=\"encrypted_backup.key\",\n                        help='The WhatsApp encrypted_backup key file or the hex encoded key. '\n                             'Default: encrypted_backup.key')\n    parser.add_argument('decrypted', nargs='?', type=argparse.FileType('rb'), default=\"msgstore.db\",\n                        help='The input file. Default: msgstore.db')\n    parser.add_argument('encrypted', nargs='?', type=argparse.FileType('wb'), default=\"msgstore.db.crypt15\",\n                        help='The encrypted crypt15 or crypt14 file. Default: msgstore.db.crypt15')\n    parser.add_argument('-f', '--force', action='store_true',\n                        help='Makes errors non fatal. Default: false')\n    parser.add_argument('-v', '--verbose', action='store_true', help='Prints all offsets and messages')\n    parser.add_argument('--enable-features', type=int, nargs='*', default=C.DEFAULT_FEATURE_LIST,\n                        help='Enables the specified features. ')\n    parser.add_argument('--max-feature', type=int, default=39,\n                        help='The max feature number, the older is the backup the lower should be the number. ')\n    parser.add_argument('--multi-file', action='store_true',\n                        help='Encrypts a multi-file backup (either stickers or wallpapers)')\n    parser.add_argument('--type', type=int, choices=[12, 14, 15], default=15,\n                        help='The type of encryption to use. Default: 15')\n    parser.add_argument('--iv', type=str, help='The IV to use for crypt15 encryption. Default: random')\n    parser.add_argument('--reference', type=argparse.FileType('rb'),\n                        help='The reference file to use for crypt15 encryption. Highly recommended.')\n    parser.add_argument('--noparse', action='store_true',\n                        help='Do not parse the header of the reference file. Default: false')\n    parser.add_argument('--wa-version', type=str, default=C.DEFAULT_APP_VERSION,\n                        help='The WhatsApp version to use for crypt15 encryption. Default:' +\n                             C.DEFAULT_APP_VERSION)\n    parser.add_argument('--jid', type=str, default=C.DEFAULT_JID_SUFFIX,\n                        help='The last 2 numbers of your phone number. Default: 00')\n    parser.add_argument('--backup-version', type=int, default=C.DEFAULT_BACKUP_VERSION,\n                        help='The backup version to use in the header of the encrypted file. Default: 0')\n    parser.add_argument('--no-compress', action='store_true',\n                        help='Do not compress the file. This will make the backup not working. Only used in development. Default: false')\n    return parser.parse_args()\n\n\ndef main():\n    \"\"\"Main function\"\"\"\n    # Parse the command line arguments\n    args = parsecmdline()\n    # set wa_crypt_tools l to debug\n    log.setLevel(logging.DEBUG if args.verbose else logging.INFO)\n    ch = logging.StreamHandler()\n    ch.setLevel(logging.DEBUG if args.verbose else logging.INFO)\n    ch.setFormatter(CustomFormatter())\n    log.addHandler(ch)\n    log.warning(\"This script is in beta stage\")\n\n    # Read the key file\n    key = KeyFactory.new(args.keyfile)\n    # If specified, use the IV from the command line\n    iv = None\n    props = None\n    if not args.reference:\n        if args.iv:\n            iv = bytes.fromhex(args.iv)\n        # Create the props object from the command line arguments\n        props = Props(wa_version=args.wa_version, jid=args.jid, max_feature=args.max_feature,\n                      features=args.enable_features, backup_version=args.backup_version)\n    else:\n        reference = DatabaseFactory.from_file(args.reference)\n        iv: bytes = reference.get_iv()\n        props = reference.props\n    data = args.decrypted.read()\n    if args.type == 15:\n        db = Database15(key=key, iv=iv)\n    elif args.type == 14:\n        db = Database14(key=key, iv=iv)\n    else:\n        db = Database12(key=key, iv=iv)\n    if args.no_compress:\n        encrypted = db.encrypt(key, props, data)\n    else:\n        compressed = zlib.compress(data, 1)\n        encrypted = db.encrypt(key, props, compressed)\n    args.encrypted.write(encrypted)\n    # Close the files\n    log.info(\"Done!\")\n    args.decrypted.close()\n    args.encrypted.close()\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "src/wa_crypt_tools/waguess.py",
    "content": "# AES import party!\n# pycryptodome and PyCryptodomex's implementations of AES are the same,\n# so we try to import one of these twos.\nimport argparse\nimport io\nimport zlib\nfrom datetime import date\nfrom re import findall\n\nimport logging\nfrom time import sleep\n\nfrom wa_crypt_tools.lib.constants import C\nfrom wa_crypt_tools.lib.key.keyfactory import KeyFactory\nfrom wa_crypt_tools.lib.logformat import CustomFormatter\nfrom wa_crypt_tools.lib.utils import test_decompression\n\nlog = logging.getLogger(__name__)\n\n# AES import party!\n# pycryptodome and PyCryptodomex's implementations of AES are the same,\n# so we try to import one of these twos.\ntry:\n    # pycryptodomex\n    from Cryptodome.Cipher import AES\nexcept ModuleNotFoundError:\n    try:\n        # pycryptodome\n        # noinspection PyUnresolvedReferences\n        from Crypto.Cipher import AES\n\n        if not hasattr(AES, 'MODE_GCM'):\n            # pycrypto\n            raise ModuleNotFoundError(\"You installed pycrypto and not pycryptodome(x). \"\n                                      \"Pycrypto is old, deprecated and not supported. \\n\"\n                                      \"Run: python -m pip uninstall pycrypto\\n\"\n                                      \"And: python -m pip install pycryptodomex\\n\"\n                                      \"Or:  python -m pip install pycryptodome\")\n    except ModuleNotFoundError:\n        # crypto (or nothing)\n        raise ModuleNotFoundError(\"You need pycryptodome(x) to run these scripts!\\n\"\n                                  \"python -m pip install pycryptodome\\n\"\n                                  \"Or: python -m pip install pycryptodome\\n\"\n                                  \"You can also remove \\\"crypto\\\" if you have it installed\\n\"\n                                  \"python -m pip uninstall crypto\")\n\n\ndef oscillate(n: int, n_min: int, n_max: int):\n    \"\"\"Yields n, n-1, n+1, n-2, n+2..., with constraints:\n    - n is in [min, max]\n    - n is never negative\n    Reverts to range() when n touches min or max. Example:\n    oscillate(8, 2, 10) => 8, 7, 9, 6, 10, 5, 4, 3, 2\n    \"\"\"\n\n    if n_min < 0:\n        n_min = 0\n\n    i = n\n    c = 1\n\n    # First phase (n, n-1, n+1...)\n    while True:\n\n        if i == n_max:\n            break\n        yield i\n        i -= c\n        c += 1\n\n        if i == 0 or i == n_min:\n            break\n        yield i\n        i += c\n        c += 1\n\n    # Second phase (range of remaining numbers)\n    # n != i/2 fixes a bug where we would yield min and max two times if n == (max-min)/2\n    if i == n_min and n != i / 2:\n\n        yield i\n        i += c\n        for j in range(i, n_max + 1):\n            yield j\n\n    if i == n_max and n != i / 2:\n\n        yield n_max\n        i -= c\n        for j in range(i, n_min - 1, -1):\n            yield j\n\n\ndef find_data_offset(header: bytes, iv_offset: int, key: bytes, starting_data_offset: int) -> int:\n    \"\"\"Tries to find the offset in which the encrypted data starts.\n    Returns the offset or -1 if the offset is not found.\n    Only works with ZLIB stream, not with ZIP file.\"\"\"\n\n    iv = header[iv_offset:iv_offset + 16]\n\n    # oscillate ensures we try the closest values to the default value first.\n    for i in oscillate(n=starting_data_offset, n_min=iv_offset + len(iv), n_max=C.HEADER_SIZE - 128):\n\n        cipher = AES.new(key, AES.MODE_GCM, iv)\n\n        # We only decrypt the first two bytes.\n        test_bytes = cipher.decrypt(header[i:i + 2])\n\n        for zheader in C.ZLIB_HEADERS:\n\n            if test_bytes == zheader:\n                # We found a match, but this might also happen by chance.\n                # Let's run another test by decrypting some hundreds of bytes.\n                # We need to reinitialize the cipher everytime as it has an internal status.\n                cipher = AES.new(key, AES.MODE_GCM, iv)\n                decrypted = cipher.decrypt(header[i:])\n                if test_decompression(decrypted):\n                    return i\n    return -1\n\n\ndef guess_offsets(key: bytes, encrypted: io.BufferedReader, def_iv_offset: int,\n                  def_data_offset: int):\n    \"\"\"Gets the IV, shifts the stream to the beginning of the encrypted data and returns the cipher.\n    It does so by guessing the offset.\"\"\"\n\n    # Assign variables to suppress warnings\n    db_header, data_offset, iv_offset = None, None, None\n\n    # Restart the file stream\n    encrypted.seek(0)\n\n    db_header = encrypted.read(C.HEADER_SIZE)\n    if len(db_header) < C.HEADER_SIZE:\n        log.fatal(\"The encrypted database is too small.\\n    \"\n                  \"Did you swap the keyfile and the encrypted database file by mistake?\")\n\n    try:\n        if db_header[:15].decode('ascii') == 'SQLite format 3':\n            log.error(\"The database file is not encrypted.\\n    \"\n                      \"Did you swap the input and the output files by mistake?\")\n    except ValueError:\n        pass\n\n    # Finding WhatsApp's version is nice\n    version = findall(b\"\\\\d(?:\\\\.\\\\d{1,3}){3}\", db_header)\n    if len(version) != 1:\n        log.info('WhatsApp version not found (Crypt12?)')\n    else:\n        log.debug(\"WhatsApp version: {}\".format(version[0].decode('ascii')))\n\n    # Determine IV offset and data offset.\n    for iv_offset in oscillate(n=def_iv_offset, n_min=0, n_max=C.HEADER_SIZE - 128):\n        data_offset = find_data_offset(db_header, iv_offset, key, def_data_offset)\n        if data_offset != -1:\n            log.info(\"Offsets guessed (IV: {}, data: {}).\".format(iv_offset, data_offset))\n            if iv_offset != def_iv_offset or data_offset != def_data_offset:\n                log.info(\"Next time, use -ivo {} -do {} for guess-free decryption\".format(iv_offset, data_offset))\n            break\n    if data_offset == -1:\n        return None\n\n    iv = db_header[iv_offset:iv_offset + 16]\n\n    encrypted.seek(data_offset)\n\n    return AES.new(key, AES.MODE_GCM, iv)\n\n\ndef parsecmdline() -> argparse.Namespace:\n    \"\"\"Sets up the argument parser\"\"\"\n    parser = argparse.ArgumentParser(description='Decrypts WhatsApp backup files'\n                                                 ' encrypted with crypt12, 14 or 15')\n    parser.add_argument('keyfile', nargs='?', type=str, default=\"encrypted_backup.key\",\n                        help='The WhatsApp encrypted_backup key file or the hex encoded key. '\n                             'Default: encrypted_backup.key')\n    parser.add_argument('encrypted', nargs='?', type=argparse.FileType('rb'), default=\"msgstore.db.crypt15\",\n                        help='The encrypted crypt12, 14 or 15 file. Default: msgstore.db.crypt15')\n    parser.add_argument('decrypted', nargs='?', type=argparse.FileType('wb'), default=\"msgstore.db\",\n                        help='The decrypted output file. Default: msgstore.db')\n    parser.add_argument('-ivo', '--iv-offset', type=int, default=C.DEFAULT_IV_OFFSET,\n                        help='The default offset of the IV in the encrypted file. '\n                             'Default: {}'.format(C.DEFAULT_IV_OFFSET))\n    parser.add_argument('-do', '--data-offset', type=int, default=C.DEFAULT_DATA_OFFSET,\n                        help='The default offset of the encrypted data in the encrypted file. '\n                             'Default: {}'.format(C.DEFAULT_DATA_OFFSET))\n    parser.add_argument('-v', '--verbose', action='store_true', help='Prints all offsets and messages')\n\n    return parser.parse_args()\n\n\ndef decrypt(cipher, encrypted, decrypted):\n    \"\"\"Does the actual decryption.\"\"\"\n\n    z_obj = zlib.decompressobj()\n\n    if cipher is None:\n        log.fatal(\"Could not create a decryption cipher\")\n\n    try:\n\n        try:\n            encrypted_data = encrypted.read()\n            # Crypt12 moment: the last 4 bytes are --xx, where xx\n            # are the last 2 numbers of the jid (user's phone number).\n            # We need to remove them.\n\n            try:\n                output_decrypted: bytearray = cipher.decrypt(encrypted_data)\n            except ValueError as e:\n                log.fatal(\"Decryption failed: {}.\"\n                          \"\\n    This probably means your backup is corrupted.\".format(e))\n                # Dead code to make pycharm warning go away\n                exit(1)\n\n            try:\n                output_file = z_obj.decompress(output_decrypted)\n                if not z_obj.eof:\n                    log.error(\"The encrypted database file is truncated (damaged).\")\n            except zlib.error:\n                output_file = output_decrypted\n                if test_decompression(output_file[:io.DEFAULT_BUFFER_SIZE]):\n                    log.info(\"Decrypted data is a ZIP file that I will not decompress automatically.\")\n                else:\n                    log.error(\"I can't recognize decrypted data. Decryption not successful.\\n    \"\n                              \"The key probably does not match with the encrypted file.\\n    \"\n                              \"Or the backup is simply empty. (check with --force)\")\n\n            decrypted.write(output_file)\n\n        except MemoryError:\n            log.fatal(\"Out of RAM, please use -nm.\")\n\n        decrypted.flush()\n\n    except OSError as e:\n        log.fatal(\"I/O error: {}\".format(e))\n\n    finally:\n        decrypted.close()\n        encrypted.close()\n\n\ndef main():\n    args = parsecmdline()\n\n    # set wa_crypt_tools l to debug\n    log.setLevel(logging.DEBUG if args.verbose else logging.INFO)\n    ch = logging.StreamHandler()\n    ch.setLevel(logging.DEBUG if args.verbose else logging.INFO)\n    ch.setFormatter(CustomFormatter())\n    log.addHandler(ch)\n    if not (0 < args.data_offset < C.HEADER_SIZE - 128):\n        log.fatal(\"The data offset must be between 1 and {}\".format(C.HEADER_SIZE - 129))\n    if not (0 < args.iv_offset < C.HEADER_SIZE - 128):\n        log.fatal(\"The IV offset must be between 1 and {}\".format(C.HEADER_SIZE - 129))\n    # Get the decryption key from the key file or the hex encoded string.\n    key = KeyFactory.new(args.keyfile)\n    log.debug(str(key))\n\n    cipher = guess_offsets(key=key.get(), encrypted=args.encrypted,\n                           def_iv_offset=args.iv_offset, def_data_offset=args.data_offset)\n\n    decrypt(cipher, args.encrypted, args.decrypted)\n\n    if date.today().day == 1 and date.today().month == 4:\n        log.info(\"Done. Uploading messages to the developer's server...\")\n        sleep(0.5)\n        log.info(\"Uploaded. The developer will now read and publish your messages!\")\n    else:\n        log.info(\"Done\")\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "src/wa_crypt_tools/wainfo.py",
    "content": "#!/usr/bin/env python\n\"\"\"\nThis script prints info on WhatsApp's DB files.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom wa_crypt_tools.lib.logformat import CustomFormatter\nfrom wa_crypt_tools.lib.db.dbfactory import DatabaseFactory\nfrom wa_crypt_tools.lib.key.keyfactory import KeyFactory\n\nimport argparse\n\n__author__ = 'ElDavo'\n__copyright__ = 'Copyright (C) 2024'\n__license__ = 'GPLv3'\n__status__ = 'Beta'\n\nimport logging\n\nlog = logging.getLogger(__name__)\n\n\ndef parsecmdline() -> argparse.Namespace:\n    \"\"\"Sets up the argument parser\"\"\"\n    parser = argparse.ArgumentParser(description='Prints info on whatsapp crypted files')\n    parser.add_argument('encrypted', nargs='?',\n                        type=str,\n                        default=\"msgstore.db.crypt15\",\n                        help='The encrypted crypt12, 14 or 15 file. Default: msgstore.db.crypt15')\n    parser.add_argument('-k', '--key',\n                        action='store_true',\n                        help='tell the program that the file is a key file')\n    return parser.parse_args()\n\n\ndef main():\n    args = parsecmdline()\n\n    # set wa_crypt_tools l to debug\n    log.setLevel(logging.DEBUG)\n    ch = logging.StreamHandler()\n    ch.setLevel(logging.DEBUG)\n    ch.setFormatter(CustomFormatter())\n    log.addHandler(ch)\n    # also add to \"wa_crypt_tools.lib\" logger\n    logging.getLogger(\"wa_crypt_tools.lib\").addHandler(ch)\n    logging.getLogger(\"wa_crypt_tools.lib\").setLevel(logging.DEBUG)\n\n    log.warning(\"This script is in beta stage.\")\n\n    if args.key:\n        key = KeyFactory.from_file(args.encrypted)\n        print(key)\n        return\n    try:\n        DatabaseFactory.from_file(open(args.encrypted, 'rb'))\n    except Exception as e:\n        log.error(\"Error: {}\".format(e))\n        return\n        # TODO\n    # print(db)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "tests/__init__.py",
    "content": ""
  },
  {
    "path": "tests/lib/__init__.py",
    "content": ""
  },
  {
    "path": "tests/lib/db/__init__.py",
    "content": ""
  },
  {
    "path": "tests/lib/db/test_db.py",
    "content": "\nclass TestDatabase():\n    pass\n"
  },
  {
    "path": "tests/lib/test_constants.py",
    "content": "from wa_crypt_tools.lib.constants import C\n\n\nclass TestConstants:\n    def test_zip_header(self):\n        assert C.ZIP_HEADER == b'PK\\x03\\x04'\n"
  },
  {
    "path": "tests/lib/test_utils.py",
    "content": "from wa_crypt_tools.lib.utils import hexstring2bytes\n\n\nclass TestUtils:\n    # Sample test to test the test infrastructure (!)\n    def test_hexstring2bytes(self):\n        assert hexstring2bytes(\"0\"*64) == b'\\x00' * 32\n"
  },
  {
    "path": "tests/res/test.json",
    "content": "{\n  \"test_json\": \"A JSON file that is not a SQLite database nor a ZIP file\"\n}"
  },
  {
    "path": "tests/test_createkey.py",
    "content": "import os\nimport zlib\n\nfrom wa_crypt_tools.lib.key.key15 import Key15\nfrom wa_crypt_tools.lib.key.key14 import Key14\nfrom wa_crypt_tools.lib.key.keyfactory import KeyFactory\nfrom wa_crypt_tools.lib.props import Props\nfrom hashlib import sha512\n\n\nclass TestCreatekey:\n    def test_createkey(self):\n        key: Key15 = Key15(key=\n        bytes.fromhex(\n            '6730a595a1484d0c39c101dc0ac82ec5e401bb6f0e1b8ee2dc104a6b3687f017'\n        ))\n        keyb: bytes = key.dump()\n        keyb_digest = sha512(keyb).digest()\n        with open(\"tests/res/encrypted_backup.key\", 'rb') as f:\n            orig_check = sha512(f.read()).digest()\n        assert keyb_digest == orig_check\n\n    def test_createkey14(self):\n        key: Key14 = Key14(key=\n        bytes.fromhex(\n            '3a146d9bbd8b6311d962c71619c0c2cce3ce694ea4a0f3f600e271380e1226c6'\n        ),\n            serversalt=bytes.fromhex('cd788b1b4625f50d3fccdeac94e1ff638899733b77a224ff614918363901f044'),\n            googleid=bytes.fromhex('92683e735c88727eef9486911f3ac6fa'),\n            key_version=b'\\x02',\n            cipher_version=b'\\x00\\x01')\n        keyb: bytes = key.dump()\n        with open(\"tests/res/key\", 'rb') as f:\n            assert keyb == f.read()\n"
  },
  {
    "path": "tests/test_decrypt.py",
    "content": "import os\nimport zlib\n\nfrom wa_crypt_tools.lib.db.db12 import Database12\nfrom wa_crypt_tools.lib.db.db14 import Database14\nfrom wa_crypt_tools.lib.db.db15 import Database15\nfrom wa_crypt_tools.lib.db.dbfactory import DatabaseFactory\nfrom wa_crypt_tools.lib.key.keyfactory import KeyFactory\nfrom wa_crypt_tools.lib.props import Props\nfrom hashlib import sha512\n\nclass TestDecryption:\n    def test_decryption15(self):\n        key = KeyFactory.new(\"tests/res/encrypted_backup.key\")\n        f = open(\"tests/res/msgstore.db.crypt15\",'rb')\n        db = DatabaseFactory.from_file(f)\n        encrypted = f.read()\n        decrypted_db = db.decrypt(key, encrypted)\n        decrypted_db = zlib.decompress(decrypted_db)\n        new_check = sha512(decrypted_db).digest()\n        with open(\"tests/res/msgstore.db\", 'rb') as f:\n            orig_check = sha512(f.read()).digest()\n        assert new_check == orig_check\n    \n    def test_decryption14(self):\n        key = KeyFactory.new(\"tests/res/key\")\n        f = open(\"tests/res/msgstore.db.crypt14\",'rb')\n        db = DatabaseFactory.from_file(f)\n        encrypted = f.read()\n        decrypted_db = db.decrypt(key, encrypted)\n        decrypted_db = zlib.decompress(decrypted_db)\n        new_check = sha512(decrypted_db).digest()\n        with open(\"tests/res/msgstore.db\", 'rb') as f:\n            orig_check = sha512(f.read()).digest()\n        assert new_check == orig_check\n        \n    def test_decryption12(self):\n        key = KeyFactory.new(\"tests/res/key\")\n        f = open(\"tests/res/msgstore.db.crypt12\",'rb')\n        db = DatabaseFactory.from_file(f)\n        encrypted = f.read()\n        decrypted_db = db.decrypt(key, encrypted)\n        decrypted_db = zlib.decompress(decrypted_db)\n        new_check = sha512(decrypted_db).digest()\n        with open(\"tests/res/msgstore.db\", 'rb') as f:\n            orig_check = sha512(f.read()).digest()\n        assert new_check == orig_check"
  },
  {
    "path": "tests/test_encrypt.py",
    "content": "import os\nimport zlib\n\nfrom wa_crypt_tools.lib.db.db12 import Database12\nfrom wa_crypt_tools.lib.db.db14 import Database14\nfrom wa_crypt_tools.lib.db.db15 import Database15\nfrom wa_crypt_tools.lib.key.keyfactory import KeyFactory\nfrom wa_crypt_tools.lib.props import Props\nfrom hashlib import sha512\n\n\nclass TestEncryption:\n    def test_encryption15(self):\n        key = KeyFactory.new(\"tests/res/encrypted_backup.key\")\n        props = Props(wa_version=\"2.22.5.13\", jid=\"67\", features=[5, 7, 8, 13, 14, 19, 22, 25, 28, 30, 31, 32, 36, 37],\n                      max_feature=37)\n        db = Database15(key=key, iv=bytes.fromhex(\"C395EE009CF8B68AC0EA760550F6559C\"))\n        data = db.encrypt(\n            key,\n            props,\n            zlib.compress(\n                open(\"tests/res/msgstore.db\", 'rb').read(),\n                level=1,\n            )\n        )\n        new_check = sha512(data).digest()\n        with open(\"tests/res/msgstore-new.db.crypt15\", 'wb') as f:\n            f.write(data)\n        with open(\"tests/res/msgstore.db.crypt15\", 'rb') as f:\n            orig_check = sha512(f.read()).digest()\n        assert new_check == orig_check\n        os.remove(\"tests/res/msgstore-new.db.crypt15\")\n\n    def test_encryption14(self):\n        key = KeyFactory.new(\"tests/res/key\")\n        props = Props(wa_version=\"2.22.5.13\", jid=\"67\", features=[5, 7, 8, 13, 14, 19, 22, 25, 28, 30, 31, 32, 36, 37],\n                      max_feature=37)\n        db = Database14(key=key, iv=bytes.fromhex(\"EA53CEAE36ECAB50BC331AEB62491625\"))\n        data = db.encrypt(\n            key,\n            props,\n            zlib.compress(\n                open(\"tests/res/msgstore.db\", 'rb').read(),\n                level=1,\n            )\n        )\n        new_check = sha512(data).digest()\n        with open(\"tests/res/msgstore-new.db.crypt14\", 'wb') as f:\n            f.write(data)\n        with open(\"tests/res/msgstore.db.crypt14\", 'rb') as f:\n            orig_check = sha512(f.read()).digest()\n        assert new_check == orig_check\n        os.remove(\"tests/res/msgstore-new.db.crypt14\")\n\n    def test_encryption14_noexpiry(self):\n        key = KeyFactory.new(\"tests/res/key\")\n        props = Props(wa_version=\"2.22.5.13\", jid=\"67\", features=None)\n        db = Database14(key=key, iv=bytes.fromhex(\"EA53CEAE36ECAB50BC331AEB62491625\"))\n        data = db.encrypt(\n            key,\n            props,\n            zlib.compress(\n                open(\"tests/res/msgstore.db\", 'rb').read(),\n                level=1,\n            )\n        )\n        new_check = sha512(data).digest()\n        with open(\"tests/res/msgstore-new.db.crypt14\", 'wb') as f:\n            f.write(data)\n        with open(\"tests/res/msgstore-noexpiry.db.crypt14\", 'rb') as f:\n            orig_check = sha512(f.read()).digest()\n        assert new_check == orig_check\n        os.remove(\"tests/res/msgstore-new.db.crypt14\")\n\n    def test_encryption12(self):\n        key = KeyFactory.new(\"tests/res/key\")\n        props = Props(wa_version=\"2.22.5.13\", jid=\"67\", features=None)\n        db = Database12(key=key, iv=bytes.fromhex(\"F4E9A6DC0B6F0D8986AF6C7180F02356\"))\n        data = db.encrypt(\n            key,\n            props,\n            zlib.compress(\n                open(\"tests/res/msgstore.db\", 'rb').read(),\n                level=1,\n            )\n        )\n        new_check = sha512(data).digest()\n        with open(\"tests/res/msgstore-new.db.crypt12\", 'wb') as f:\n            f.write(data)\n        with open(\"tests/res/msgstore.db.crypt12\", 'rb') as f:\n            orig_check = sha512(f.read()).digest()\n        assert new_check == orig_check\n        os.remove(\"tests/res/msgstore-new.db.crypt12\")\n"
  },
  {
    "path": "tests/tools-invocation/test_wacreatekey.py",
    "content": "from os.path import exists\nfrom hashlib import sha512\n\nfrom wa_crypt_tools.lib.key.key15 import Key15\nfrom wa_crypt_tools.lib.key.keyfactory import KeyFactory\n\nfrom tests.utils.utils import Propen, cmp_files, rm_if_found\n\n\nclass TestWaCreateKey:\n    def test_no_input(self):\n        assert not exists(\"encrypted_backup.key\")\n        try:\n            out, ret = Propen(\"wacreatekey\")\n            assert ret == 0\n            assert \"Key file \\\"encrypted_backup.key\\\" created.\" in out\n            key: Key15 = KeyFactory.from_file(\"encrypted_backup.key\")\n        finally:\n            # cleanup\n            rm_if_found(\"encrypted_backup.key\")\n\n    def test_hex_key(self):\n        assert not exists(\"encrypted_backup.key\")\n        try:\n            out,ret  = Propen(\"wacreatekey\"\n                              \" --hex 6730a595a1484d0c39c101dc0ac82ec5e401bb6f0e1b8ee2dc104a6b3687f017\")\n            print(out)\n\n            assert ret == 0\n            assert \"Key file \\\"encrypted_backup.key\\\" created.\" in out\n            assert cmp_files(\"encrypted_backup.key\", \"tests/res/encrypted_backup.key\")\n        finally:\n            rm_if_found(\"encrypted_backup.key\")\n\n    def test_invalid_hex_key(self):\n        assert not exists(\"encrypted_backup.key\")\n        out, ret = Propen(\"wacreatekey --hex invalid\")\n        assert ret != 0\n        assert \"Key is not in hexadecimal format\" in out\n        assert not exists(\"encrypted_backup.key\")\n\n    def test_invalid_hex_key_length(self):\n        assert not exists(\"encrypted_backup.key\")\n        out, ret = Propen(\"wacreatekey --hex 00\")\n        assert ret != 0\n        assert \"Invalid key length\" in out\n        assert not exists(\"encrypted_backup.key\")\n\n    def test_custom_output(self):\n        assert not exists(\"custom.key\")\n        try:\n            out, ret = Propen(\"wacreatekey -o custom.key\")\n            assert ret == 0\n            assert \"Key file \\\"custom.key\\\" created.\" in out\n            assert exists(\"custom.key\")\n        finally:\n            rm_if_found(\"custom.key\")\n\n    def test_not_overwrite_file(self):\n        assert not exists(\"encrypted_backup.key\")\n        try:\n            Propen(\"wacreatekey\")\n            with open(\"encrypted_backup.key\", \"rb\") as f:\n                chksum = sha512(f.read()).digest()\n            out, ret = Propen(\"wacreatekey\")\n            assert ret != 0\n            assert \"The output file already exists.\" in out\n            with open(\"encrypted_backup.key\", \"rb\") as f:\n                assert chksum == sha512(f.read()).digest()\n        finally:\n            # cleanup\n            rm_if_found(\"encrypted_backup.key\")\n\n    def test_overwrite_file(self):\n        assert not exists(\"encrypted_backup.key\")\n        try:\n            Propen(\"wacreatekey\")\n            with open(\"encrypted_backup.key\", \"rb\") as f:\n                chksum = sha512(f.read()).digest()\n            out, ret = Propen(\"wacreatekey -y\")\n            assert ret == 0\n            with open(\"encrypted_backup.key\", \"rb\") as f:\n                assert chksum != sha512(f.read()).digest()\n                assert chksum != sha512(f.read()).digest()\n        finally:\n            # cleanup\n            rm_if_found(\"encrypted_backup.key\")\n\n    def test_crypt14_key(self):\n        assert not exists(\"key\")\n        try:\n            out, ret = Propen(\"wacreatekey -c14\"\n                      \" --hex 3a146d9bbd8b6311d962c71619c0c2cce3ce694ea4a0f3f600e271380e1226c6\"\n                      \" -ss cd788b1b4625f50d3fccdeac94e1ff638899733b77a224ff614918363901f044\"\n                      \" -gi 92683e735c88727eef9486911f3ac6fa\"\n                      \" -kv 2\"\n                      \" -cv 1\")\n            assert ret == 0\n            assert \"Key file \\\"key\\\" created.\" in out\n            assert cmp_files(\"key\", \"tests/res/key\")\n        finally:\n            rm_if_found(\"key\")\n\n    def call_wacreatekey_14(self, arguments):\n        assert not exists(\"key\")\n        try:\n            out, ret = Propen(arguments)\n            assert ret == 0\n            key = KeyFactory.from_file(\"key\")\n            return out\n        finally:\n            rm_if_found(\"key\")\n\n    def test_crypt14_key_not_all_parameters(self):\n        arguments=[\"wacreatekey\", \"-c14\", \"--hex\",\n                   \"3a146d9bbd8b6311d962c71619c0c2cce3ce694ea4a0f3f600e271380e1226c6\",\n                    \"-ss\", \"cd788b1b4625f50d3fccdeac94e1ff638899733b77a224ff614918363901f044\",\n                    \"-gi\", \"92683e735c88727eef9486911f3ac6fa\",\n                    \"-kv\", \"2\",\n                    \"-cv\", \"1\"]\n        # call without key\n        self.call_wacreatekey_14(arguments[:2] + arguments[4:])\n        # call without server salt\n        self.call_wacreatekey_14(arguments[:4] + arguments[6:])\n        # without google id\n        self.call_wacreatekey_14(arguments[:6] + arguments[8:])\n        # without key version\n        self.call_wacreatekey_14(arguments[:8] + arguments[10:])\n        # without cipher version\n        self.call_wacreatekey_14(arguments[:10])\n        # Some AI generated combinations below\n        self.call_wacreatekey_14(arguments[:2] + arguments[4:6] + arguments[8:])\n        self.call_wacreatekey_14(arguments[:2] + arguments[4:8] + arguments[10:])\n        self.call_wacreatekey_14(arguments[:2] + arguments[4:10])\n        self.call_wacreatekey_14(arguments[:2] + arguments[6:8] + arguments[10:])\n        self.call_wacreatekey_14(arguments[:2] + arguments[6:10])\n        self.call_wacreatekey_14(arguments[:2] + arguments[8:10])\n        self.call_wacreatekey_14(arguments[:4] + arguments[6:8] + arguments[10:])\n        self.call_wacreatekey_14(arguments[:4] + arguments[6:10])\n        self.call_wacreatekey_14(arguments[:4] + arguments[8:10])\n        self.call_wacreatekey_14(arguments[:6] + arguments[8:10])\n\n    def test_crypt14_invalid_server_salt(self):\n        assert not exists(\"key\")\n        try:\n            out, ret = Propen(\"wacreatekey -c14\"\n                              \" --hex 3a146d9bbd8b6311d962c71619c0c2cce3ce694ea4a0f3f600e271380e1226c6\"\n                              \" -ss invalid\"\n                              \" -gi 92683e735c88727eef9486911f3ac6fa\"\n                              \" -kv 2\"\n                              \" -cv 1\")\n            assert ret != 0\n            assert \"Something was not right\" in out\n            assert not exists(\"key\")\n        finally:\n            rm_if_found(\"key\")\n\n    def test_crypt14_invalid_google_id(self):\n        assert not exists(\"key\")\n        try:\n            out, ret = Propen(\"wacreatekey -c14\"\n                              \" --hex 3a146d9bbd8b6311d962c71619c0c2cce3ce694ea4a0f3f600e271380e1226c6\"\n                              \" -ss cd788b1b4625f50d3fccdeac94e1ff638899733b77a224ff614918363901f044\"\n                              \" -gi invalid\"\n                              \" -kv 2\"\n                              \" -cv 1\")\n            assert ret != 0\n            assert \"Something was not right\" in out\n        finally:\n            rm_if_found(\"key\")\n        assert not exists(\"key\")\n\n    def test_crypt14_invalid_google_id_length(self):\n        assert not exists(\"key\")\n        try:\n            out, ret = Propen(\"wacreatekey -c14\"\n                          \" --hex 3a146d9bbd8b6311d962c71619c0c2cce3ce694ea4a0f3f600e271380e1226c6\"\n                          \" -ss cd788b1b4625f50d3fccdeac94e1ff638899733b77a224ff614918363901f044\"\n                          \" -gi 92683e7eef9486911f3ac6fa00\"\n                          \" -kv 2\"\n                          \" -cv 1\")\n            assert ret != 0\n            # assert \"Invalid google id length\" in out\n            assert not exists(\"key\")\n        finally:\n            rm_if_found(\"key\")\n\n    def test_crypt14_invalid_key_version(self):\n        assert not exists(\"key\")\n        try:\n            out, ret = Propen(\"wacreatekey -c14\"\n                          \" --hex 3a146d9bbd8b6311d962c71619c0c2cce3ce694ea4a0f3f600e271380e1226c6\"\n                          \" -ss cd788b1b4625f50d3fccdeac94e1ff638899733b77a224ff614918363901f044\"\n                          \" -gi 92683e735c88727eef9486911f3ac6fa\"\n                          \" -kv invalid\"\n                          \" -cv 1\")\n            assert ret != 0\n            #assert \"usage:\" in out\n            assert not exists(\"key\")\n        finally:\n            rm_if_found(\"key\")\n\n    def test_crypt14_invalid_cipher_version(self):\n        assert not exists(\"key\")\n        out, ret = Propen(\"wacreatekey -c14\"\n                          \" --hex 3a146d9bbd8b6311d962c71619c0c2cce3ce694ea4a0f3f600e271380e1226c6\"\n                          \" -ss cd788b1b4625f50d3fccdeac94e1ff638899733b77a224ff614918363901f044\"\n                          \" -gi 92683e735c88727eef9486911f3ac6fa\"\n                          \" -kv 2\"\n                          \" -cv invalid\")\n        assert ret != 0\n        assert \"usage:\" in out\n        assert not exists(\"key\")\n"
  },
  {
    "path": "tests/utils/__init__.py",
    "content": ""
  },
  {
    "path": "tests/utils/utils.py",
    "content": "import os\nfrom hashlib import sha512\nfrom subprocess import Popen, STDOUT, PIPE\n\ndef Propen(command):\n    if isinstance(command, str):\n        command = command.split()\n    # split the command string in a list\n    p = Popen(command, stdout=PIPE, stderr=STDOUT, text=True)\n    return p.communicate()[0], p.returncode\n\ndef cmp_files(file1: str, file2: str):\n    with open(file1, 'rb') as f:\n        keyb_digest = sha512(f.read()).digest()\n    with open(file2, 'rb') as f:\n        orig_check = sha512(f.read()).digest()\n    return keyb_digest == orig_check\n\ndef rm_if_found(file: str):\n    if not os.path.exists(file):\n        return\n    if not os.path.isfile(file):\n        return\n    try:\n        os.remove(file)\n    except FileNotFoundError:\n        pass"
  },
  {
    "path": "utils/WA_HMACSHA256_Loop.java",
    "content": "package com.test;\n\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\nimport java.io.ByteArrayOutputStream;\nimport java.security.InvalidKeyException;\nimport java.security.NoSuchAlgorithmException;\n\n/*\nThe original loop WhatsApp uses to encode a encrypted_backup.key.\nTODO make a python implementation of this function.\n */\npublic class WA_HMACSHA256_Loop {\n\n    public static byte[] nestedHMACSHA256NoKey(byte[] first_iteration_data, byte[] message, int permutations) {\n        return nestedHmacSHA256(first_iteration_data, new byte[32], message, permutations);\n    }\n    public static byte[] nestedHmacSHA256(byte[] first_iteration_data, byte[] privateHmacSHA256Key, byte[] message, int permutations) {\n        try {\n            Mac hmacSHA256 = Mac.getInstance(\"HmacSHA256\");\n            hmacSHA256.init(new SecretKeySpec(privateHmacSHA256Key, \"HmacSHA256\"));\n            byte[] hmacsha256header = hmacSHA256.doFinal(first_iteration_data);\n            try {\n                /*The permutation number is actually divided by 32.\n                Be sure to give *32 the number of permutations you actually want!*/\n                int numPermutations = (int) Math.ceil(((double) permutations) / 32.0d);\n                byte[] existingData = new byte[0];\n                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n                for (int i = 1; i < numPermutations + 1; i++) {\n                    Mac hasher = Mac.getInstance(\"HmacSHA256\");\n                    hasher.init(new SecretKeySpec(hmacsha256header, \"HmacSHA256\"));\n                    hasher.update(existingData);\n                    if (message != null) {\n                        hasher.update(message);\n                    }\n                    // Mettiamoci dentro anche l'indice\n                    byte one = (byte) i;\n                    System.out.println((byte) i);\n                    hasher.update((byte) i);\n                    existingData = hasher.doFinal();\n                    int min = Math.min(permutations, existingData.length);\n                    byteArrayOutputStream.write(existingData, 0, min);\n                    permutations -= min;\n                }\n                return byteArrayOutputStream.toByteArray();\n            } catch (InvalidKeyException | NoSuchAlgorithmException e) {\n                throw new AssertionError(e);\n            }\n        } catch (InvalidKeyException | NoSuchAlgorithmException e2) {\n            throw new AssertionError(e2);\n        }\n    }\n}\n"
  },
  {
    "path": "utils/password_data_key_to_hashcat.py",
    "content": "#!/usr/bin/env python\n\"\"\"\nThis script transforms a password_data.key file into a hashcat hash.\n\"\"\"\nfrom __future__ import annotations\n\nimport argparse\n\n# noinspection PyPackageRequirements\n# This is from javaobj-py3\nimport javaobj.v2 as javaobj\n\nfrom base64 import b64encode\n\n\n# password_data.key file format:\n# The password_data.key file is a serialized Java object, composed by:\n# 1) An int (4 bytes), which should be the version of the format.\n# The only known value for now is 1, so we only support this version.\n# 2) The encoded password (32 bytes), encoded with PBKDF2-HMAC-SHA512.\n# PBKDF2 needs a salt and a permutation number, which are written after:\n# 3) The salt (32 bytes), which is a random byte array.\n# 4) The permutation number (4 bytes), which is an int. For now seems to be fixed at 100000.\n# The script parses the permutation number for the file, so if it changes, no problem.\n\nclass Log:\n    \"\"\"Simpler logger class. Supports 2 verbosity levels.\"\"\"\n\n    @staticmethod\n    def i(msg: str):\n        \"\"\"Always prints message.\"\"\"\n        print('[I] {}'.format(msg))\n\n    @staticmethod\n    def f(msg: str):\n        \"\"\"Always prints message and exit.\"\"\"\n        print('[F] {}'.format(msg))\n        exit(1)\n\n\ndef parsecmdline() -> argparse.Namespace:\n    \"\"\"Sets up the argument parser\"\"\"\n    parser = argparse.ArgumentParser(description='Gives a hashcat representation of the password data key')\n    parser.add_argument('passworddatakeyfile', nargs='?', type=argparse.FileType('rb'), default=\"password_data.key\",\n                        help='The WhatsApp password data keyfile. Default: password_data.key')\n    return parser.parse_args()\n\n\ndef barrtoint(barr: javaobj.beans.BlockData) -> int:\n    \"\"\"Converts a javaobj BlockData to an int\"\"\"\n    return int.from_bytes(barr.data, byteorder='big', signed=False)\n\n\ndef javaintlist2bytes(barr: javaobj.beans.JavaArray) -> bytes:\n    \"\"\"Converts a javaobj bytearray which somehow became a list of signed integers back to a Python byte array\"\"\"\n    out: bytes = b''\n    for i in barr.data:\n        out += i.to_bytes(1, byteorder='big', signed=True)\n    return out\n\n\ndef read_password_data_key(passworddatakeyfilestream) -> str:\n    # Assign variables to suppress warnings\n    deserialized: list = list()\n\n    try:\n        deserialized: list = javaobj.load(passworddatakeyfilestream)\n    except OSError as e:\n        Log.f(\"Couldn't read keyfile: {}\".format(e))\n    except (ValueError, RuntimeError) as e:\n        Log.f(\"The keyfile is not a valid Java object: {}\".format(e))\n\n    if len(deserialized) != 4:\n        Log.f(\"The keyfile has more fields than expected.\")\n\n    version: int = barrtoint(deserialized[0])\n    if version != 1:\n        Log.f(\"Unexpected key version: {}\".format(version))\n\n    encoded = javaintlist2bytes(deserialized[1])\n    if len(encoded) != 64:\n        Log.f(\"The encoded password has the wrong length\")\n\n    salt = javaintlist2bytes(deserialized[2])\n    if len(salt) != 64:\n        Log.f(\"The salt has the wrong length\")\n\n    permutations: int = barrtoint(deserialized[3])\n    if permutations != 100000:\n        Log.i(\"Unexpected permutation number: {}\".format(permutations))\n\n    return \"sha512:{}:{}:{}\".format(\n        permutations,\n        b64encode(salt).decode('ascii'),\n        b64encode(encoded).decode('ascii')\n    )\n\n\ndef main():\n    args = parsecmdline()\n    Log.i(\"Remember: hashcat mode is 12100 (PBKDF2-HMAC-SHA512)\")\n    pwd_hash = read_password_data_key(args.passworddatakeyfile)\n    print(pwd_hash)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "utils/protobuf_bruteforce.py",
    "content": "\"\"\"\nThis script tries to find protobuf messages in a file.\nProps to protobuf_inspector for the parser.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom protobuf_inspector.types import StandardParser\nfrom io import BytesIO\nfrom os.path import getsize\n\nimport argparse\n\n\ndef parsecmdline() -> argparse.Namespace:\n    \"\"\"Sets up the argument parser\"\"\"\n    parser = argparse.ArgumentParser(description='Find protocol buffers in a file.')\n    parser.add_argument('file_name', type=str, help='A file that you believe contains protobuf messages.')\n    parser.add_argument('-k', '--keep-going', action='store_true', help='Don\\'t stop after the first result.')\n    parser.add_argument('-r', '--range', type=int, default=512, help='The number of bytes to search. Ignored if -w is '\n                                                                     'set.')\n    parser.add_argument('-w', '--whole-file', action='store_true', help='Search the whole file. Not advised for large '\n                                                                        'files')\n    return parser.parse_args()\n\n\ndef load_file(file_name: str, byte_range=0, reverse=False) -> bytes:\n    \"\"\" Loads a file and returns it as a byte array.\n    If byte_range is set, it will return the first byte_range bytes of the file.\n    If reverse is set, it will return the last byte_range bytes of the file.\n    \"\"\"\n    try:\n\n        size = getsize(file_name)\n\n        if byte_range > size / 2:\n            raise ValueError(\"Range provided is bigger than half of file. Use -w or lower the range.\")\n\n        with open(file_name, 'rb') as f:\n\n            if byte_range < 1:\n                if reverse:\n                    raise ValueError(\"Cannot read the whole file from end\")\n                return f.read()\n\n            if reverse:\n                f.seek(size - byte_range)\n                return f.read(byte_range)\n\n            return f.read(byte_range)\n\n    except IOError:\n        print(\"File not found or other IO error\")\n        exit(1)\n\n\ndef get_truncated_stream(content: bytes, start: int, end: int) -> BytesIO:\n    \"\"\" Returns a BytesIO object with the content truncated to the given range. \"\"\"\n    return BytesIO(content[start:end])\n\n\ndef main():\n    args = parsecmdline()\n\n    if args.whole_file:\n\n        whole_file = load_file(args.file_name)\n        search(whole_file, args.keep_going)\n\n    else:\n\n        # We first try the first \"range\" bytes.\n        whole_file = load_file(args.file_name, args.range)\n        search(whole_file, args.keep_going)\n\n        print(\"Now searching at the end of the file\")\n        # Then we try the last \"range\" bytes.\n        size = getsize(args.file_name)\n        whole_file = load_file(args.file_name, args.range, reverse=True)\n        search(whole_file, args.keep_going, size - len(whole_file))\n\n    if args.keep_going:\n        print(\"Finished\")\n    else:\n        print(\"Nothing found\")\n        exit(1)\n\n\ndef protoparse(stream):\n    return StandardParser().parse_message(stream, \"message\")\n\n\nclass Message:\n    last_good_i = 0\n    last_good_j = 0\n    output = \"\"\n\n\ndef search(whole_file: bytes, keep_going: bool, offset=0):\n    \"\"\" Searches for protobuf messages in the given byte array. \"\"\"\n\n    for i in range(len(whole_file)):\n        message = Message()\n\n        for j in range(i + 1, len(whole_file)):\n            candidate = get_truncated_stream(whole_file, i, j)\n            try:\n                message.output = protoparse(candidate)\n                message.last_good_j = j\n                message.last_good_i = i\n\n            except Exception:\n                pass\n        if message.last_good_j and message.last_good_i == i:\n            print(\"\\n Message from byte {} to {}\".format(message.last_good_i + offset, message.last_good_j + offset))\n            print(message.output)\n            if not keep_going:\n                exit(0)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  }
]