Repository: ElDavoo/WhatsApp-Crypt14-Crypt15-Decrypter
Branch: main
Commit: ae6e1ebb8d3d
Files: 76
Total size: 203.2 KB
Directory structure:
gitextract_jz02_bs8/
├── .coveragerc
├── .devcontainer/
│ └── devcontainer.json
├── .github/
│ ├── FUNDING.yml
│ ├── ISSUE_TEMPLATE/
│ │ └── can-t-decrypt.md
│ ├── PULL_REQUEST_TEMPLATE.md
│ ├── copilot-instructions.md
│ ├── dependabot.yml
│ └── workflows/
│ ├── codeql-analysis.yml
│ ├── lint-test-coverage.yml
│ └── pypi.yml
├── .gitignore
├── CHANGELOG.md
├── CITATION.cff
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── SECURITY.md
├── git-hooks/
│ └── pre-commit
├── notebook.ipynb
├── proto/
│ ├── C14_cipher.proto
│ ├── C15_IV.proto
│ ├── backup_expiry.proto
│ ├── backup_prefix.proto
│ └── key_type.proto
├── pyproject.toml
├── requirements.txt
├── src/
│ └── wa_crypt_tools/
│ ├── __init__.py
│ ├── lib/
│ │ ├── constants.py
│ │ ├── db/
│ │ │ ├── db.py
│ │ │ ├── db12.py
│ │ │ ├── db14.py
│ │ │ ├── db15.py
│ │ │ └── dbfactory.py
│ │ ├── key/
│ │ │ ├── key.py
│ │ │ ├── key14.py
│ │ │ ├── key15.py
│ │ │ └── keyfactory.py
│ │ ├── logformat.py
│ │ ├── props.py
│ │ └── utils.py
│ ├── proto/
│ │ ├── C14_cipher_pb2.py
│ │ ├── C15_IV_pb2.py
│ │ ├── __init__.py
│ │ ├── backup_expiry_pb2.py
│ │ ├── backup_prefix_pb2.py
│ │ └── key_type_pb2.py
│ ├── wacreatekey.py
│ ├── wadecrypt.py
│ ├── waencrypt.py
│ ├── waguess.py
│ └── wainfo.py
├── tests/
│ ├── __init__.py
│ ├── lib/
│ │ ├── __init__.py
│ │ ├── db/
│ │ │ ├── __init__.py
│ │ │ └── test_db.py
│ │ ├── test_constants.py
│ │ └── test_utils.py
│ ├── res/
│ │ ├── empty-db.sql
│ │ ├── empty-db.zlib1
│ │ ├── encrypted_backup.key
│ │ ├── key
│ │ ├── msgstore-noexpiry.db.crypt14
│ │ ├── msgstore.db.crypt12
│ │ ├── msgstore.db.crypt14
│ │ ├── msgstore.db.crypt15
│ │ └── test.json
│ ├── test_createkey.py
│ ├── test_decrypt.py
│ ├── test_encrypt.py
│ ├── tools-invocation/
│ │ └── test_wacreatekey.py
│ └── utils/
│ ├── __init__.py
│ └── utils.py
└── utils/
├── WA_HMACSHA256_Loop.java
├── password_data_key_to_hashcat.py
└── protobuf_bruteforce.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .coveragerc
================================================
[run]
omit=*/tests/*,*/proto/*
================================================
FILE: .devcontainer/devcontainer.json
================================================
{
"image": "mcr.microsoft.com/devcontainers/python:3.14",
"features": {
},
"mounts": [
"source=${localEnv:HOME}/.ssh,target=/home/vscode/.ssh,type=bind,consistency=cached,readonly"
]
}
================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
custom: ["https://www.paypal.me/eldavoo"]
================================================
FILE: .github/ISSUE_TEMPLATE/can-t-decrypt.md
================================================
---
name: Can't decrypt
about: The program can't decrypt my files
title: ''
labels: ''
assignees: ElDavoo
---
**Hexdump of your key file**
Add the hexdump of your key file here
**Hexdump of the encrypted DB
Add the hexdump of the first 256 bytes of your DB here.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Program output using -v and -f**
**Additional context**
Add any other context about the problem here.
================================================
FILE: .github/PULL_REQUEST_TEMPLATE.md
================================================
This pull requests fixes the issue # (issue number)
================================================
FILE: .github/copilot-instructions.md
================================================
# WhatsApp Crypt Tools - AI Coding Agent Instructions
## Project Overview
**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.
## Architecture Patterns
### Factory Pattern for Version Handling
The codebase uses two factory classes to abstract version-specific logic:
1. **KeyFactory** ([src/wa_crypt_tools/lib/key/keyfactory.py](src/wa_crypt_tools/lib/key/keyfactory.py))
- Handles both file-based keys and hex string keys
- Dispatches to Key14 or Key15 based on key format
- Falls back gracefully with helpful error messages
2. **DatabaseFactory** ([src/wa_crypt_tools/lib/db/dbfactory.py](src/wa_crypt_tools/lib/db/dbfactory.py))
- Detects crypt version (12/14/15) from file headers
- Uses protobuf messages for crypt15 header parsing
- Returns version-specific Database class (Database12/14/15)
Each version class inherits from base `Database` and `Key` classes, implementing version-specific encryption/decryption logic.
### Protobuf Integration for Crypt15
Crypt15 uses protobuf messages to parse backup headers:
- Definition files in [proto/](proto/) directory (backup_prefix.proto, C14_cipher.proto, C15_IV.proto, key_type.proto)
- Generated Python files in [src/wa_crypt_tools/proto/](src/wa_crypt_tools/proto/)
- **Critical dependency**: Requires protobuf ≥5.28.5 (failing imports suggest version mismatch)
## Command-Line Tools
All entry points in [src/wa_crypt_tools/](src/wa_crypt_tools/):
| Tool | Purpose |
|------|---------|
| **wadecrypt.py** | Decrypt crypt12/14/15 files; supports streaming with buffer control |
| **waencrypt.py** | Encrypt databases (BETA); requires reference file or complex parameters |
| **waguess.py** | Brute-force guess encryption keys |
| **wainfo.py** | Print metadata about encrypted/key files |
| **wacreatekey.py** | Generate new encryption keys |
Each tool:
- Configures logging via CustomFormatter ([src/wa_crypt_tools/lib/logformat.py](src/wa_crypt_tools/lib/logformat.py))
- Uses argparse for CLI argument parsing
- Sets up handlers for both root logger and `wa_crypt_tools.lib` logger
## Key Technical Details
### Decryption Process (wadecrypt.py)
- Uses AES GCM cipher with HMAC-SHA256 authentication
- Supports streaming/chunked reading to handle large files (buffer_size parameter)
- Handles three footer detection scenarios: single-file backup, multi-file backup, and split checksum
- Tests decompression using zlib; auto-detects ZIP vs. raw formats
- Verifies HMAC and detects corruption
### Critical Constants
See [src/wa_crypt_tools/lib/constants.py](src/wa_crypt_tools/lib/constants.py):
- `ZLIB_HEADERS`: Expected uncompressed data starts with `x\x01` or `PK`
- `HEADER_SIZE`: 384 bytes required for reliable header detection
- `DEFAULT_DATA_OFFSET`: 122 bytes (where encrypted data begins)
- `SUPPORTED_CIPHER_VERSION`: Only `b'\x00\x01'` supported
- `SUPPORTED_KEY_VERSIONS`: Keys support versions 1-3
### Logging Format
All tools use custom colored logging: `filename:lineno : [LEVEL] message`
- Enable debug with `-v` flag on CLI tools
- Levels: INFO (default), DEBUG, WARNING, ERROR, CRITICAL
## Testing
### Test Structure
- [tests/test_decrypt.py](tests/test_decrypt.py): Validates decryption against known test files using SHA512 hash
- [tests/test_encrypt.py](tests/test_encrypt.py): Tests encryption round-trips
- [tests/test_createkey.py](tests/test_createkey.py): Key generation and parsing
- [tests/lib/](tests/lib/): Unit tests for constants, utilities
- Test resources in [tests/res/](tests/res/): Contains test keys and encrypted databases
Run tests:
```bash
python -m pytest
```
### Test Data Files
- `tests/res/encrypted_backup.key`: Crypt15 E2E key (hex format)
- `tests/res/key`: Crypt12/14 key (binary, Java serialized)
- `tests/res/msgstore.db.crypt{12,14,15}`: Encrypted test databases
## Critical Dependencies
- **pycryptodomex ≥3.20.0**: AES-GCM encryption
- **protobuf ≥5.28.5 <6.0.0**
- **javaobj-py3 ≥0.4.4**: Parse Java serialized key objects (crypt12/14)
**Troubleshooting imports**:
- If protobuf import fails with "cannot import name 'builder'": Update protobuf to ≥3.20.0
- If no proto modules found: Download from [proto/](proto/) or run proto code generation
## Conventions & Patterns
1. **Logging**: Always use module-level logger: `log = logging.getLogger(__name__)`
2. **Error handling**: Use try/except with detailed log messages; avoid silent failures
3. **Versioning**: Pass version-specific context through factory; never check string filenames
4. **File I/O**: Use context managers (`with` statements); handle large files with streaming
5. **Checksum validation**: Always verify HMAC/authentication tags at end of decryption
## Extending the Codebase
- **Adding new crypt version**: Create `DatabaseXX.py` and `KeyXX.py` in respective lib folders; update factories
- **Modifying decryption logic**: Changes in base `Database` class affect all versions; test all three
- **Adding proto messages**: Update .proto files, regenerate Python code, update imports in db15.py
================================================
FILE: .github/dependabot.yml
================================================
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: "pip" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "daily"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
# Check for updates to GitHub Actions every weekday
interval: "daily"
================================================
FILE: .github/workflows/codeql-analysis.yml
================================================
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
on:
push:
branches: [ '*' ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ main ]
workflow_call:
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'python' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Learn more about CodeQL language support at https://git.io/codeql-language-support
steps:
- name: Checkout repository
uses: actions/checkout@v6
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v4
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v4
# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v4
================================================
FILE: .github/workflows/lint-test-coverage.yml
================================================
name: "Lint, tests, coverage"
on:
push:
branches:
- '*'
pull_request:
branches:
- main
workflow_call:
permissions:
contents: read
jobs:
job:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
steps:
- uses: actions/checkout@v6
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v6
with:
python-version: ${{ matrix.python-version }}
cache: 'pip'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install flake8 pytest codecov pytest-cov coveralls
python -m pip install -e .[test]
- name: Lint with flake8
run: |
# stop the build if there are Python syntax errors or undefined names
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
- name: Test with pytest
run: |
python -m pytest --cov
- name: Coveralls
uses: coverallsapp/github-action@v2
if: github.event_name != 'pull_request'
env:
COVERALLS_REPO_TOKEN: ${{ secrets.COVERALLS_REPO_TOKEN }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
================================================
FILE: .github/workflows/pypi.yml
================================================
name: Upload Python Package to PyPI when a Release is Created
on:
push:
tags:
- 'v*'
jobs:
codeql:
uses: ./.github/workflows/codeql-analysis.yml
tests:
uses: ./.github/workflows/lint-test-coverage.yml
release:
permissions: write-all
needs:
- codeql
- tests
name: Create Release
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v6
- name: Create Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: Release ${{ github.ref }}
draft: false
prerelease: false
pypi-publish:
needs: release
name: Publish release to PyPI
runs-on: ubuntu-latest
environment:
name: pypi
url: https://pypi.org/p/wa-crypt-tools
permissions:
id-token: write
steps:
- uses: actions/checkout@v6
- name: Set up Python
uses: actions/setup-python@v6
with:
python-version: "3.x"
- name: Install dependencies
run: |
python -m pip install --upgrade pip build
pip install -r requirements.txt
- name: Build package
run: |
python -m build
- name: Publish package distributions to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
================================================
FILE: .gitignore
================================================
.idea
test-files
protoc*
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
================================================
FILE: CHANGELOG.md
================================================
# Changelog
## Version 0.0.9
- Code refactored as a library, with lots of files, classes and methods
- decrypt14_15 renamed to wadecrypt
- Guessing logic moved to waguess
- New tools introduced:
- wacreatekey
- waencrypt, for encrypting backups
- wainfo, for printing infos
## Version 0.0.8
As I uploaded the package to PyPI, the versioning scheme changed. It was too ugly to start from version 7.0.
- Uploaded package to PyPI
## Old changelogs
---
Note: this script did not use to follow a versioning policy. Versions number were written just for reference.
This file may not be 100% correct: The true changelog is the git history.
## Version 7.0
- Support for crypt12 files (only msgstore tested)
## Version 6.1
- The AES authentication tag is now checked.
This is the beginning of a new era as everything is checked properly.
## Version 6.0
- The MD5 checksum at the end of the file is now checked.
## Version 5.4
- Support for key version 3
## Version 5.3
- You can now specify a custom buffer size to be used.
## Version 5.2
- You can write the hex encoded key (crypt15) directly instead of specifying the key file.
## Version 5.1
- More command line switches
(you can choose the approach and the default offsets for guessing mode)
## Version 5.0
- Unified the crypt14 and the crypt15 code bases.
## Version 4.1
- (Crypt15) Support for other DB files, like stickers, chat_settings, wallpapers...
Note: stickers and wallpapers are ZIP files that will not be decompressed automatically.
## Version 4.0
- (crypt15) No more guessing offsets! The database header is now completely parsed.
The guessing logic has been left as a fallback behaviour.
The structure of the program has been changed accordingly.
- The proto file for msgstore.db.crypt15 are now complete
## Version 3.0
- crypt15 support (in a separate script, decrypt15.py)
- added a proto file describing the header of a msgstore.db.crypt15 file
## Version 2.2
- The Java object from the "key" file is now correctly deserialized, instead of just ignoring the header.
- The SHA256 of the googleIdSalt in the "key" file is now actually checked.
- Added a utility to read "password_data.key" and give a hashcat representation of the file.
- Moved the changelog to a separate file.
## Version 2.1
- Refactoring
- Added new command line options
## Version 2.0 is here!
Since the file format keeps changing, I decided to completely reimplement the script.
It should be much more efficient, and it should handle small variations of offset **automatically**.
## Version 1.1
- Added support for crypt14, via fixed headers.
## Version 1.0
- Initial implementation by TripCode for crypt12 files.
================================================
FILE: CITATION.cff
================================================
# This CITATION.cff file was generated with cffinit.
# Visit https://bit.ly/cffinit to generate yours today!
cff-version: 1.2.0
title: wa-crypt-tools
message: >-
Please don't say "et al.", I'm the only author.
type: software
authors:
- given-names: Davide
family-names: Palma
email: posta@davidepalma.it
orcid: 'https://orcid.org/0000-0003-1931-7836'
repository-code: 'https://github.com/ElDavoo/wa-crypt-tools'
abstract: 'Manage WhatsApp .crypt12, .crypt14 and .crypt15 files.'
keywords:
- WhatsApp
- crypt12
- crypt14
- crypt15
license: GPL-3.0-only
date-released: '2022-06-01'
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
github@davidepalma.it.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
================================================
FILE: CONTRIBUTING.md
================================================
# How to contribute
## Test
Test the program with your own databases, both crypt 12, crypt14 and crypt15. Report any errors.
## Work on issues
Take a look at the open issues and work on them
## Submitting changes
Open a pull request
## Coding conventions
Those of PyCharm
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
================================================
FILE: README.md
================================================
[](https://coveralls.io/github/ElDavoo/wa-crypt-tools?branch=main)

# WhatsApp Crypt Tools
Decrypt and encrypt WhatsApp and WA Business' .crypt12, .crypt14 and .crypt15 files with ease!
For decryption, you NEED **the key file** or the 64-characters long key.
The key file is named "key" if the backup is crypt14 or
"encrypted_backup.key" if the backup is crypt15 (encrypted E2E backups).
Those who are looking for a more complete suite for
WhatsApp forensics, check out [whapa.](https://github.com/B16f00t/whapa)
# Quick install
## Cloud - Google Colab
If you do not want to install programs in your computer, you can run this program
[in Google Colab](https://colab.research.google.com/drive/17z5UWE9dBbyvVfOG-KzRWCmTqFA3j82u?usp=sharing)
.
## Local - Jupyter
If you are familiar with Jupyter (read
[here](https://www.earthdatascience.org/courses/intro-to-earth-data-science/open-reproducible-science/jupyter-python/get-started-with-jupyter-notebook-for-python)
if you're not), you can use the
[notebook version](notebook.ipynb)
of the program.
## Local - pip
You can install this script as a package through pip. Just run:
```bash
python -m pip install wa-crypt-tools
```
for the stable version and
```bash
python -m pip install git+https://github.com/ElDavoo/wa-crypt-tools
```
for the development version.
You might have to create a virtual environment to avoid conflicts with other packages.
# Quick start
## Decrypt a file with wadecrypt
```
usage: wadecrypt [-h] [-nm] [-bs BUFFER_SIZE] [-nd] [-v] [-f] [keyfile] [encrypted] [decrypted]
```
So, for decrypting a crypt12/14/15, we give the program the key file, the encrypted file and the name of the output file.
### Example
```
$ wadecrypt encrypted_backup.key msgstore.db.crypt15 msgstore.db
key15.py:51 : [I] Crypt15 / Raw key loaded
wadecrypt.py:271 : [I] Done
```
## Encrypt a file with waencrypt (BETA)
```
usage: waencrypt [-h] [-f] [-v] [--enable-features [ENABLE_FEATURES ...]] [--max-feature MAX_FEATURE]
[--multi-file] [--type {12,14,15}] [--iv IV] [--reference REFERENCE] [--noparse]
[--wa-version WA_VERSION] [--jid JID] [--backup-version BACKUP_VERSION] [--no-compress]
[keyfile] [decrypted] [encrypted]
```
Encryption is more complex and untested: it is advised to use another encrypted file
from the same account, which we will call "reference".
### With a reference file (only database crypt15 tested)
```
waencrypt --reference msgstore.db.crypt15 encrypted_backup.key msgstore.db msgstore-new.db.crypt15
waencrypt.py:57 : [W] This script is in beta stage
waencrypt.py:89 : [I] Done!
```
### Without a reference file
You need to supply the following parameters:
1) The feature list: Only for 2019+ databases. A list of numbered boolean
properties related to your database. There is currently no way to infer them
from a database file. In the example, we will just use my backup's feature list,
but don't expect it to work for you.
2) The max feature number, which is 39 at the time of writing
3) The version of the app that encrypted the file: Use a reasonable value,
like 2.24.8.6 or something.
4) Jid: The last 2 numbers of your phone number
5) Backup version: Use 1.
Defaults will be used if parameters are omitted.
To sum it up:
```
$ waencrypt --enable-features 5 6 7 8 9 10 11 12 13 14 15 16
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
-version 1 encrypted_backup.key msgstore.db msgstore-new.db.crypt15
waencrypt.py:57 : [W] This script is in beta stage
waencrypt.py:89 : [I] Done!
```
You can get info about a backup file with the `wainfo` tool.
# Tool list
For usage, run the tool with `-h` option.
1) `wacreatekey` - Create key files
2) `wadecrypt` - Decrypt backups
3) `waencrypt` - Encrypt backups
4) `waguess` - Hacky way to try decrypt backups
5) `wainfo` - Get info about a backup
# FAQ
## Can I decrypt a backup without a key file?
NO! What would be the point of encrypting a file otherwise?
## I forgot the password / 64-letters key, can you help me?
See above.
## The program doesn't decrypt my backups and says the backups are corrupted
Your backups are corrupted. You can try disabling all checks with the
`-f` flag, but expect crashes and/or unreadable output.
## The program doesn't decrypt and says the key is wrong
The key is wrong. You can try disabling all checks with the
`-f` flag, but expect crashes and/or unreadable output.
## What is the best setup for decrypting my own databases?
1) Enable end-to-end backups and do NOT use a password, use the 64-letters key option.
2) Use `wacreatekey` to create a `encrypted_backup.key` file
3) Store your key file safely and use `wadecrypt` to decrypt your backups.
In this way, you will manage your own root key - otherwise WhatsApp might change
your key when appropriate.
## Can I use the password to decrypt the database?
No! The password is only used to talk with the WhatsApp servers and retrieve
the 64-letters key.
In other words, the password is used to **protect the key**, it's not used
to encrypt the backups.
## Can I decrypt .mcrypt1 files downloaded from Google Drive?
Yes, but the code is not documented, so please at this time read the code.
## I really think the program is broken, that my backups are intact and that the key is right
Send me the needed files on Telegram and I will take a look.
If you (understandably) have privacy concerns, open an issue and attach:
1) Output of the program (both with and without --force)
2) Hexdump of keyfile
3) Hexdump of first 512 bytes of encrypted DB
But it will be more difficult to help you.
## Where do I get the key(file)?
On a rooted Android device, you can just copy
`/data/data/com.whatsapp/files/key`
(or `/data/data/com.whatsapp/files/encrypted_backup.key` if backups are crypt15).
If you enabled E2E backups, and you did not use a password
(you have a copy of the 64-digit key, for example a screenshot),
you can just transcribe and use it in lieu of the key file parameter.
**There are other ways, but it is not in the scope of this project
to tell you.
Issues asking for this will be closed as invalid.**
## How can I cite this software?
There was no paper or thesis written about this software, but you can cite this online repository.
Please don't say "et al." as there is (for now) only one author.
### CITATION.cff
See the [CITATION.cff](CITATION.cff) file for citation information.
### BibTeX
```
@misc{wa-crypt-tools,
author = {ElDavoo},
title = {WhatsApp Crypt Tools},
year = {2022},
month = {06},
howpublished = {\url{https://github.com/ElDavoo/wa-crypt-tools}
}
```
### BibLaTeX
```
@online{wa-crypt-tools,
author = {ElDavoo},
title = {WhatsApp Crypt Tools},
year = {2022},
month = {06},
url = {https://github.com/ElDavoo/wa-crypt-tools}
}
```
### I will happily accept pull requests for the currently open issues. :)
### Last tested version (don't expect this to be updated)
Stable:
2.24.16.76
Beta:
2.24.26.11
#### Business
Stable:
2.24.23.78
#### Protobuf automatic fix
You can install the proto optional dependencies to use `protoletariat` and fix the proto imports automatically.
First, after cloning the repository, do an editable installation of the package (possibily in a virtual environment) with:
`pip install -e .[proto]`
This will also install the optional dependencies of the package.
Next, download the protobuf compiler from its repository [here](https://github.com/protocolbuffers/protobuf/releases).
You can move the protoc program to the `wa-crypt-tools/proto` folder where the .proto files are.
Replace the protobuf classes as needed and run `protoc` to generate the python classes.
From the `wa-crypt-tools/proto` directory of the project, run:
`./protoc --python_out=../src/wa_crypt_tools/proto --proto_path=. *.proto`
After generating the protobuf python classes through `protoc`, from that same directory run:
`protol --in-place --python-out ..\src\wa_crypt_tools\proto protoc --proto-path=. *.proto`
Linux:
`PATH="$(pwd):$PATH" protol --in-place --python-out ../src/wa_crypt_tools/proto protoc --proto-path=. *.proto`
Now all the generated python classes should have their imports fixed.
---
## Donations
Thank you so much to each one of you!
- **🎉🎉🎉 [githubsterer](https://github.com/githubsterer) 🎉🎉🎉**
- **🎉🎉🎉 [courious875](https://github.com/courious875) 🎉🎉🎉**
- **🎉 [pscriptos](https://github.com/pscriptos) 🎉**
Anyone else that I forgot to mention!
---
#### Credits:
- Original implementation for crypt12: [TripCode](https://github.com/TripCode)
- Some help at the beginning: [DjEdu28](https://github.com/DjEdu28)
- Actual crypt14/15 implementation with protobuf: [ElDavoo](https://github.com/ElDavoo)
- Help with crypt14/15 footer: [george-lam](https://github.com/georg-lam)
- Pip package implementation: [Mikel12455](https://github.com/Mikel12455)
- [kingbtcvl](https://github.com/kingbtcvl)
Anyone else that helped!
#### Research papers that used this software
- [Injection Attacks Against End-to-End Encrypted Applications](https://ieeexplore.ieee.org/abstract/document/10646849)
- [Forensic Analysis of WhatsApp Disappearing Message on
Unrooted Android Using Mobile Device Forensics
Methodology NIST SP 800-101r1](https://catalog.lib.kyushu-u.ac.jp/opac_download_md/7172316/pp516-524.pdf)
- [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 )
### Stargazers over time
[](https://star-history.com/#ElDavoo/wa-crypt-tools&Date)
================================================
FILE: SECURITY.md
================================================
# Security Policy
## Supported Versions
Latest
## Reporting a Vulnerability
Open an issue or contact me in my profile's email
================================================
FILE: git-hooks/pre-commit
================================================
#!/bin/sh
#
# An example hook script to verify what is about to be committed.
# Called by "git commit" with no arguments. The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
#
# To enable this hook, rename this file to "pre-commit".
if git rev-parse --verify HEAD >/dev/null 2>&1
then
against=HEAD
else
# Initial commit: diff against an empty tree object
against=$(git hash-object -t tree /dev/null)
fi
# If you want to allow non-ASCII filenames set this variable to true.
allownonascii=$(git config --type=bool hooks.allownonascii)
# Redirect output to stderr.
exec 1>&2
# Cross platform projects tend to avoid non-ASCII filenames; prevent
# them from being added to the repository. We exploit the fact that the
# printable range starts at the space character and ends with tilde.
if [ "$allownonascii" != "true" ] &&
# Note that the use of brackets around a tr range is ok here, (it's
# even required, for portability to Solaris 10's /usr/bin/tr), since
# the square bracket bytes happen to fall in the designated range.
test $(git diff --cached --name-only --diff-filter=A -z $against |
LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0
then
cat <<\EOF
Error: Attempt to add a non-ASCII file name.
This can cause problems if you want to work with people on other platforms.
To be portable it is advisable to rename the file.
If you know what you are doing you can disable this check using:
git config hooks.allownonascii true
EOF
exit 1
fi
# If there are whitespace errors, print the offending file names and fail.
git diff-index --check --cached $against --
# Run the tests
exec python3 -m pytest -q
================================================
FILE: notebook.ipynb
================================================
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "7cXVAM_dA3AS"
},
"source": [
"#WhatsApp Crypt14-15 Backup Decrypter\n",
"Decrypts WhatsApp .crypt12, .crypt14 and .crypt15 files, given the key file or the 64-characters long key.\n",
"\n",
"The key file is named \"key\" if the backup is crypt14 or\n",
"\"encrypted_backup.key\" if the backup is crypt15 (encrypted E2E backups).\n",
"The output result is either a SQLite database or a ZIP file (in case of wallpapers and stickers)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "qPWe755MTd8M"
},
"source": [
"###Key takeaways\n",
"* You need root access in most devices https://github.com/ElDavoo/WhatsApp-Crypt14-Crypt15-Decrypter#where-do-i-get-the-keyfile\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "zJ-qUk9E5fpm"
},
"source": [
"## Upload your key file and crypt files before running"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "hWpc4SKqERuO"
},
"source": [
"###Installation"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "t8sD3dVEt_-v"
},
"outputs": [],
"source": [
"!python -m pip install git+https://github.com/ElDavoo/wa-crypt-tools\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Myz44qhTR8uk"
},
"source": [
"###Run this after uploaded the .crypt14/15 file here"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "CK0eJ_0YyXsL"
},
"outputs": [],
"source": [
"#example of a file key name \"key\", an encrypted crypt14 inside default folder and an output with the decrypted file\n",
"\n",
"#parameters\n",
"# decrypter_script keyfile_path/key_value encrypted_file_path decrypter_output_file_path\n",
"!wadecrypt ./key ./msgstore.db.crypt14 ./msgstore.db"
]
}
],
"metadata": {
"colab": {
"collapsed_sections": [
"hWpc4SKqERuO"
],
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
================================================
FILE: proto/C14_cipher.proto
================================================
edition = "2023";
// crypt14 cipher files.
message C14_cipher {
bytes cipher_version = 1; // is usually 0001
bytes key_version = 2; // Is usually "1"
bytes server_salt = 3; // The 32-bytes long server salt
bytes google_id = 4; // The 16-bytes long google id salt
bytes IV = 5; // The 16-bytes long IV
}
================================================
FILE: proto/C15_IV.proto
================================================
edition = "2023";
// In crypt15 files only the IV is stored.
message C15_IV {
bytes IV = 1; // The 16-bytes long IV
}
================================================
FILE: proto/backup_expiry.proto
================================================
edition = "2023";
// This describes the metadata, e.g. the version, the ph number and various features.
message BackupExpiry {
string app_version = 1; // Whatsapp version, for example "2.22.4.14"
// optional string device_model = 2; // Device model, unused
string jidSuffix = 3; // The last two numbers of the user's Jid (phone number)
// These bools are only written if the backup is a msgstore backup.
int32 backup_version = 4;
// Booleans that indicate various features
bool f_5 = 5; // call_log
bool f_6 = 6; // labeled_jid
bool f_7 = 7; // message_fts
bool f_8 = 8; // blank_me_jid
bool f_9 = 9; // message_link
bool f_10 = 10; // message_main
bool f_11 = 11; // message_text
bool f_12 = 12; // missed_calls
bool f_13 = 13; // receipt_user
bool f_14 = 14; // message_media
bool f_15 = 15; // message_vcard
bool f_16 = 16; // message_future
bool f_17 = 17; // message_quoted
bool f_18 = 18; // message_system
bool f_19 = 19; // receipt_device
bool f_20 = 20; // message_mention
bool f_21 = 21; // message_revoked
bool f_22 = 22; // broadcast_me_jid
bool f_23 = 23; // message_frequent
bool f_24 = 24; // message_location
bool f_25 = 25; // participant_user
bool f_26 = 26; // message_thumbnail
bool f_27 = 27; // message_send_count
bool f_28 = 28; // migration_jid_store
bool f_29 = 29; // payment_transaction
bool f_30 = 30; // migration_chat_store
bool f_31 = 31; // quoted_order_message
bool f_32 = 32; // media_migration_fixer
bool f_33 = 33; // quoted_order_message_v2
bool f_34 = 34; // message_main_verification
bool f_35 = 35; // quoted_ui_elements_reply_message
bool f_36 = 36; // alter_message_ephemeral_to_message_ephemeral_remove_column
bool f_37 = 37; // alter_message_ephemeral_setting_to_message_ephemeral_setting_remove_column
// optional int32 backup_export_file_size = 38; // The size of the backup file, unused
bool f_39 = 39; // cleaned_db, does not show in incremental backups
}
================================================
FILE: proto/backup_prefix.proto
================================================
edition = "2023";
import "C14_cipher.proto";
import "C15_IV.proto";
import "key_type.proto";
import "backup_expiry.proto";
/*
This file describes the header you can find near the start of an encrypted backup file.
*/
message BackupPrefix {
Key_Type key_type = 1; // 0 if traditional (crypt14), 1 if end-to-end (crypt15)
oneof cipher_info {
C14_cipher c14_cipher = 2; // If DB is crypt14
C15_IV c15_iv = 3; // If DB is crypt15
}
// Version that generated backup and other infos
BackupExpiry info = 4;
}
================================================
FILE: proto/key_type.proto
================================================
edition = "2023";
// This enum describes if the key is self-managed by WhatsApp of if it is stored in the HSM.
// In other words, traditional = 0, end-to-end = 1
enum Key_Type {
WA_PROVIDED = 0;
HSM_CONTROLLED = 1;
}
================================================
FILE: pyproject.toml
================================================
[build-system]
requires = ["setuptools", "setuptools-scm"]
build-backend = "setuptools.build_meta"
[project]
name = "wa-crypt-tools"
keywords = ["whatsapp", "crypt12", "crypt14", "crypt15"]
version = "0.1.0"
authors = [
{name = "Davide Palma", email = "pypi@davidepalma.it"},
]
description = "Manages WhatsApp .crypt12, .crypt14 and .crypt15 files, given the key."
readme = "README.md"
requires-python = ">=3.10"
dependencies = [
"javaobj-py3 >= 0.4.4",
"pycryptodomex >= 3.20.0",
"protobuf >= 5.28.5,< 6.0.0"
]
classifiers = [
"Environment :: Console",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
"Operating System :: OS Independent",
"Topic :: Security :: Cryptography",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Utilities",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14",
]
[project.scripts]
wacreatekey = "wa_crypt_tools.wacreatekey:main"
wadecrypt = "wa_crypt_tools.wadecrypt:main"
waencrypt = "wa_crypt_tools.waencrypt:main"
waguess = "wa_crypt_tools.waguess:main"
wainfo = "wa_crypt_tools.wainfo:main"
[project.optional-dependencies]
proto = [
"protoletariat"
]
================================================
FILE: requirements.txt
================================================
javaobj-py3==0.4.4
pycryptodomex==3.23.0
protobuf==5.29.5
================================================
FILE: src/wa_crypt_tools/__init__.py
================================================
import logging
l = logging.getLogger(__name__)
l.addHandler(logging.NullHandler())
================================================
FILE: src/wa_crypt_tools/lib/constants.py
================================================
class C:
# These constants are only used by the guessing logic.
# zlib magic header is 78 01 (Low Compression).
# The first two bytes of the decrypted data should be those,
# in case of single file backup, or PK in case of multi file.
ZLIB_HEADERS = [
b'x\x01',
b'PK'
]
ZIP_HEADER = b'PK\x03\x04'
# Size of bytes to test (number chosen arbitrarily, but values less than ~310 makes test_decompression fail)
HEADER_SIZE = 384
DEFAULT_DATA_OFFSET = 122
DEFAULT_IV_OFFSET = 8
# Encryption constants
DEFAULT_APP_VERSION = "2.23.18.12"
DEFAULT_JID_SUFFIX = "00"
DEFAULT_BACKUP_VERSION = 0
# The Props I got from a recent backup of mine
DEFAULT_FEATURE_LIST = [5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 35, 36, 37, 39]
# Old backups might not have knowledge of the new features (in 2022 backups the max is 37)
DEFAULT_MAX_FEATURE = 39
# Constants for crypt12/14 key and db
SUPPORTED_CIPHER_VERSION = b'\x00\x01'
SUPPORTED_KEY_VERSIONS = [b'\x01', b'\x02', b'\x03']
================================================
FILE: src/wa_crypt_tools/lib/db/db.py
================================================
import abc
import logging
from wa_crypt_tools.lib.key.key import Key
from wa_crypt_tools.lib.props import Props
log = logging.getLogger(__name__)
class Database(abc.ABC):
"""
An abstract class that represents a database.
"""
iv: bytes
@abc.abstractmethod
def __str__(self):
pass
@abc.abstractmethod
def decrypt(self, key: Key, encrypted: bytes) -> bytes:
pass
@abc.abstractmethod
def encrypt(self, key: Key, props: Props, decrypted: bytes) -> bytes:
pass
@abc.abstractmethod
def get_iv(self) -> bytes:
return self.iv
================================================
FILE: src/wa_crypt_tools/lib/db/db12.py
================================================
from hashlib import md5
from os import urandom
from pathlib import Path
from re import findall
from Cryptodome.Cipher import AES
import logging
from wa_crypt_tools.lib.constants import C
from wa_crypt_tools.lib.db.db import Database
from wa_crypt_tools.lib.key.key14 import Key14
from wa_crypt_tools.lib.props import Props
log = logging.getLogger(__name__)
class Database12(Database):
"""
Implementation of a crypt12 database.
"""
def __init__(self, key: Key14 = None, encrypted=None,
cipher_version: bytes = None, key_version: bytes = None, serversalt: bytes = None,
googleid: bytes = None, iv: bytes = None):
"""Checks if the file is a Crypt12 file.
Returns the cipher if it is, None otherwise."""
"""
The crypt12 file format is similar to the crypt14 file format.
It is a "raw" header, which means it's not a protobuf message,
nor a serialized java object.
Structure:
Cipher version (2 bytes)
Key version (1 byte)
Server salt (32 bytes)
Google ID (16 bytes)
IV (16 bytes)
( so we finally understood why the IV is at offset 51 ... )
"""
self.file_hash = md5()
if encrypted and key:
self.cipher_version = encrypted.read(2)
if self.cipher_version != key.get_cipher_version():
log.error("Cipher version mismatch: {} != {}".format(self.cipher_version, key.get_cipher_version()))
raise ValueError
self.file_hash.update(self.cipher_version)
self.key_version = encrypted.read(1)
if self.key_version != key.get_key_version():
log.error("Key version mismatch: {} != {}".format(self.key_version, key.get_key_version()))
raise ValueError
self.file_hash.update(self.key_version)
self.serversalt = encrypted.read(32)
if self.serversalt != key.get_serversalt():
log.error("Server salt mismatch: {} != {}".format(self.serversalt, key.get_serversalt()))
raise ValueError
self.file_hash.update(self.serversalt)
self.googleid = encrypted.read(16)
if self.googleid != key.get_googleid():
log.error("Google ID mismatch: {} != {}".format(self.googleid, key.get_googleid()))
self.file_hash.update(self.googleid)
self.iv = encrypted.read(16)
self.file_hash.update(self.iv)
elif encrypted:
self.cipher_version = encrypted.read(2)
# if test_bytes != key.get_cipher_version():
# quit_12()
self.file_hash.update(self.cipher_version)
self.key_version = encrypted.read(1)
# if test_bytes != key.get_key_version():
# quit_12()
self.file_hash.update(self.key_version)
self.serversalt = encrypted.read(32)
# if test_bytes != key.get_serversalt():
# quit_12()
self.file_hash.update(self.serversalt)
self.googleid = encrypted.read(16)
# if test_bytes != key.get_googleid():
# quit_12()
self.file_hash.update(self.googleid)
self.iv = encrypted.read(16)
self.file_hash.update(self.iv)
elif key:
self.cipher_version = key.get_cipher_version()
self.file_hash.update(self.cipher_version)
self.key_version = key.get_key_version()
self.file_hash.update(self.key_version)
self.serversalt = key.get_serversalt()
self.file_hash.update(self.serversalt)
self.googleid = key.get_googleid()
self.file_hash.update(self.googleid)
if iv:
self.iv = iv
else:
self.iv = urandom(16)
self.file_hash.update(self.iv)
else:
if cipher_version:
if cipher_version == C.SUPPORTED_CIPHER_VERSION:
self.cipher_version = cipher_version
self.file_hash.update(self.cipher_version)
else:
log.error("Unsupported cipher version provided!")
raise ValueError
else:
self.cipher_version = C.SUPPORTED_CIPHER_VERSION
self.file_hash.update(self.cipher_version)
if key_version:
if key_version in C.SUPPORTED_KEY_VERSIONS:
self.key_version = key_version
self.file_hash.update(self.key_version)
else:
log.error("Unsupported key version provided!")
else:
self.key_version = C.SUPPORTED_KEY_VERSIONS[-1]
self.file_hash.update(self.key_version)
if serversalt:
self.serversalt = serversalt
else:
self.serversalt = urandom(32)
self.file_hash.update(self.serversalt)
if googleid:
self.googleid = googleid
else:
self.googleid = urandom(16)
self.file_hash.update(self.googleid)
if iv:
self.iv = iv
else:
self.iv = urandom(16)
self.file_hash.update(self.iv)
def __str__(self):
return f"""cipher_version: {self.cipher_version}
key_version: {self.key_version}
serversalt: {self.serversalt}
googleid: {self.googleid}
iv: {self.iv}"""
def decrypt(self, key: Key14, encrypted: bytes) -> bytes:
"""Decrypts the database using the provided key"""
userjid = encrypted[-4:]
# check the userjid
crypt12_footer = str(userjid)
jid = findall(r"(?:-|\d)(?:-|\d)(\d\d)", crypt12_footer)
if len(jid) != 1:
log.error("The phone number end is not 2 characters long")
else:
log.debug("Your phone number ends with {}".format(jid[0]))
checksum = encrypted[-20:-4]
authentication_tag = encrypted[-36:-20]
encrypted_data = encrypted[:-36]
is_multifile_backup = False
self.file_hash.update(encrypted_data)
self.file_hash.update(authentication_tag)
if self.file_hash.digest() != checksum:
# We are probably in a multifile backup, which does not have a checksum.
# TODO do crypt12 multifiles actually exist?
is_multifile_backup = True
else:
log.debug("Checksum OK ({}). Decrypting...".format(self.file_hash.hexdigest()))
cipher = AES.new(key.get(), AES.MODE_GCM, self.iv)
try:
output_decrypted: bytes = cipher.decrypt(encrypted_data)
except ValueError as e:
log.fatal("Decryption failed: {}."
"\n This probably means your backup is corrupted.".format(e))
raise e
# Verify the authentication tag
try:
if is_multifile_backup:
# In multifile backups, there is no checksum.
# This means, the last 16 bytes of the files are not the checksum,
# despite being called "checksum", but are the authentication tag.
# Same way, "authentication tag" is not the tag, but the last
# 16 bytes of the encrypted file.
output_decrypted += cipher.decrypt(authentication_tag)
cipher.verify(checksum)
else:
cipher.verify(authentication_tag)
except ValueError as e:
log.error("Authentication tag mismatch: {}."
"\n This probably means your backup is corrupted.".format(e))
return output_decrypted
def encrypt(self, key: Key14, props: Props, decrypted: bytes) -> bytes:
file_hash = md5()
out = b""
out += self.cipher_version
out += self.key_version
out += self.serversalt
out += self.googleid
out += self.iv
cipher = AES.new(key.get(), AES.MODE_GCM, self.iv)
encrypted = cipher.encrypt(decrypted)
out += encrypted
out += cipher.digest()
file_hash.update(out)
out += file_hash.digest()
jid = props.get_jid()
if len(jid) != 2:
log.error("The phone number end is not 2 characters long")
out += "--{}".format(jid).encode()
return out
def get_iv(self) -> bytes:
return self.iv
================================================
FILE: src/wa_crypt_tools/lib/db/db14.py
================================================
import logging
from hashlib import md5
from os import urandom
from re import findall
from Cryptodome.Cipher import AES
from google.protobuf.message import DecodeError
from wa_crypt_tools.lib.db.db import Database
from wa_crypt_tools.lib.key.key import Key
from wa_crypt_tools.lib.key.key14 import Key14
from wa_crypt_tools.lib.props import Props
l = logging.getLogger(__name__)
class Database14(Database):
def __init__(self, key: Key14 = None, encrypted=None, file_hash=None,
cipher_version: bytes = None, key_version: bytes = None, serversalt: bytes = None,
googleid: bytes = None, iv: bytes = None,
props: Props = None):
self.props = props
if encrypted and file_hash:
try:
from wa_crypt_tools.proto import backup_prefix_pb2 as prefix
from wa_crypt_tools.proto import key_type_pb2 as key_type
except ImportError as e:
l.error("Could not import the proto classes: {}".format(e))
if str(e).startswith("cannot import name 'builder' from 'google.protobuf.internal'"):
l.error("You need to upgrade the protobuf library to at least 3.20.0.\n"
" python -m pip install --upgrade protobuf")
elif str(e).startswith("no module named"):
l.error("Please download them and put them in the \"proto\" sub folder.")
raise e
except AttributeError as e:
l.error("Could not import the proto classes: {}\n ".format(e) +
"Your protobuf library is probably too old.\n "
"Please upgrade to at least version 3.20.0 , by running:\n "
"python -m pip install --upgrade protobuf")
raise e
self.header = prefix.BackupPrefix()
l.debug("Parsing database header...")
try:
# The first byte is the size of the upcoming protobuf message
protobuf_size = encrypted.read(1)
file_hash.update(protobuf_size)
protobuf_size = int.from_bytes(protobuf_size, byteorder='big')
# A 0x01 as a second byte indicates the presence of the feature table in the protobuf.
# It is optional and present only in msgstore database, although
# I found some old msgstore backups without it, so it is optional.
msgstore_features_flag = encrypted.peek(1)[0]
if msgstore_features_flag != 1:
msgstore_features_flag = 0
else:
file_hash.update(encrypted.read(1))
if not msgstore_features_flag:
l.debug("No feature table found (not a msgstore DB or very old)")
self.__msgstore_features_flag = msgstore_features_flag
try:
protobuf_raw = encrypted.read(protobuf_size)
file_hash.update(protobuf_raw)
if self.header.ParseFromString(protobuf_raw) != protobuf_size:
l.error("Protobuf message not fully read. Please report a bug.")
else:
# Checking and printing WA version and phone number
self.__version = findall(r"\d(?:\.\d{1,3}){3}", self.header.info.app_version)
if len(self.__version) != 1:
l.error('WhatsApp version not found')
else:
l.debug("WhatsApp version: {}".format(self.__version[0]))
if len(self.header.info.jidSuffix) != 2:
l.error("The phone number end is not 2 characters long")
l.debug("Your phone number ends with {}".format(self.header.info.jidSuffix))
if len(self.header.c15_iv.IV) != 0:
# DB Header is crypt15
# if type(key) is not Key15:
# l.error("You are using a crypt14 key file with a crypt15 backup.")
raise ValueError("Crypt15 file in crypt14 constructor!")
elif len(self.header.c14_cipher.IV) != 0:
# DB Header is crypt14
# if type(key) is not Key14:
# l.fatal("You are using a crypt15 key file with a crypt14 backup.")
# if key.cipher_version != p.c14_cipher.version.cipher_version:
# l.error("Cipher version mismatch: {} != {}"
# .format(key.cipher_version, p.c14_cipher.cipher_version))
# Fix bytes to string encoding
# key.key_version = (key.key_version[0] + 48).to_bytes(1, byteorder='big')
# if key.key_version != p.c14_cipher.key_version:
# if key.key_version > p.c14_cipher.key_version:
# l.error("Key version mismatch: {} != {} .\n "
# .format(key.key_version, p.c14_cipher.key_version) +
# "Your backup is too old for this key file.\n " +
# "Please try using a newer backup.")
# elif key.key_version < p.c14_cipher.key_version:
# l.error("Key version mismatch: {} != {} .\n "
# .format(key.key_version, p.c14_cipher.key_version) +
# "Your backup is too new for this key file.\n " +
# "Please try using an older backup, or getting the new key.")
# else:
# l.error("Key version mismatch: {} != {} (?)"
# .format(key.key_version, p.c14_cipher.key_version))
# if key.get_serversalt() != p.c14_cipher.server_salt:
# l.error("Server salt mismatch: {} != {}".format(key.get_serversalt(), p.c14_cipher.server_salt))
# if key.get_googleid() != p.c14_cipher.google_id:
# l.error("Google ID mismatch: {} != {}".format(key.get_googleid(), p.c14_cipher.google_id))
if len(self.header.c14_cipher.IV) != 16:
l.error("IV is not 16 bytes long but is {} bytes long".format(
len(self.header.c14_cipher.IV)))
self.__iv = self.header.c14_cipher.IV
else:
l.error("Could not parse the IV from the protobuf message. Please report a bug.")
raise ValueError
except DecodeError as e:
print(e)
except OSError as e:
l.fatal("Reading database header failed: {}".format(e))
else:
if iv:
self.__iv = iv
else:
self.__iv = urandom(16)
def encrypt(self, key: Key, props: Props, decrypted: bytes) -> bytes:
"""Encrypts the database using the provided key"""
from wa_crypt_tools.proto import C14_cipher_pb2 as C14_cipher
from wa_crypt_tools.proto import key_type_pb2 as key_type
cipher = C14_cipher.C14_cipher()
# TODO which ones take priority? Key or self values?
cipher.cipher_version = key.get_cipher_version()
#FIXME
cipher.key_version = "2".encode()
cipher.server_salt = key.get_serversalt()
cipher.google_id = key.get_googleid()
cipher.IV = self.__iv
from wa_crypt_tools.proto import backup_prefix_pb2 as prefix
from wa_crypt_tools.proto import key_type_pb2 as key_type
prefix = prefix.BackupPrefix()
prefix.key_type = 0
prefix.c14_cipher.CopyFrom(cipher)
prefix.info.CopyFrom(props.get_proto())
prefix = prefix.SerializeToString()
out = b''
file_hash = md5()
out += len(prefix).to_bytes(1, byteorder='big')
file_hash.update(out)
if len(props.get_features()) > 0:
out += b'\x01'
file_hash.update(b'\x01')
out += prefix
file_hash.update(prefix)
cipher = AES.new(key.get(), AES.MODE_GCM, self.__iv)
encrypted_data, authentication_tag = cipher.encrypt_and_digest(decrypted)
out += encrypted_data
file_hash.update(encrypted_data)
out += authentication_tag
file_hash.update(authentication_tag)
out += file_hash.digest()
return out
def __str__(self):
return f"""cipher_version: {self.cipher_version}
key_version: {self.key_version}
serversalt: {self.serversalt}
googleid: {self.googleid}
iv: {self.iv}"""
def get_iv(self) -> bytes:
return self.__iv
def decrypt(self, key: Key14, encrypted: bytes) -> bytes:
"""Decrypts the database using the provided key"""
checksum = encrypted[-16:]
authentication_tag = encrypted[-32:-16]
encrypted_data = encrypted[:-32]
is_multifile_backup = False
self.file_hash.update(encrypted_data)
self.file_hash.update(authentication_tag)
if self.file_hash.digest() != checksum:
# We are probably in a multifile backup, which does not have a checksum.
is_multifile_backup = True
else:
l.debug("Checksum OK ({}). Decrypting...".format(self.file_hash.hexdigest()))
cipher = AES.new(key.get(), AES.MODE_GCM, self.__iv)
try:
output_decrypted: bytes = cipher.decrypt(encrypted_data)
except ValueError as e:
l.fatal("Decryption failed: {}."
"\n This probably means your backup is corrupted.".format(e))
raise e
# Verify the authentication tag
try:
if is_multifile_backup:
# In multifile backups, there is no checksum.
# This means, the last 16 bytes of the files are not the checksum,
# despite being called "checksum", but are the authentication tag.
# Same way, "authentication tag" is not the tag, but the last
# 16 bytes of the encrypted file.
output_decrypted += cipher.decrypt(authentication_tag)
cipher.verify(checksum)
else:
cipher.verify(authentication_tag)
except ValueError as e:
l.error("Authentication tag mismatch: {}."
"\n This probably means your backup is corrupted.".format(e))
return output_decrypted
================================================
FILE: src/wa_crypt_tools/lib/db/db15.py
================================================
import logging
from hashlib import md5
from os import urandom
from re import findall
from Cryptodome.Cipher import AES
from google.protobuf.message import DecodeError
from wa_crypt_tools.lib.props import Props
log = logging.getLogger(__name__)
from wa_crypt_tools.lib.db.db import Database
from wa_crypt_tools.lib.key.key15 import Key15
class Database15(Database):
def __str__(self):
return "Database15"
# todo
def __init__(self, *, key: Key15 = None, encrypted=None, iv: bytes = None
, props: Props = None):
self.file_hash = md5()
# just store it for now
self.props = props
if encrypted:
try:
from wa_crypt_tools.proto import backup_prefix_pb2 as prefix
from wa_crypt_tools.proto import key_type_pb2 as key_type
except ImportError as e:
log.error("Could not import the proto classes: {}".format(e))
if str(e).startswith("cannot import name 'builder' from 'google.protobuf.internal'"):
log.error("You need to upgrade the protobuf library to at least 3.20.0.\n"
" python -m pip install --upgrade protobuf")
elif str(e).startswith("no module named"):
log.error("Please download them and put them in the \"proto\" sub folder.")
raise e
except AttributeError as e:
log.error("Could not import the proto classes: {}\n ".format(e) +
"Your protobuf library is probably too old.\n "
"Please upgrade to at least version 3.20.0 , by running:\n "
"python -m pip install --upgrade protobuf")
raise e
self.header = prefix.BackupPrefix()
log.debug("Parsing database header...")
try:
# The first byte is the size of the upcoming protobuf message
protobuf_size = encrypted.read(1)
self.file_hash.update(protobuf_size)
protobuf_size = int.from_bytes(protobuf_size, byteorder='big')
# A 0x01 as a second byte indicates the presence of the feature table in the protobuf.
# It is optional and present only in msgstore database, although
# I found some old msgstore backups without it, so it is optional.
msgstore_features_flag = encrypted.peek(1)[0]
if msgstore_features_flag != 1:
msgstore_features_flag = 0
else:
self.file_hash.update(encrypted.read(1))
if not msgstore_features_flag:
log.debug("No feature table found (not a msgstore DB or very old)")
try:
protobuf_raw = encrypted.read(protobuf_size)
self.file_hash.update(protobuf_raw)
if self.header.ParseFromString(protobuf_raw) != protobuf_size:
log.error("Protobuf message not fully read. Please report a bug.")
else:
# Checking and printing WA version and phone number
version = findall(r"\d(?:\.\d{1,3}){3}", self.header.info.app_version)
if len(version) != 1:
log.error('WhatsApp version not found')
else:
log.debug("WhatsApp version: {}".format(version[0]))
if len(self.header.info.jidSuffix) != 2:
log.error("The phone number end is not 2 characters long")
log.debug("Your phone number ends with {}".format(self.header.info.jidSuffix))
if len(self.header.c15_iv.IV) != 0:
# DB Header is crypt15
# if type(key) is not Key15:
# l.error("You are using a crypt14 key file with a crypt15 backup.")
if len(self.header.c15_iv.IV) != 16:
log.error(
"IV is not 16 bytes long but is {} bytes long".format(len(self.header.c15_iv.IV)))
iv = self.header.c15_iv.IV
elif len(self.header.c14_cipher.IV) != 0:
raise ValueError("Crypt14 file in crypt15 constructor!")
else:
log.error("Could not parse the IV from the protobuf message. Please report a bug.")
raise ValueError
except DecodeError as e:
log.error("Could not parse the protobuf message: {}".format(e))
raise e
except OSError as e:
log.fatal("Reading database header failed: {}".format(e))
raise e
else:
if iv:
if len(iv) != 16:
log.error("IV is not 16 bytes long but is {} bytes long".format(len(iv)))
self.iv = iv
else:
self.iv = urandom(16)
def decrypt(self, key: Key15, encrypted: bytes) -> bytes:
"""Decrypts the database using the provided key"""
checksum = encrypted[-16:]
authentication_tag = encrypted[-32:-16]
encrypted_data = encrypted[:-32]
is_multifile_backup = False
self.file_hash.update(encrypted_data)
self.file_hash.update(authentication_tag)
if self.file_hash.digest() != checksum:
# We are probably in a multifile backup, which does not have a checksum.
is_multifile_backup = True
else:
log.debug("Checksum OK ({}). Decrypting...".format(self.file_hash.hexdigest()))
cipher = AES.new(key.get(), AES.MODE_GCM, self.iv)
try:
output_decrypted: bytes = cipher.decrypt(encrypted_data)
except ValueError as e:
log.fatal("Decryption failed: {}."
"\n This probably means your backup is corrupted.".format(e))
raise e
# Verify the authentication tag
try:
if is_multifile_backup:
# In multifile backups, there is no checksum.
# This means, the last 16 bytes of the files are not the checksum,
# despite being called "checksum", but are the authentication tag.
# Same way, "authentication tag" is not the tag, but the last
# 16 bytes of the encrypted file.
output_decrypted += cipher.decrypt(authentication_tag)
cipher.verify(checksum)
else:
cipher.verify(authentication_tag)
except ValueError as e:
log.error("Authentication tag mismatch: {}."
"\n This probably means your backup is corrupted.".format(e))
return output_decrypted
def encrypt(self, key: Key15, props: Props, decrypted: bytes) -> bytes:
"""Encrypts the database using the provided key"""
from wa_crypt_tools.proto import C15_IV_pb2 as C15_IV
cipher = C15_IV.C15_IV()
cipher.IV = self.iv
from wa_crypt_tools.proto import backup_prefix_pb2 as prefix
from wa_crypt_tools.proto import key_type_pb2 as key_type
prefix = prefix.BackupPrefix()
prefix.key_type = key_type.Key_Type.HSM_CONTROLLED
prefix.c15_iv.CopyFrom(cipher)
prefix.info.CopyFrom(props.get_proto())
prefix = prefix.SerializeToString()
out = b''
file_hash = md5()
out += len(prefix).to_bytes(1, byteorder='big')
file_hash.update(out)
out += b'\x01'
file_hash.update(b'\x01')
out += prefix
file_hash.update(prefix)
cipher = AES.new(key.get(), AES.MODE_GCM, self.iv)
encrypted_data, authentication_tag = cipher.encrypt_and_digest(decrypted)
out += encrypted_data
file_hash.update(encrypted_data)
out += authentication_tag
file_hash.update(authentication_tag)
out += file_hash.digest()
return out
def get_iv(self) -> bytes:
return self.iv
================================================
FILE: src/wa_crypt_tools/lib/db/dbfactory.py
================================================
import logging
from google.protobuf.message import DecodeError
from wa_crypt_tools.lib.constants import C
from wa_crypt_tools.lib.db.db12 import Database12
from wa_crypt_tools.lib.db.db14 import Database14
from wa_crypt_tools.lib.db.db15 import Database15
from wa_crypt_tools.lib.props import Props
from wa_crypt_tools.lib.utils import header_info
log = logging.getLogger(__name__)
from hashlib import md5
from re import findall
class DatabaseFactory:
@staticmethod
def from_file(encrypted):
try:
from wa_crypt_tools.proto import backup_prefix_pb2 as prefix
from wa_crypt_tools.proto import key_type_pb2 as key_type
except ImportError as e:
log.error("Could not import the proto classes: {}".format(e))
if str(e).startswith("cannot import name 'builder' from 'google.protobuf.internal'"):
log.error("You need to upgrade the protobuf library to at least 3.20.0.\n"
" python -m pip install --upgrade protobuf")
elif str(e).startswith("no module named"):
log.error("Please download them and put them in the \"proto\" sub folder.")
raise e
except AttributeError as e:
log.error("Could not import the proto classes: {}\n ".format(e) +
"Your protobuf library is probably too old.\n "
"Please upgrade to at least version 3.20.0 , by running:\n "
"python -m pip install --upgrade protobuf")
raise e
header = prefix.BackupPrefix()
log.debug("Parsing database header...")
try:
file_hash = md5()
# The first byte is the size of the upcoming protobuf message
protobuf_size = encrypted.read(1)
file_hash.update(protobuf_size)
protobuf_size = int.from_bytes(protobuf_size, byteorder='big')
# A 0x01 as a second byte indicates the presence of the feature table in the protobuf.
# It is optional and present only in msgstore database, although
# I found some old msgstore backups without it, so it is optional.
msgstore_features_flag = encrypted.peek(1)[0]
if msgstore_features_flag != 1:
msgstore_features_flag = 0
else:
file_hash.update(encrypted.read(1))
if not msgstore_features_flag:
log.debug("No feature table found (not a msgstore DB or very old)")
try:
protobuf_raw = encrypted.read(protobuf_size)
file_hash.update(protobuf_raw)
if header.ParseFromString(protobuf_raw) != protobuf_size:
log.error("Protobuf message not fully read. Please report a bug.")
else:
# Checking and printing WA version and phone number
version = findall(r"\d(?:\.\d{1,3}){3}", header.info.app_version)
if len(version) != 1:
log.error('WhatsApp version not found')
else:
log.debug("WhatsApp version: {}".format(version[0]))
if len(header.info.jidSuffix) != 2:
log.error("The phone number end is not 2 characters long")
log.debug("Your phone number ends with {}".format(header.info.jidSuffix))
if len(header.c15_iv.IV) != 0:
# DB Header is crypt15
# if type(key) is not Key15:
# l.error("You are using a crypt14 key file with a crypt15 backup.")
if len(header.c15_iv.IV) != 16:
log.error("IV is not 16 bytes long but is {} bytes long".format(len(header.c15_iv.IV)))
iv = header.c15_iv.IV
elif len(header.c14_cipher.IV) != 0:
# DB Header is crypt14
# if type(key) is not Key14:
# l.fatal("You are using a crypt15 key file with a crypt14 backup.")
# if key.cipher_version != p.c14_cipher.version.cipher_version:
# l.error("Cipher version mismatch: {} != {}"
# .format(key.cipher_version, p.c14_cipher.cipher_version))
# Fix bytes to string encoding key.key_version = (key.key_version[0] + 48).to_bytes(1,
# byteorder='big') if key.key_version != p.c14_cipher.key_version: if key.key_version >
# p.c14_cipher.key_version: l.error("Key version mismatch: {} != {} .\n " .format(
# key.key_version, p.c14_cipher.key_version) + "Your backup is too old for this key file.\n
# " + "Please try using a newer backup.") elif key.key_version < p.c14_cipher.key_version:
# l.error("Key version mismatch: {} != {} .\n " .format(key.key_version,
# p.c14_cipher.key_version) + "Your backup is too new for this key file.\n " + "Please try
# using an older backup, or getting the new key.") else: l.error("Key version mismatch: {} !=
# {} (?)" .format(key.key_version, p.c14_cipher.key_version)) if key.get_serversalt() !=
# p.c14_cipher.server_salt: l.error("Server salt mismatch: {} != {}".format(
# key.get_serversalt(), p.c14_cipher.server_salt)) if key.get_googleid() !=
# p.c14_cipher.google_id: l.error("Google ID mismatch: {} != {}".format(key.get_googleid(),
# p.c14_cipher.google_id))
if len(header.c14_cipher.IV) != 16:
log.error(
"IV is not 16 bytes long but is {} bytes long".format(len(header.c14_cipher.IV)))
iv = header.c14_cipher.IV
else:
log.error("Could not parse the IV from the protobuf message. Please report a bug.")
raise DecodeError
# We are done here
log.debug(header_info(header))
props = Props(v_features=header.info)
if header.c15_iv.IV:
db = Database15(iv=iv, props=props)
db.file_hash = file_hash
return db
elif header.c14_cipher.IV:
db = Database14(iv=iv, props=props)
db.file_hash = file_hash
return db
else:
log.error("Could not parse the IV from the protobuf message. Please report a bug.")
raise DecodeError
except DecodeError:
# try again as a crypt12
log.debug("Could not parse the protobuf message as a crypt14/15. Trying as a crypt12...")
try:
encrypted.seek(0)
except OSError as e:
log.fatal("Could not reset the file pointer: {}".format(e))
raise e
return Database12(encrypted=encrypted)
except OSError as e:
log.fatal("Reading database header failed: {}".format(e))
================================================
FILE: src/wa_crypt_tools/lib/key/key.py
================================================
from __future__ import annotations
import abc
class Key(abc.ABC):
@abc.abstractmethod
def __init__(self, keyarray: bytes = None):
pass
@abc.abstractmethod
def __str__(self) -> str:
pass
@abc.abstractmethod
def get(self) -> bytes:
pass
@abc.abstractmethod
def dump(self) -> bytes:
pass
================================================
FILE: src/wa_crypt_tools/lib/key/key14.py
================================================
from hashlib import sha256
from os import urandom
from pathlib import Path
from javaobj import JavaObjectMarshaller
from wa_crypt_tools.lib.key.key import Key
from wa_crypt_tools.lib.utils import create_jba
import logging
log = logging.getLogger(__name__)
class Key14(Key):
# These constants are only used with crypt12/14 keys.
__SUPPORTED_CIPHER_VERSION = b'\x00\x01'
__SUPPORTED_KEY_VERSIONS = [b'\x01', b'\x02', b'\x03']
def __init__(self, keyarray: bytes = None,
cipher_version: bytes = None, key_version: bytes = None,
serversalt: bytes = None, googleid: bytes = None, hashedgoogleid: bytes = None,
iv: bytes = None, key: bytes = None):
"""Extracts the fields from a crypt14 loaded key file."""
# key file format and encoding explanation:
# The key file is actually a serialized byte[] object.
# After deserialization, we will have a byte[] object that we have to split in:
# 1) The cipher version (2 bytes). Known values are 0x0000 and 0x0001. So far we only support the latter.
# SUPPORTED_CIPHER_VERSION = b'\x00\x01'
# 2) The key version (1 byte). All the known versions are supported.
# SUPPORTED_KEY_VERSIONS = [b'\x01', b'\x02', b'\x03']
# Looks like nothing actually changes between the versions.
# 3) Server salt (32 bytes)
# 4) googleIdSalt (unused?) (16 bytes)
# 5) hashedGoogleID (The SHA-256 hash of googleIdSalt) (32 bytes)
# 6) encryption IV (zeroed out, as it is read from the database) (16 bytes)
# 7) cipherKey (The actual AES-256 decryption key) (32 bytes)
if keyarray is None:
# Randomly generated key or with supplied parameters
if cipher_version is None:
self.__cipher_version = self.__SUPPORTED_CIPHER_VERSION
else:
if cipher_version != self.__SUPPORTED_CIPHER_VERSION:
log.error("Invalid cipher version: {}".format(cipher_version.hex()))
self.__cipher_version = cipher_version
if key_version is None:
self.__key_version = self.__SUPPORTED_KEY_VERSIONS[-1]
else:
if key_version not in self.__SUPPORTED_KEY_VERSIONS:
log.error("Invalid key version: {}".format(key_version.hex()))
self.__key_version = key_version
if serversalt is None:
self.__serversalt = urandom(32)
else:
if len(serversalt) != 32:
raise ValueError("Invalid server salt length: {}".format(serversalt.hex()))
self.__serversalt = serversalt
if googleid is None:
self.__googleid = urandom(16)
else:
if len(googleid) != 16:
raise ValueError("Invalid google id length: {}".format(googleid.hex()))
self.__googleid = googleid
if hashedgoogleid is None:
self.__hashedgoogleid = sha256(self.__googleid).digest()
else:
log.warning("Using supplied hashed google id")
if len(hashedgoogleid) != 32:
log.error("Invalid hashed google id length: {}".format(hashedgoogleid.hex()))
self.__hashedgoogleid = hashedgoogleid
if iv is None:
self.__padding = b'\x00' * 16
else:
if len(iv) != 16:
log.error("Invalid IV length: {}".format(iv.hex()))
if iv != b'\x00' * 16:
log.warning("IV should be empty")
self.__padding = iv
if key is None:
self.__key = urandom(32)
else:
if len(key) != 32:
log.error("Invalid key length: {}".format(key.hex()))
self.__key = key
return
# Check if the keyfile has a supported cipher version
self.__cipher_version = keyarray[:len(self.__SUPPORTED_CIPHER_VERSION)]
if self.__SUPPORTED_CIPHER_VERSION != self.__cipher_version:
log.error("Invalid keyfile: Unsupported cipher version {}"
.format(keyarray[:len(self.__SUPPORTED_CIPHER_VERSION)].hex()))
index = len(self.__SUPPORTED_CIPHER_VERSION)
# Check if the keyfile has a supported key version
version_supported = False
for v in self.__SUPPORTED_KEY_VERSIONS:
if v == keyarray[index:index + len(self.__SUPPORTED_KEY_VERSIONS[0])]:
version_supported = True
self.__key_version = v
break
if not version_supported:
log.error('Invalid keyfile: Unsupported key version {}'
.format(keyarray[index:index + len(self.__SUPPORTED_KEY_VERSIONS[0])].hex()))
self.__serversalt = keyarray[3:35]
# Check the SHA-256 of the salt
self.__googleid = keyarray[35:51]
expected_digest = sha256(self.__googleid).digest()
actual_digest = keyarray[51:83]
if expected_digest != actual_digest:
log.error("Invalid keyfile: Invalid SHA-256 of salt.\n "
"Expected: {}\n Got:{}".format(expected_digest, actual_digest))
self.__hashedgoogleid = actual_digest
self.__padding = keyarray[83:99]
# Check if IV is made of zeroes
for byte in self.__padding:
if byte:
log.error("Invalid keyfile: IV is not zeroed out but is: {}".format(self.__padding.hex()))
break
self.__key = keyarray[99:]
log.info("Crypt12/14 key loaded")
def get(self) -> bytes:
return self.__key
def get_serversalt(self) -> bytes:
return self.__serversalt
def get_googleid(self) -> bytes:
return self.__googleid
def get_cipher_version(self) -> bytes:
return self.__cipher_version
def get_key_version(self) -> bytes:
return self.__key_version
def __str__(self) -> str:
"""Returns a string representation of the key"""
try:
string: str = "Key14("
if self.__key is not None:
string += "key: {}".format(self.__key.hex())
if self.__serversalt is not None:
string += " , serversalt: {}".format(self.__serversalt.hex())
if self.__googleid is not None:
string += " , googleid: {}".format(self.__googleid.hex())
if self.__key_version is not None:
string += " , key_version: {}".format(self.__key_version.hex())
if self.__cipher_version is not None:
string += " , cipher_version: {}".format(self.__cipher_version.hex())
return string + ")"
except Exception as e:
return "Exception printing key: {}".format(e)
def __repr__(self) -> str:
# TODO
return self.__str__()
def dump(self) -> bytes:
"""Dumps the key to a file"""
out: bytes = b''
out += self.__cipher_version
out += self.__key_version
out += self.__serversalt
out += self.__googleid
out += self.__hashedgoogleid
out += self.__padding
out += self.__key
return JavaObjectMarshaller().dump(create_jba(out))
def file_dump(self, file: Path):
with open(file, 'wb') as f:
f.write(self.dump())
================================================
FILE: src/wa_crypt_tools/lib/key/key15.py
================================================
import hmac
from hashlib import sha256
from os import urandom
from pathlib import Path
from javaobj import JavaObjectMarshaller
from wa_crypt_tools.lib.utils import create_jba, encryptionloop
from wa_crypt_tools.lib.key.key import Key
import logging
l = logging.getLogger(__name__)
class Key15(Key):
# This constant is only used with crypt15 keys.
BACKUP_ENCRYPTION = b'backup encryption'
def __init__(self, keyarray: bytes = None, key: bytes = None):
"""Extracts the key from a loaded crypt15 key file."""
# encrypted_backup.key file format and encoding explanation:
# The E2E key file is actually a serialized byte[] object.
# After deserialization, we will have the root key (32 bytes).
# The root key is further encoded with three different strings, depending on what you want to do.
# These three ways are "backup encryption";
# "metadata encryption" and "metadata authentication", for Google Drive E2E encrypted metadata.
# We are only interested in the local backup encryption.
# Why the \x01 at the end of the BACKUP_ENCRYPTION constant?
# Whatsapp uses a nested encryption function to encrypt many times the same data.
# The iteration counter is appended to the end of the encrypted data. However,
# since the loop is actually executed only one time, we will only have one interaction,
# and thus a \x01 at the end.
# Take a look at utils/wa_hmacsha256_loop.java that is the original code.
if keyarray is None:
# Randomly generated key or with supplied parameters
if key is None:
self.__key = urandom(32)
else:
if len(key) != 32:
l.error("Invalid key length: {}".format(key.hex()))
self.__key = key
return
if not isinstance(keyarray, bytes):
raise ValueError("keyarray is not a byte array!")
if len(keyarray) != 32:
raise ValueError("Invalid key length")
l.debug("Root key: {}".format(keyarray.hex()))
# Save the root key in the class
self.__key = keyarray
l.info("Crypt15 / Raw key loaded")
def get(self) -> bytes:
"""
Returns the key used for encryption, that is not the root key.
"""
return encryptionloop(
first_iteration_data=self.__key,
message=b'backup encryption',
output_bytes=32)
def get_root(self) -> bytes:
"""
Returns the root key.
"""
return self.__key
def get_metadata_encryption(self) -> bytes:
"""
Returns the key used for metadata encryption
"""
return encryptionloop(
first_iteration_data=self.__key,
message=b'metadata encryption',
output_bytes=32)
def get_metadata_authentication(self) -> bytes:
"""
Returns the key used for metadata authentication
"""
return encryptionloop(
first_iteration_data=self.__key,
message=b'metadata authentication',
output_bytes=32)
def dump(self) -> bytes:
"""Dumps the key"""
return JavaObjectMarshaller().dump(create_jba(self.__key))
def file_dump(self, file: Path):
with open(file, 'wb') as f:
f.write(self.dump())
def __str__(self) -> str:
"""Returns a string representation of the key"""
try:
string: str = "Key15("
if self.__key is not None:
string += "key: {}".format(self.__key.hex())
return string + ")"
except Exception as e:
return "Exception printing key: {}".format(e)
def __repr__(self) -> str:
# TODO
return self.__str__()
================================================
FILE: src/wa_crypt_tools/lib/key/keyfactory.py
================================================
from pathlib import Path
import javaobj.v2 as javaobj
from wa_crypt_tools.lib.key.key14 import Key14
from wa_crypt_tools.lib.key.key15 import Key15
import logging
from wa_crypt_tools.lib.utils import javaintlist2bytes, hexstring2bytes
l = logging.getLogger(__name__)
class KeyFactory:
@staticmethod
def new(file: Path):
"""Tries to load the key from a file, or if it fails, from a hex string."""
try:
return KeyFactory.from_file(file)
except OSError:
try:
return KeyFactory.from_hex(str(file))
except ValueError:
l.critical("The key file specified does not exist.\n "
"If you tried to specify the key directly, note it should be "
"64 characters long and not {} characters long.".format(len(str(file))))
@staticmethod
def from_file(file: Path):
keyfile: bytes = b''
l.debug("Reading keyfile...")
# Try to open the keyfile.
try:
key_file_stream = open(file, 'rb')
try:
# Deserialize the byte object written in the file
jarr: javaobj.beans.JavaArray = javaobj.load(key_file_stream).data
# Convert from a list of Int8 to a byte array
keyfile: bytes = javaintlist2bytes(jarr)
except (ValueError, RuntimeError) as e:
l.critical("The keyfile is not a valid Java object: {}".format(e))
except OSError:
l.info("The keyfile could not be opened.")
raise OSError
# We guess the key type from its length
if len(keyfile) == 131:
return Key14(keyarray=keyfile)
elif len(keyfile) == 32:
return Key15(keyarray=keyfile)
else:
l.critical("Unrecognized key file format.")
@staticmethod
def from_hex(hexstring: str) -> Key15:
if hexstring is None or len(hexstring) != 64:
raise ValueError("The key is invalid or of the wrong length.")
barr: bytes = hexstring2bytes(hexstring)
if barr is None or len(barr) != 32:
raise ValueError("The key is invalid or of the wrong length.")
return Key15(keyarray=barr)
================================================
FILE: src/wa_crypt_tools/lib/logformat.py
================================================
import logging
class CustomFormatter(logging.Formatter):
grey = "\x1b[38;20m"
yellow = "\x1b[33;20m"
red = "\x1b[31;20m"
bold_red = "\x1b[31;1m"
reset = "\x1b[0m"
format = "%(filename)s:%(lineno)d \t: [%(levelname).1s] %(message)s"
FORMATS = {
logging.DEBUG: grey + format + reset,
logging.INFO: grey + format + reset,
logging.WARNING: yellow + format + reset,
logging.ERROR: red + format + reset,
logging.CRITICAL: bold_red + format + reset
}
def format(self, record):
log_fmt = self.FORMATS.get(record.levelno)
formatter = logging.Formatter(log_fmt)
return formatter.format(record)
================================================
FILE: src/wa_crypt_tools/lib/props.py
================================================
from __future__ import annotations
from wa_crypt_tools.lib.constants import C
from wa_crypt_tools.proto import backup_expiry_pb2 as backup_expiry
class Props:
def __init__(self, *, v_features=None, wa_version: str = C.DEFAULT_APP_VERSION, jid: str = C.DEFAULT_JID_SUFFIX,
features: list[int] | None = C.DEFAULT_FEATURE_LIST, max_feature: int = C.DEFAULT_MAX_FEATURE,
backup_version: int = C.DEFAULT_BACKUP_VERSION):
if v_features is not None:
self.props = v_features
return
self.props = backup_expiry.BackupExpiry()
self.props.app_version = wa_version
self.props.jidSuffix = jid
self.max_feature = max_feature
if features is None or len(features) == 0:
return
self.props.backup_version = backup_version
for f in range(5, max_feature + 1):
try:
self.disable_feature(f)
except AttributeError:
pass
for f in features:
self.enable_feature(f)
def enable_feature(self, feature: int):
feature_name = "f_" + str(feature)
setattr(self.props, feature_name, True)
def disable_feature(self, feature: int):
feature_name = "f_" + str(feature)
setattr(self.props, feature_name, False)
def get_feature(self, feature: int) -> bool:
feature_name = "f_" + str(feature)
return getattr(self.props, feature_name)
def get_features(self) -> list[int]:
features = []
for i in range(5, self.max_feature + 1):
try:
if self.get_feature(i):
features.append(i)
except AttributeError:
pass
return features
def get_wa_version(self) -> str:
return self.props.version
def get_jid(self) -> str:
return self.props.jidSuffix
def get_proto(self):
return self.props
def __str__(self):
return str(self.props)
================================================
FILE: src/wa_crypt_tools/lib/utils.py
================================================
import base64
import hmac
import json
import math
import zlib
from hashlib import sha256
from Cryptodome.Cipher import AES
from javaobj import JavaByteArray
from javaobj.v2.beans import JavaArray, JavaClassDesc, ClassDescType
import logging
from wa_crypt_tools.lib.constants import C
# FIXME a "utils" file shouldn't have its own logger
l = logging.getLogger(__name__)
def test_decompression(test_data: bytes) -> bool:
"""Returns true if the SQLite header is valid.
It is assumed that the data are valid.
(If it is valid, it also means the decryption and decompression were successful.)"""
# If we get a ZIP file header, return true
if test_data[:4] == C.ZIP_HEADER:
return True
try:
zlib_obj = zlib.decompressobj().decompress(test_data)
# These two errors should never happen
if len(zlib_obj) < 16:
l.error("Test decompression: chunk too small")
return False
# Decoding can fail if first two bytes are a bad UTF-8 char
if zlib_obj[:15].decode('ascii') != 'SQLite format 3':
l.error("Test decompression: Decryption and decompression ok but not a valid SQLite database")
return False
else:
return True
except (zlib.error, UnicodeDecodeError):
return False
def create_jba(out: bytes) -> JavaByteArray:
"""Creates a JavaByteArray object from a bytes array"""
# Create the classdesc
cd = JavaClassDesc(ClassDescType.NORMALCLASS)
cd.name = "[B"
cd.superclass = None
cd.serial_version_uid = -5984413125824719648
cd.desc_flags = 2
return JavaByteArray(out, classdesc=cd)
def hexstring2bytes(string: str) -> bytes:
"""Converts a hex string into a bytes array"""
if len(string) != 64:
l.critical("The key file specified does not exist.\n "
"If you tried to specify the key directly, note it should be "
"64 characters long and not {} characters long.".format(len(string)))
barr = None
try:
barr = bytes.fromhex(string)
except ValueError as e:
l.critical("Couldn't convert the hex string.\n "
"Exception: {}".format(e))
if len(barr) != 32:
l.error("The key is not 32 bytes long but {} bytes long.".format(len(barr)))
return barr
def javaintlist2bytes(barr: JavaArray) -> bytes:
"""Converts a javaobj bytearray which somehow became a list of signed integers back to a Python byte array"""
out: bytes = b''
for i in barr:
out += i.to_bytes(1, byteorder='big', signed=True)
return out
def encryptionloop(*, first_iteration_data: bytes, privateseed: bytes = b'\x00' * 32, message: bytes,
output_bytes: int):
# The private key and the seed are used to create the HMAC key
privatekey = hmac.new(privateseed, msg=first_iteration_data, digestmod=sha256).digest()
data = b''
output = b''
permutations = int(math.ceil(float(output_bytes) / float(32)))
i = 1
while i < permutations + 1:
hasher = hmac.new(privatekey, msg=data, digestmod=sha256)
if message is not None:
hasher.update(message)
hasher.update(i.to_bytes(1, byteorder='big'))
data = hasher.digest()
bytestowrite = min(output_bytes, len(data))
output += data[:bytestowrite]
i += 1
return output
def mcrypt1_metadata_decrypt(*, key, encoded: str):
"""
Decrypts the metadata of a mcrypt1 file.
:param key: The key used to decrypt the metadata
:param encoded: The metadata downloaded from Google Drive in base64
:return: The decrypted JSON
"""
# Base64 decoding
encoded = base64.b64decode(encoded)
# PKCS5Padding is not natively supported
unpad = lambda s: s[:-ord(s[len(s) - 1:])]
iv_size = encoded[0]
if iv_size != 16:
raise Exception("IV Size is not 16")
iv = encoded[1:17]
mac_size = encoded[17]
if mac_size != 32:
raise Exception("MAC Size is not 32")
mac = encoded[18:50]
encrypted_metadata = encoded[50:]
# Authentication part
hmac_auth = hmac.new(key.get_metadata_authentication(), digestmod='sha256')
hmac_auth.update(iv)
hmac_auth.update(encrypted_metadata)
hmac_auth = hmac_auth.digest()
if hmac_auth != mac:
raise ValueError("MAC does not match")
# Decryption part
cipher = AES.new(key.get_metadata_encryption(), AES.MODE_CBC, iv)
decrypted_metadata = cipher.decrypt(encrypted_metadata)
decrypted_metadata = unpad(decrypted_metadata)
# Load the JSON
return json.loads(decrypted_metadata.decode('utf-8'))
def get_mcrypt1_name(*, key, name: str, md5: bytes) -> bytes:
hmac_n = hmac.new(key.get_root(), digestmod='sha256')
# Calculate SHA256 of the name
digest = sha256()
digest.update(name.encode('utf-8'))
# Pour it into the HMAC
hmac_n.update(digest.digest())
# If md5 is a string, convert it to bytes
if isinstance(md5, str):
md5 = bytes.fromhex(md5)
# Now pour the MD5 into the HMAC
hmac_n.update(md5)
media_hash = hmac_n.digest()
return media_hash
def header_info(header):
"""
shows all header, information including the feature vector
FIXME
"""
string: str = ""
if header.c15_iv.IV:
string += "Crypt15 info:\n"
string += str("Header information in your crypt15 file:")
string += str("IV: {}\n".format(header.c15_iv.IV.hex()))
if header.c14_cipher.IV:
string += str("Header information in your crypt14 file:\n")
string += str("Cipher version: {}\n".format(header.c14_cipher.cipher_version.hex()))
string += str("Key version: {}\n".format(header.c14_cipher.key_version.hex()))
string += str("Server salt: {}\n".format(header.c14_cipher.server_salt.hex()))
string += str("Google ID: {}\n".format(header.c14_cipher.google_id.hex()))
string += str("IV: {}\n".format(header.c14_cipher.IV.hex()))
string += str("Key type: {}\n".format(header.key_type))
string += str("WhatsApp version: {}\n".format(header.info.app_version))
#string += str("Device model: {}".format(header.info.device_model))
string += str("The last two numbers of the user's Jid: {}\n".format(header.info.jidSuffix))
string += str("Backup version: {}\n".format(header.info.backup_version))
#string += str("Size of the backup file: {}".format(header.backup_export_file_size))
features = [n for n in [*range(5, 38), 39] if getattr(header.info, "f_" + str(n)) == True]
if len(features) > 0:
string += str("Features: {}\n".format(features))
string += str("Max feature number: {}\n".format(max(features)))
else:
string += str("No feature table found (not a msgstore DB or very old)\n")
return string
================================================
FILE: src/wa_crypt_tools/proto/C14_cipher_pb2.py
================================================
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import runtime_version as _runtime_version
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
_runtime_version.ValidateProtobufRuntimeVersion(_runtime_version.Domain.PUBLIC, 5, 29, 5, '', 'C14_cipher.proto')
_sym_db = _symbol_database.Default()
DESCRIPTOR = _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')
_globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'C14_cipher_pb2', _globals)
if not _descriptor._USE_C_DESCRIPTORS:
DESCRIPTOR._loaded_options = None
_globals['_C14_CIPHER']._serialized_start = 20
_globals['_C14_CIPHER']._serialized_end = 129
================================================
FILE: src/wa_crypt_tools/proto/C15_IV_pb2.py
================================================
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import runtime_version as _runtime_version
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
_runtime_version.ValidateProtobufRuntimeVersion(_runtime_version.Domain.PUBLIC, 5, 29, 5, '', 'C15_IV.proto')
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0cC15_IV.proto"\x14\n\x06C15_IV\x12\n\n\x02IV\x18\x01 \x01(\x0cb\x08editionsp\xe8\x07')
_globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'C15_IV_pb2', _globals)
if not _descriptor._USE_C_DESCRIPTORS:
DESCRIPTOR._loaded_options = None
_globals['_C15_IV']._serialized_start = 16
_globals['_C15_IV']._serialized_end = 36
================================================
FILE: src/wa_crypt_tools/proto/__init__.py
================================================
================================================
FILE: src/wa_crypt_tools/proto/backup_expiry_pb2.py
================================================
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import runtime_version as _runtime_version
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
_runtime_version.ValidateProtobufRuntimeVersion(_runtime_version.Domain.PUBLIC, 5, 29, 5, '', 'backup_expiry.proto')
_sym_db = _symbol_database.Default()
DESCRIPTOR = _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')
_globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'backup_expiry_pb2', _globals)
if not _descriptor._USE_C_DESCRIPTORS:
DESCRIPTOR._loaded_options = None
_globals['_BACKUPEXPIRY']._serialized_start = 24
_globals['_BACKUPEXPIRY']._serialized_end = 573
================================================
FILE: src/wa_crypt_tools/proto/backup_prefix_pb2.py
================================================
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import runtime_version as _runtime_version
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
_runtime_version.ValidateProtobufRuntimeVersion(_runtime_version.Domain.PUBLIC, 5, 29, 5, '', 'backup_prefix.proto')
_sym_db = _symbol_database.Default()
from . import C14_cipher_pb2 as C14__cipher__pb2
from . import C15_IV_pb2 as C15__IV__pb2
from . import key_type_pb2 as key__type__pb2
from . import backup_expiry_pb2 as backup__expiry__pb2
DESCRIPTOR = _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')
_globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'backup_prefix_pb2', _globals)
if not _descriptor._USE_C_DESCRIPTORS:
DESCRIPTOR._loaded_options = None
_globals['_BACKUPPREFIX']._serialized_start = 93
_globals['_BACKUPPREFIX']._serialized_end = 242
================================================
FILE: src/wa_crypt_tools/proto/key_type_pb2.py
================================================
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import runtime_version as _runtime_version
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
_runtime_version.ValidateProtobufRuntimeVersion(_runtime_version.Domain.PUBLIC, 5, 29, 5, '', 'key_type.proto')
_sym_db = _symbol_database.Default()
DESCRIPTOR = _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')
_globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'key_type_pb2', _globals)
if not _descriptor._USE_C_DESCRIPTORS:
DESCRIPTOR._loaded_options = None
_globals['_KEY_TYPE']._serialized_start = 18
_globals['_KEY_TYPE']._serialized_end = 65
================================================
FILE: src/wa_crypt_tools/wacreatekey.py
================================================
#!/usr/bin/env python
"""
This script decrypts WhatsApp's DB files encrypted with Crypt12, Crypt14 or Crypt15.
"""
from __future__ import annotations
import os
from pathlib import Path
from wa_crypt_tools.lib.key.key14 import Key14
from wa_crypt_tools.lib.key.key15 import Key15
from wa_crypt_tools.lib.logformat import CustomFormatter
import argparse
__author__ = 'ElDavo'
__copyright__ = 'Copyright (C) 2023'
__license__ = 'GPLv3'
__status__ = 'Production'
import logging
lo = logging.getLogger(__name__)
def parsecmdline() -> argparse.Namespace:
"""Sets up the argument parser"""
parser = argparse.ArgumentParser(description='Create a key or encrypted_backup.key from a hex input.'
'The only parameter a encrypted_backup.key stores is the key itself.')
parser.add_argument('-c14', '--crypt14', action='store_true', default=False, help='Create a traditional key file.')
parser.add_argument('-o', '--output', type=str,
help='The output file')
parser.add_argument('-y', '--yes', action='store_true', help='Overwrite the output file if it exists.')
parser.add_argument('-v', '--verbose', action='store_true', help='Prints all messages')
parser.add_argument('--hex', type=str, nargs='?', help='The hex string to convert to a key')
parser.add_argument('-cv', '--cipher-version', type=int, help='The cipher version to use. Default: 1')
parser.add_argument('-kv', '--key-version', type=int, help='The key version to use. Default: 3')
parser.add_argument('-ss', '--server-salt', type=str, help='The server salt to use. Default: random')
parser.add_argument('-gi', '--googleid', type=str, help='The google id salt to use. Default: random')
return parser.parse_args()
def main():
args = parsecmdline()
# set wa_crypt_tools l to debug
lo.setLevel(logging.DEBUG if args.verbose else logging.INFO)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG if args.verbose else logging.INFO)
ch.setFormatter(CustomFormatter())
lo.addHandler(ch)
# also add to "wa_crypt_tools.lib" logger
logging.getLogger("wa_crypt_tools.lib").addHandler(ch)
logging.getLogger("wa_crypt_tools.lib").setLevel(logging.DEBUG if args.verbose else logging.INFO)
hex_key = None
if args.hex is None:
lo.warning("Key not specified, a random key will be generated.")
else:
try:
hex_key: bytes = bytes.fromhex(args.hex)
except ValueError:
lo.critical("Key is not in hexadecimal format")
exit(1)
if args.output is None:
args.output = "key" if args.crypt14 else "encrypted_backup.key"
if args.crypt14:
if args.cipher_version is None:
args.cipher_version = 1
if args.key_version is None:
args.key_version = 3
if args.server_salt is None:
lo.warning("Server salt not specified, a random one will be generated.")
if args.googleid is None:
lo.warning("Google id not specified, a random one will be generated.")
try:
key: Key14 = Key14(cipher_version=args.cipher_version.to_bytes(2, "big"),
key_version=args.key_version.to_bytes(1, "big"),
serversalt=bytes.fromhex(args.server_salt) if args.server_salt is not None else None,
googleid=bytes.fromhex(args.googleid) if args.googleid is not None else None,
iv=None,
key=hex_key)
except ValueError as e:
lo.critical(f"Something was not right: {e}")
exit(1)
else:
if args.cipher_version is not None:
lo.warning("Cipher version specified, but it is not used for crypt15 keys, ignoring.")
if args.key_version is not None:
lo.warning("Key version specified, but it is not used for crypt15 keys, ignoring.")
if args.server_salt is not None:
lo.warning("Server salt specified, but it is not used for crypt15 keys, ignoring.")
if args.googleid is not None:
lo.warning("Google id specified, but it is not used for crypt15 keys, ignoring.")
try:
key: Key15 = Key15(keyarray=hex_key)
except ValueError as e:
lo.critical(f"Error while creating the key: {e}")
exit(1)
# Check if the output file exists
output_file = Path(args.output)
print(os.getcwd())
if output_file.is_file() and not args.yes:
lo.fatal("The output file already exists.")
exit(1)
# Write the key file
key.file_dump(output_file)
lo.info("Key file \"{}\" created.".format(args.output))
if __name__ == "__main__":
main()
================================================
FILE: src/wa_crypt_tools/wadecrypt.py
================================================
#!/usr/bin/env python
"""
This script decrypts WhatsApp's DB files encrypted with Crypt12, Crypt14 or Crypt15.
"""
from __future__ import annotations
from wa_crypt_tools.lib.logformat import CustomFormatter
from wa_crypt_tools.lib.key.keyfactory import KeyFactory
from wa_crypt_tools.lib.db.dbfactory import DatabaseFactory
from wa_crypt_tools.lib.utils import test_decompression
# AES import party!
# pycryptodome and PyCryptodomex's implementations of AES are the same,
# so we try to import one of these twos.
try:
# pycryptodomex
from Cryptodome.Cipher import AES
except ModuleNotFoundError:
try:
# pycryptodome
# noinspection PyUnresolvedReferences
from Crypto.Cipher import AES
if not hasattr(AES, 'MODE_GCM'):
# pycrypto
raise ModuleNotFoundError("You installed pycrypto and not pycryptodome(x). "
"Pycrypto is old, deprecated and not supported. \n"
"Run: python -m pip uninstall pycrypto\n"
"And: python -m pip install pycryptodomex\n"
"Or: python -m pip install pycryptodome")
except ModuleNotFoundError:
# crypto (or nothing)
raise ModuleNotFoundError("You need pycryptodome(x) to run these scripts!\n"
"python -m pip install pycryptodome\n"
"Or: python -m pip install pycryptodome\n"
"You can also remove \"crypto\" if you have it installed\n"
"python -m pip uninstall crypto")
# noinspection PyPackageRequirements
# This is from javaobj-py3
# noinspection PyPackageRequirements
import io
from re import findall
from sys import maxsize
from time import sleep
from datetime import date
import argparse
import zlib
__author__ = 'ElDavo'
__copyright__ = 'Copyright (C) 2023'
__license__ = 'GPLv3'
__status__ = 'Production'
import logging
log = logging.getLogger(__name__)
def parsecmdline() -> argparse.Namespace:
"""Sets up the argument parser"""
parser = argparse.ArgumentParser(description='Decrypts WhatsApp backup files'
' encrypted with crypt12, 14 or 15')
parser.add_argument('keyfile', nargs='?', type=str, default="encrypted_backup.key",
help='The WhatsApp encrypted_backup key file or the hex encoded key. '
'Default: encrypted_backup.key')
parser.add_argument('encrypted', nargs='?', type=argparse.FileType('rb'), default="msgstore.db.crypt15",
help='The encrypted crypt12, 14 or 15 file. Default: msgstore.db.crypt15')
parser.add_argument('decrypted', nargs='?', type=argparse.FileType('wb'), default="msgstore.db",
help='The decrypted output file. Default: msgstore.db')
parser.add_argument('-nm', '--no-mem', action='store_true',
help='Does not load files in RAM, stresses the disk more. '
'Default: load files into RAM')
parser.add_argument('-bs', '--buffer-size', type=int, help='How many bytes of data to process at a time. '
'Implies -nm. Default: {}'.format(
io.DEFAULT_BUFFER_SIZE))
parser.add_argument('-nd', '--no-decompress', action='store_true',
help='Does not decompress the decrypted data. '
'Default: decompresses the decrypted data')
parser.add_argument('-v', '--verbose', action='store_true', help='Prints all offsets and messages')
parser.add_argument('-f', '--force', action='store_true', help='Does nothing, but it is here for compatibility')
return parser.parse_args()
def chunked_decrypt(file_hash, cipher, encrypted, decrypted, buffer_size: int = 0, no_decompress: bool = False):
"""
Does the actual decryption chunking bytes, so the file does not get loaded into RAM.
"""
z_obj = zlib.decompressobj()
if cipher is None:
log.fatal("Could not create a decryption cipher")
try:
if buffer_size < 17:
log.info("Invalid buffer size, will use default of {}".format(io.DEFAULT_BUFFER_SIZE))
buffer_size = io.DEFAULT_BUFFER_SIZE
# Does the thing above but only with DEFAULT_BUFFER_SIZE bytes at a time.
# Less RAM used, more I/O used
is_zip = True
# Read the first data chunk (there must be at least one, otherwise the
# encrypted file is clearly malformed).
chunk = encrypted.read(buffer_size)
log.debug("Reading and decrypting...")
if not chunk:
log.error("Encrypted file is empty or truncated.")
else:
while True:
# We will need to manage two chunks at a time, because we might have
# the checksum in both the last chunk and the chunk before that.
# This makes the logic more complicated, but it's the only way to.
checksum = None
try:
next_chunk = encrypted.read(buffer_size)
except MemoryError:
log.fatal("Out of RAM, please use a smaller buffer size.")
break
if len(next_chunk) <= 36:
# Last bytes read. Three cases:
# 1. The checksum is entirely in the last chunk
if len(next_chunk) == 36:
checksum = next_chunk
# 2. The checksum is entirely in the chunk before the last
elif len(next_chunk) == 0:
checksum = chunk[-36:]
chunk = chunk[:-36]
# 3. The checksum is split between the last two chunks
else:
checksum = chunk[-(36 - len(next_chunk)):] + next_chunk
chunk = chunk[:-(36 - len(next_chunk))]
file_hash.update(chunk)
decrypted_chunk = cipher.decrypt(chunk)
if is_zip:
try:
if no_decompress:
decrypted.write(decrypted_chunk)
else:
decrypted.write(z_obj.decompress(decrypted_chunk))
except zlib.error:
if test_decompression(decrypted_chunk):
log.info("Decrypted data is a ZIP file that I will not decompress automatically.")
else:
log.error("I can't recognize decrypted data. Decryption not successful.\n "
"The key probably does not match with the encrypted file.")
is_zip = False
decrypted.write(decrypted_chunk)
else:
decrypted.write(decrypted_chunk)
# The presence of the checksum tells us it's the last chunk
if checksum is not None:
is_multifile_backup = False
crypt12_footer = str(checksum[-4:])
jid = findall(r"(?:-|\d)(?:-|\d)(\d\d)", crypt12_footer)
if len(jid) == 1:
# Confirmed to be crypt12
checksum = checksum[:-4]
log.debug("Your phone number ends with {}".format(jid[0]))
else:
# Shift everything forward by 4 bytes
chunk = checksum[:4]
file_hash.update(chunk)
decrypted_chunk = cipher.decrypt(chunk)
if is_zip:
try:
if no_decompress:
decrypted.write(decrypted_chunk)
else:
decrypted.write(z_obj.decompress(decrypted_chunk))
except zlib.error:
log.error("Backup is corrupted.")
decrypted.write(decrypted_chunk)
else:
decrypted.write(decrypted_chunk)
checksum = checksum[4:]
file_hash.update(checksum[:16])
if file_hash.digest() != checksum[16:]:
is_multifile_backup = True
else:
log.debug("Checksum OK ({})!".format(file_hash.hexdigest()))
try:
if is_multifile_backup:
decrypted.write(cipher.decrypt(checksum[:16]))
cipher.verify(checksum[16:])
else:
cipher.verify(checksum[:16])
except ValueError as e:
log.error("Authentication tag mismatch: {}."
"\n This probably means your backup is corrupted.".format(e))
break
# If there is no more data, we should already have seen a checksum.
if not next_chunk:
log.error("The encrypted database file is truncated (no checksum found).")
break
# Move the sliding window forward.
chunk = next_chunk
if is_zip and not no_decompress and not z_obj.eof:
log.error("The encrypted database file is truncated (damaged).")
decrypted.flush()
except OSError as e:
log.fatal("I/O error: {}".format(e))
finally:
decrypted.close()
encrypted.close()
def main():
args = parsecmdline()
# set wa_crypt_tools l to debug
log.setLevel(logging.DEBUG if args.verbose else logging.INFO)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG if args.verbose else logging.INFO)
ch.setFormatter(CustomFormatter())
log.addHandler(ch)
# also add to "wa_crypt_tools.lib" logger
logging.getLogger("wa_crypt_tools.lib").addHandler(ch)
logging.getLogger("wa_crypt_tools.lib").setLevel(logging.DEBUG if args.verbose else logging.INFO)
if args.buffer_size is not None:
if not 1 < args.buffer_size < maxsize:
log.fatal("Invalid buffer size")
# Get the decryption key from the key file or the hex encoded string.
key = KeyFactory.new(args.keyfile)
log.debug(str(key))
db = DatabaseFactory.from_file(args.encrypted)
cipher = AES.new(key.get(), AES.MODE_GCM, db.get_iv())
if args.buffer_size is not None:
chunked_decrypt(db.file_hash, cipher, args.encrypted, args.decrypted, args.buffer_size, args.no_decompress)
elif args.no_mem:
chunked_decrypt(db.file_hash, cipher, args.encrypted, args.decrypted, io.DEFAULT_BUFFER_SIZE,
args.no_decompress)
else:
output_decrypted: bytearray = db.decrypt(key, args.encrypted.read())
try:
z_obj = zlib.decompressobj()
if args.no_decompress:
output_file = output_decrypted
else:
output_file = z_obj.decompress(output_decrypted)
if not z_obj.eof:
log.error("The encrypted database file is truncated (damaged).")
except zlib.error:
output_file = output_decrypted
if test_decompression(output_file[:io.DEFAULT_BUFFER_SIZE]):
log.info("Decrypted data is a ZIP file that I will not decompress automatically.")
else:
log.error("I can't recognize decrypted data. Decryption not successful.\n "
"The key probably does not match with the encrypted file.\n "
"Or the backup is simply empty. (check with --force)")
args.decrypted.write(output_file)
if date.today().day == 1 and date.today().month == 4:
log.info("Done. Uploading messages to the developer's server...")
sleep(0.5)
log.info("Uploaded. The developer will now read and publish your messages!")
else:
log.info("Done")
if __name__ == "__main__":
main()
================================================
FILE: src/wa_crypt_tools/waencrypt.py
================================================
import argparse
import hashlib
import os
import zlib
import logging
from wa_crypt_tools.lib.constants import C
from wa_crypt_tools.lib.db.db import Database
from wa_crypt_tools.lib.db.db12 import Database12
from wa_crypt_tools.lib.db.db14 import Database14
from wa_crypt_tools.lib.db.db15 import Database15
from wa_crypt_tools.lib.db.dbfactory import DatabaseFactory
from wa_crypt_tools.lib.key.key import Key
from wa_crypt_tools.lib.key.keyfactory import KeyFactory
from wa_crypt_tools.lib.logformat import CustomFormatter
from wa_crypt_tools.lib.props import Props
log = logging.getLogger(__name__)
def parsecmdline() -> argparse.Namespace:
"""Parses the command line arguments."""
"""Sets up the argument parser"""
parser = argparse.ArgumentParser(description='Encrypts a file in Crypt14 or Crypt15 format.')
parser.add_argument('keyfile', nargs='?', type=str, default="encrypted_backup.key",
help='The WhatsApp encrypted_backup key file or the hex encoded key. '
'Default: encrypted_backup.key')
parser.add_argument('decrypted', nargs='?', type=argparse.FileType('rb'), default="msgstore.db",
help='The input file. Default: msgstore.db')
parser.add_argument('encrypted', nargs='?', type=argparse.FileType('wb'), default="msgstore.db.crypt15",
help='The encrypted crypt15 or crypt14 file. Default: msgstore.db.crypt15')
parser.add_argument('-f', '--force', action='store_true',
help='Makes errors non fatal. Default: false')
parser.add_argument('-v', '--verbose', action='store_true', help='Prints all offsets and messages')
parser.add_argument('--enable-features', type=int, nargs='*', default=C.DEFAULT_FEATURE_LIST,
help='Enables the specified features. ')
parser.add_argument('--max-feature', type=int, default=39,
help='The max feature number, the older is the backup the lower should be the number. ')
parser.add_argument('--multi-file', action='store_true',
help='Encrypts a multi-file backup (either stickers or wallpapers)')
parser.add_argument('--type', type=int, choices=[12, 14, 15], default=15,
help='The type of encryption to use. Default: 15')
parser.add_argument('--iv', type=str, help='The IV to use for crypt15 encryption. Default: random')
parser.add_argument('--reference', type=argparse.FileType('rb'),
help='The reference file to use for crypt15 encryption. Highly recommended.')
parser.add_argument('--noparse', action='store_true',
help='Do not parse the header of the reference file. Default: false')
parser.add_argument('--wa-version', type=str, default=C.DEFAULT_APP_VERSION,
help='The WhatsApp version to use for crypt15 encryption. Default:' +
C.DEFAULT_APP_VERSION)
parser.add_argument('--jid', type=str, default=C.DEFAULT_JID_SUFFIX,
help='The last 2 numbers of your phone number. Default: 00')
parser.add_argument('--backup-version', type=int, default=C.DEFAULT_BACKUP_VERSION,
help='The backup version to use in the header of the encrypted file. Default: 0')
parser.add_argument('--no-compress', action='store_true',
help='Do not compress the file. This will make the backup not working. Only used in development. Default: false')
return parser.parse_args()
def main():
"""Main function"""
# Parse the command line arguments
args = parsecmdline()
# set wa_crypt_tools l to debug
log.setLevel(logging.DEBUG if args.verbose else logging.INFO)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG if args.verbose else logging.INFO)
ch.setFormatter(CustomFormatter())
log.addHandler(ch)
log.warning("This script is in beta stage")
# Read the key file
key = KeyFactory.new(args.keyfile)
# If specified, use the IV from the command line
iv = None
props = None
if not args.reference:
if args.iv:
iv = bytes.fromhex(args.iv)
# Create the props object from the command line arguments
props = Props(wa_version=args.wa_version, jid=args.jid, max_feature=args.max_feature,
features=args.enable_features, backup_version=args.backup_version)
else:
reference = DatabaseFactory.from_file(args.reference)
iv: bytes = reference.get_iv()
props = reference.props
data = args.decrypted.read()
if args.type == 15:
db = Database15(key=key, iv=iv)
elif args.type == 14:
db = Database14(key=key, iv=iv)
else:
db = Database12(key=key, iv=iv)
if args.no_compress:
encrypted = db.encrypt(key, props, data)
else:
compressed = zlib.compress(data, 1)
encrypted = db.encrypt(key, props, compressed)
args.encrypted.write(encrypted)
# Close the files
log.info("Done!")
args.decrypted.close()
args.encrypted.close()
if __name__ == '__main__':
main()
================================================
FILE: src/wa_crypt_tools/waguess.py
================================================
# AES import party!
# pycryptodome and PyCryptodomex's implementations of AES are the same,
# so we try to import one of these twos.
import argparse
import io
import zlib
from datetime import date
from re import findall
import logging
from time import sleep
from wa_crypt_tools.lib.constants import C
from wa_crypt_tools.lib.key.keyfactory import KeyFactory
from wa_crypt_tools.lib.logformat import CustomFormatter
from wa_crypt_tools.lib.utils import test_decompression
log = logging.getLogger(__name__)
# AES import party!
# pycryptodome and PyCryptodomex's implementations of AES are the same,
# so we try to import one of these twos.
try:
# pycryptodomex
from Cryptodome.Cipher import AES
except ModuleNotFoundError:
try:
# pycryptodome
# noinspection PyUnresolvedReferences
from Crypto.Cipher import AES
if not hasattr(AES, 'MODE_GCM'):
# pycrypto
raise ModuleNotFoundError("You installed pycrypto and not pycryptodome(x). "
"Pycrypto is old, deprecated and not supported. \n"
"Run: python -m pip uninstall pycrypto\n"
"And: python -m pip install pycryptodomex\n"
"Or: python -m pip install pycryptodome")
except ModuleNotFoundError:
# crypto (or nothing)
raise ModuleNotFoundError("You need pycryptodome(x) to run these scripts!\n"
"python -m pip install pycryptodome\n"
"Or: python -m pip install pycryptodome\n"
"You can also remove \"crypto\" if you have it installed\n"
"python -m pip uninstall crypto")
def oscillate(n: int, n_min: int, n_max: int):
"""Yields n, n-1, n+1, n-2, n+2..., with constraints:
- n is in [min, max]
- n is never negative
Reverts to range() when n touches min or max. Example:
oscillate(8, 2, 10) => 8, 7, 9, 6, 10, 5, 4, 3, 2
"""
if n_min < 0:
n_min = 0
i = n
c = 1
# First phase (n, n-1, n+1...)
while True:
if i == n_max:
break
yield i
i -= c
c += 1
if i == 0 or i == n_min:
break
yield i
i += c
c += 1
# Second phase (range of remaining numbers)
# n != i/2 fixes a bug where we would yield min and max two times if n == (max-min)/2
if i == n_min and n != i / 2:
yield i
i += c
for j in range(i, n_max + 1):
yield j
if i == n_max and n != i / 2:
yield n_max
i -= c
for j in range(i, n_min - 1, -1):
yield j
def find_data_offset(header: bytes, iv_offset: int, key: bytes, starting_data_offset: int) -> int:
"""Tries to find the offset in which the encrypted data starts.
Returns the offset or -1 if the offset is not found.
Only works with ZLIB stream, not with ZIP file."""
iv = header[iv_offset:iv_offset + 16]
# oscillate ensures we try the closest values to the default value first.
for i in oscillate(n=starting_data_offset, n_min=iv_offset + len(iv), n_max=C.HEADER_SIZE - 128):
cipher = AES.new(key, AES.MODE_GCM, iv)
# We only decrypt the first two bytes.
test_bytes = cipher.decrypt(header[i:i + 2])
for zheader in C.ZLIB_HEADERS:
if test_bytes == zheader:
# We found a match, but this might also happen by chance.
# Let's run another test by decrypting some hundreds of bytes.
# We need to reinitialize the cipher everytime as it has an internal status.
cipher = AES.new(key, AES.MODE_GCM, iv)
decrypted = cipher.decrypt(header[i:])
if test_decompression(decrypted):
return i
return -1
def guess_offsets(key: bytes, encrypted: io.BufferedReader, def_iv_offset: int,
def_data_offset: int):
"""Gets the IV, shifts the stream to the beginning of the encrypted data and returns the cipher.
It does so by guessing the offset."""
# Assign variables to suppress warnings
db_header, data_offset, iv_offset = None, None, None
# Restart the file stream
encrypted.seek(0)
db_header = encrypted.read(C.HEADER_SIZE)
if len(db_header) < C.HEADER_SIZE:
log.fatal("The encrypted database is too small.\n "
"Did you swap the keyfile and the encrypted database file by mistake?")
try:
if db_header[:15].decode('ascii') == 'SQLite format 3':
log.error("The database file is not encrypted.\n "
"Did you swap the input and the output files by mistake?")
except ValueError:
pass
# Finding WhatsApp's version is nice
version = findall(b"\\d(?:\\.\\d{1,3}){3}", db_header)
if len(version) != 1:
log.info('WhatsApp version not found (Crypt12?)')
else:
log.debug("WhatsApp version: {}".format(version[0].decode('ascii')))
# Determine IV offset and data offset.
for iv_offset in oscillate(n=def_iv_offset, n_min=0, n_max=C.HEADER_SIZE - 128):
data_offset = find_data_offset(db_header, iv_offset, key, def_data_offset)
if data_offset != -1:
log.info("Offsets guessed (IV: {}, data: {}).".format(iv_offset, data_offset))
if iv_offset != def_iv_offset or data_offset != def_data_offset:
log.info("Next time, use -ivo {} -do {} for guess-free decryption".format(iv_offset, data_offset))
break
if data_offset == -1:
return None
iv = db_header[iv_offset:iv_offset + 16]
encrypted.seek(data_offset)
return AES.new(key, AES.MODE_GCM, iv)
def parsecmdline() -> argparse.Namespace:
"""Sets up the argument parser"""
parser = argparse.ArgumentParser(description='Decrypts WhatsApp backup files'
' encrypted with crypt12, 14 or 15')
parser.add_argument('keyfile', nargs='?', type=str, default="encrypted_backup.key",
help='The WhatsApp encrypted_backup key file or the hex encoded key. '
'Default: encrypted_backup.key')
parser.add_argument('encrypted', nargs='?', type=argparse.FileType('rb'), default="msgstore.db.crypt15",
help='The encrypted crypt12, 14 or 15 file. Default: msgstore.db.crypt15')
parser.add_argument('decrypted', nargs='?', type=argparse.FileType('wb'), default="msgstore.db",
help='The decrypted output file. Default: msgstore.db')
parser.add_argument('-ivo', '--iv-offset', type=int, default=C.DEFAULT_IV_OFFSET,
help='The default offset of the IV in the encrypted file. '
'Default: {}'.format(C.DEFAULT_IV_OFFSET))
parser.add_argument('-do', '--data-offset', type=int, default=C.DEFAULT_DATA_OFFSET,
help='The default offset of the encrypted data in the encrypted file. '
'Default: {}'.format(C.DEFAULT_DATA_OFFSET))
parser.add_argument('-v', '--verbose', action='store_true', help='Prints all offsets and messages')
return parser.parse_args()
def decrypt(cipher, encrypted, decrypted):
"""Does the actual decryption."""
z_obj = zlib.decompressobj()
if cipher is None:
log.fatal("Could not create a decryption cipher")
try:
try:
encrypted_data = encrypted.read()
# Crypt12 moment: the last 4 bytes are --xx, where xx
# are the last 2 numbers of the jid (user's phone number).
# We need to remove them.
try:
output_decrypted: bytearray = cipher.decrypt(encrypted_data)
except ValueError as e:
log.fatal("Decryption failed: {}."
"\n This probably means your backup is corrupted.".format(e))
# Dead code to make pycharm warning go away
exit(1)
try:
output_file = z_obj.decompress(output_decrypted)
if not z_obj.eof:
log.error("The encrypted database file is truncated (damaged).")
except zlib.error:
output_file = output_decrypted
if test_decompression(output_file[:io.DEFAULT_BUFFER_SIZE]):
log.info("Decrypted data is a ZIP file that I will not decompress automatically.")
else:
log.error("I can't recognize decrypted data. Decryption not successful.\n "
"The key probably does not match with the encrypted file.\n "
"Or the backup is simply empty. (check with --force)")
decrypted.write(output_file)
except MemoryError:
log.fatal("Out of RAM, please use -nm.")
decrypted.flush()
except OSError as e:
log.fatal("I/O error: {}".format(e))
finally:
decrypted.close()
encrypted.close()
def main():
args = parsecmdline()
# set wa_crypt_tools l to debug
log.setLevel(logging.DEBUG if args.verbose else logging.INFO)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG if args.verbose else logging.INFO)
ch.setFormatter(CustomFormatter())
log.addHandler(ch)
if not (0 < args.data_offset < C.HEADER_SIZE - 128):
log.fatal("The data offset must be between 1 and {}".format(C.HEADER_SIZE - 129))
if not (0 < args.iv_offset < C.HEADER_SIZE - 128):
log.fatal("The IV offset must be between 1 and {}".format(C.HEADER_SIZE - 129))
# Get the decryption key from the key file or the hex encoded string.
key = KeyFactory.new(args.keyfile)
log.debug(str(key))
cipher = guess_offsets(key=key.get(), encrypted=args.encrypted,
def_iv_offset=args.iv_offset, def_data_offset=args.data_offset)
decrypt(cipher, args.encrypted, args.decrypted)
if date.today().day == 1 and date.today().month == 4:
log.info("Done. Uploading messages to the developer's server...")
sleep(0.5)
log.info("Uploaded. The developer will now read and publish your messages!")
else:
log.info("Done")
if __name__ == '__main__':
main()
================================================
FILE: src/wa_crypt_tools/wainfo.py
================================================
#!/usr/bin/env python
"""
This script prints info on WhatsApp's DB files.
"""
from __future__ import annotations
from wa_crypt_tools.lib.logformat import CustomFormatter
from wa_crypt_tools.lib.db.dbfactory import DatabaseFactory
from wa_crypt_tools.lib.key.keyfactory import KeyFactory
import argparse
__author__ = 'ElDavo'
__copyright__ = 'Copyright (C) 2024'
__license__ = 'GPLv3'
__status__ = 'Beta'
import logging
log = logging.getLogger(__name__)
def parsecmdline() -> argparse.Namespace:
"""Sets up the argument parser"""
parser = argparse.ArgumentParser(description='Prints info on whatsapp crypted files')
parser.add_argument('encrypted', nargs='?',
type=str,
default="msgstore.db.crypt15",
help='The encrypted crypt12, 14 or 15 file. Default: msgstore.db.crypt15')
parser.add_argument('-k', '--key',
action='store_true',
help='tell the program that the file is a key file')
return parser.parse_args()
def main():
args = parsecmdline()
# set wa_crypt_tools l to debug
log.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(CustomFormatter())
log.addHandler(ch)
# also add to "wa_crypt_tools.lib" logger
logging.getLogger("wa_crypt_tools.lib").addHandler(ch)
logging.getLogger("wa_crypt_tools.lib").setLevel(logging.DEBUG)
log.warning("This script is in beta stage.")
if args.key:
key = KeyFactory.from_file(args.encrypted)
print(key)
return
try:
DatabaseFactory.from_file(open(args.encrypted, 'rb'))
except Exception as e:
log.error("Error: {}".format(e))
return
# TODO
# print(db)
if __name__ == "__main__":
main()
================================================
FILE: tests/__init__.py
================================================
================================================
FILE: tests/lib/__init__.py
================================================
================================================
FILE: tests/lib/db/__init__.py
================================================
================================================
FILE: tests/lib/db/test_db.py
================================================
class TestDatabase():
pass
================================================
FILE: tests/lib/test_constants.py
================================================
from wa_crypt_tools.lib.constants import C
class TestConstants:
def test_zip_header(self):
assert C.ZIP_HEADER == b'PK\x03\x04'
================================================
FILE: tests/lib/test_utils.py
================================================
from wa_crypt_tools.lib.utils import hexstring2bytes
class TestUtils:
# Sample test to test the test infrastructure (!)
def test_hexstring2bytes(self):
assert hexstring2bytes("0"*64) == b'\x00' * 32
================================================
FILE: tests/res/test.json
================================================
{
"test_json": "A JSON file that is not a SQLite database nor a ZIP file"
}
================================================
FILE: tests/test_createkey.py
================================================
import os
import zlib
from wa_crypt_tools.lib.key.key15 import Key15
from wa_crypt_tools.lib.key.key14 import Key14
from wa_crypt_tools.lib.key.keyfactory import KeyFactory
from wa_crypt_tools.lib.props import Props
from hashlib import sha512
class TestCreatekey:
def test_createkey(self):
key: Key15 = Key15(key=
bytes.fromhex(
'6730a595a1484d0c39c101dc0ac82ec5e401bb6f0e1b8ee2dc104a6b3687f017'
))
keyb: bytes = key.dump()
keyb_digest = sha512(keyb).digest()
with open("tests/res/encrypted_backup.key", 'rb') as f:
orig_check = sha512(f.read()).digest()
assert keyb_digest == orig_check
def test_createkey14(self):
key: Key14 = Key14(key=
bytes.fromhex(
'3a146d9bbd8b6311d962c71619c0c2cce3ce694ea4a0f3f600e271380e1226c6'
),
serversalt=bytes.fromhex('cd788b1b4625f50d3fccdeac94e1ff638899733b77a224ff614918363901f044'),
googleid=bytes.fromhex('92683e735c88727eef9486911f3ac6fa'),
key_version=b'\x02',
cipher_version=b'\x00\x01')
keyb: bytes = key.dump()
with open("tests/res/key", 'rb') as f:
assert keyb == f.read()
================================================
FILE: tests/test_decrypt.py
================================================
import os
import zlib
from wa_crypt_tools.lib.db.db12 import Database12
from wa_crypt_tools.lib.db.db14 import Database14
from wa_crypt_tools.lib.db.db15 import Database15
from wa_crypt_tools.lib.db.dbfactory import DatabaseFactory
from wa_crypt_tools.lib.key.keyfactory import KeyFactory
from wa_crypt_tools.lib.props import Props
from hashlib import sha512
class TestDecryption:
def test_decryption15(self):
key = KeyFactory.new("tests/res/encrypted_backup.key")
f = open("tests/res/msgstore.db.crypt15",'rb')
db = DatabaseFactory.from_file(f)
encrypted = f.read()
decrypted_db = db.decrypt(key, encrypted)
decrypted_db = zlib.decompress(decrypted_db)
new_check = sha512(decrypted_db).digest()
with open("tests/res/msgstore.db", 'rb') as f:
orig_check = sha512(f.read()).digest()
assert new_check == orig_check
def test_decryption14(self):
key = KeyFactory.new("tests/res/key")
f = open("tests/res/msgstore.db.crypt14",'rb')
db = DatabaseFactory.from_file(f)
encrypted = f.read()
decrypted_db = db.decrypt(key, encrypted)
decrypted_db = zlib.decompress(decrypted_db)
new_check = sha512(decrypted_db).digest()
with open("tests/res/msgstore.db", 'rb') as f:
orig_check = sha512(f.read()).digest()
assert new_check == orig_check
def test_decryption12(self):
key = KeyFactory.new("tests/res/key")
f = open("tests/res/msgstore.db.crypt12",'rb')
db = DatabaseFactory.from_file(f)
encrypted = f.read()
decrypted_db = db.decrypt(key, encrypted)
decrypted_db = zlib.decompress(decrypted_db)
new_check = sha512(decrypted_db).digest()
with open("tests/res/msgstore.db", 'rb') as f:
orig_check = sha512(f.read()).digest()
assert new_check == orig_check
================================================
FILE: tests/test_encrypt.py
================================================
import os
import zlib
from wa_crypt_tools.lib.db.db12 import Database12
from wa_crypt_tools.lib.db.db14 import Database14
from wa_crypt_tools.lib.db.db15 import Database15
from wa_crypt_tools.lib.key.keyfactory import KeyFactory
from wa_crypt_tools.lib.props import Props
from hashlib import sha512
class TestEncryption:
def test_encryption15(self):
key = KeyFactory.new("tests/res/encrypted_backup.key")
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],
max_feature=37)
db = Database15(key=key, iv=bytes.fromhex("C395EE009CF8B68AC0EA760550F6559C"))
data = db.encrypt(
key,
props,
zlib.compress(
open("tests/res/msgstore.db", 'rb').read(),
level=1,
)
)
new_check = sha512(data).digest()
with open("tests/res/msgstore-new.db.crypt15", 'wb') as f:
f.write(data)
with open("tests/res/msgstore.db.crypt15", 'rb') as f:
orig_check = sha512(f.read()).digest()
assert new_check == orig_check
os.remove("tests/res/msgstore-new.db.crypt15")
def test_encryption14(self):
key = KeyFactory.new("tests/res/key")
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],
max_feature=37)
db = Database14(key=key, iv=bytes.fromhex("EA53CEAE36ECAB50BC331AEB62491625"))
data = db.encrypt(
key,
props,
zlib.compress(
open("tests/res/msgstore.db", 'rb').read(),
level=1,
)
)
new_check = sha512(data).digest()
with open("tests/res/msgstore-new.db.crypt14", 'wb') as f:
f.write(data)
with open("tests/res/msgstore.db.crypt14", 'rb') as f:
orig_check = sha512(f.read()).digest()
assert new_check == orig_check
os.remove("tests/res/msgstore-new.db.crypt14")
def test_encryption14_noexpiry(self):
key = KeyFactory.new("tests/res/key")
props = Props(wa_version="2.22.5.13", jid="67", features=None)
db = Database14(key=key, iv=bytes.fromhex("EA53CEAE36ECAB50BC331AEB62491625"))
data = db.encrypt(
key,
props,
zlib.compress(
open("tests/res/msgstore.db", 'rb').read(),
level=1,
)
)
new_check = sha512(data).digest()
with open("tests/res/msgstore-new.db.crypt14", 'wb') as f:
f.write(data)
with open("tests/res/msgstore-noexpiry.db.crypt14", 'rb') as f:
orig_check = sha512(f.read()).digest()
assert new_check == orig_check
os.remove("tests/res/msgstore-new.db.crypt14")
def test_encryption12(self):
key = KeyFactory.new("tests/res/key")
props = Props(wa_version="2.22.5.13", jid="67", features=None)
db = Database12(key=key, iv=bytes.fromhex("F4E9A6DC0B6F0D8986AF6C7180F02356"))
data = db.encrypt(
key,
props,
zlib.compress(
open("tests/res/msgstore.db", 'rb').read(),
level=1,
)
)
new_check = sha512(data).digest()
with open("tests/res/msgstore-new.db.crypt12", 'wb') as f:
f.write(data)
with open("tests/res/msgstore.db.crypt12", 'rb') as f:
orig_check = sha512(f.read()).digest()
assert new_check == orig_check
os.remove("tests/res/msgstore-new.db.crypt12")
================================================
FILE: tests/tools-invocation/test_wacreatekey.py
================================================
from os.path import exists
from hashlib import sha512
from wa_crypt_tools.lib.key.key15 import Key15
from wa_crypt_tools.lib.key.keyfactory import KeyFactory
from tests.utils.utils import Propen, cmp_files, rm_if_found
class TestWaCreateKey:
def test_no_input(self):
assert not exists("encrypted_backup.key")
try:
out, ret = Propen("wacreatekey")
assert ret == 0
assert "Key file \"encrypted_backup.key\" created." in out
key: Key15 = KeyFactory.from_file("encrypted_backup.key")
finally:
# cleanup
rm_if_found("encrypted_backup.key")
def test_hex_key(self):
assert not exists("encrypted_backup.key")
try:
out,ret = Propen("wacreatekey"
" --hex 6730a595a1484d0c39c101dc0ac82ec5e401bb6f0e1b8ee2dc104a6b3687f017")
print(out)
assert ret == 0
assert "Key file \"encrypted_backup.key\" created." in out
assert cmp_files("encrypted_backup.key", "tests/res/encrypted_backup.key")
finally:
rm_if_found("encrypted_backup.key")
def test_invalid_hex_key(self):
assert not exists("encrypted_backup.key")
out, ret = Propen("wacreatekey --hex invalid")
assert ret != 0
assert "Key is not in hexadecimal format" in out
assert not exists("encrypted_backup.key")
def test_invalid_hex_key_length(self):
assert not exists("encrypted_backup.key")
out, ret = Propen("wacreatekey --hex 00")
assert ret != 0
assert "Invalid key length" in out
assert not exists("encrypted_backup.key")
def test_custom_output(self):
assert not exists("custom.key")
try:
out, ret = Propen("wacreatekey -o custom.key")
assert ret == 0
assert "Key file \"custom.key\" created." in out
assert exists("custom.key")
finally:
rm_if_found("custom.key")
def test_not_overwrite_file(self):
assert not exists("encrypted_backup.key")
try:
Propen("wacreatekey")
with open("encrypted_backup.key", "rb") as f:
chksum = sha512(f.read()).digest()
out, ret = Propen("wacreatekey")
assert ret != 0
assert "The output file already exists." in out
with open("encrypted_backup.key", "rb") as f:
assert chksum == sha512(f.read()).digest()
finally:
# cleanup
rm_if_found("encrypted_backup.key")
def test_overwrite_file(self):
assert not exists("encrypted_backup.key")
try:
Propen("wacreatekey")
with open("encrypted_backup.key", "rb") as f:
chksum = sha512(f.read()).digest()
out, ret = Propen("wacreatekey -y")
assert ret == 0
with open("encrypted_backup.key", "rb") as f:
assert chksum != sha512(f.read()).digest()
assert chksum != sha512(f.read()).digest()
finally:
# cleanup
rm_if_found("encrypted_backup.key")
def test_crypt14_key(self):
assert not exists("key")
try:
out, ret = Propen("wacreatekey -c14"
" --hex 3a146d9bbd8b6311d962c71619c0c2cce3ce694ea4a0f3f600e271380e1226c6"
" -ss cd788b1b4625f50d3fccdeac94e1ff638899733b77a224ff614918363901f044"
" -gi 92683e735c88727eef9486911f3ac6fa"
" -kv 2"
" -cv 1")
assert ret == 0
assert "Key file \"key\" created." in out
assert cmp_files("key", "tests/res/key")
finally:
rm_if_found("key")
def call_wacreatekey_14(self, arguments):
assert not exists("key")
try:
out, ret = Propen(arguments)
assert ret == 0
key = KeyFactory.from_file("key")
return out
finally:
rm_if_found("key")
def test_crypt14_key_not_all_parameters(self):
arguments=["wacreatekey", "-c14", "--hex",
"3a146d9bbd8b6311d962c71619c0c2cce3ce694ea4a0f3f600e271380e1226c6",
"-ss", "cd788b1b4625f50d3fccdeac94e1ff638899733b77a224ff614918363901f044",
"-gi", "92683e735c88727eef9486911f3ac6fa",
"-kv", "2",
"-cv", "1"]
# call without key
self.call_wacreatekey_14(arguments[:2] + arguments[4:])
# call without server salt
self.call_wacreatekey_14(arguments[:4] + arguments[6:])
# without google id
self.call_wacreatekey_14(arguments[:6] + arguments[8:])
# without key version
self.call_wacreatekey_14(arguments[:8] + arguments[10:])
# without cipher version
self.call_wacreatekey_14(arguments[:10])
# Some AI generated combinations below
self.call_wacreatekey_14(arguments[:2] + arguments[4:6] + arguments[8:])
self.call_wacreatekey_14(arguments[:2] + arguments[4:8] + arguments[10:])
self.call_wacreatekey_14(arguments[:2] + arguments[4:10])
self.call_wacreatekey_14(arguments[:2] + arguments[6:8] + arguments[10:])
self.call_wacreatekey_14(arguments[:2] + arguments[6:10])
self.call_wacreatekey_14(arguments[:2] + arguments[8:10])
self.call_wacreatekey_14(arguments[:4] + arguments[6:8] + arguments[10:])
self.call_wacreatekey_14(arguments[:4] + arguments[6:10])
self.call_wacreatekey_14(arguments[:4] + arguments[8:10])
self.call_wacreatekey_14(arguments[:6] + arguments[8:10])
def test_crypt14_invalid_server_salt(self):
assert not exists("key")
try:
out, ret = Propen("wacreatekey -c14"
" --hex 3a146d9bbd8b6311d962c71619c0c2cce3ce694ea4a0f3f600e271380e1226c6"
" -ss invalid"
" -gi 92683e735c88727eef9486911f3ac6fa"
" -kv 2"
" -cv 1")
assert ret != 0
assert "Something was not right" in out
assert not exists("key")
finally:
rm_if_found("key")
def test_crypt14_invalid_google_id(self):
assert not exists("key")
try:
out, ret = Propen("wacreatekey -c14"
" --hex 3a146d9bbd8b6311d962c71619c0c2cce3ce694ea4a0f3f600e271380e1226c6"
" -ss cd788b1b4625f50d3fccdeac94e1ff638899733b77a224ff614918363901f044"
" -gi invalid"
" -kv 2"
" -cv 1")
assert ret != 0
assert "Something was not right" in out
finally:
rm_if_found("key")
assert not exists("key")
def test_crypt14_invalid_google_id_length(self):
assert not exists("key")
try:
out, ret = Propen("wacreatekey -c14"
" --hex 3a146d9bbd8b6311d962c71619c0c2cce3ce694ea4a0f3f600e271380e1226c6"
" -ss cd788b1b4625f50d3fccdeac94e1ff638899733b77a224ff614918363901f044"
" -gi 92683e7eef9486911f3ac6fa00"
" -kv 2"
" -cv 1")
assert ret != 0
# assert "Invalid google id length" in out
assert not exists("key")
finally:
rm_if_found("key")
def test_crypt14_invalid_key_version(self):
assert not exists("key")
try:
out, ret = Propen("wacreatekey -c14"
" --hex 3a146d9bbd8b6311d962c71619c0c2cce3ce694ea4a0f3f600e271380e1226c6"
" -ss cd788b1b4625f50d3fccdeac94e1ff638899733b77a224ff614918363901f044"
" -gi 92683e735c88727eef9486911f3ac6fa"
" -kv invalid"
" -cv 1")
assert ret != 0
#assert "usage:" in out
assert not exists("key")
finally:
rm_if_found("key")
def test_crypt14_invalid_cipher_version(self):
assert not exists("key")
out, ret = Propen("wacreatekey -c14"
" --hex 3a146d9bbd8b6311d962c71619c0c2cce3ce694ea4a0f3f600e271380e1226c6"
" -ss cd788b1b4625f50d3fccdeac94e1ff638899733b77a224ff614918363901f044"
" -gi 92683e735c88727eef9486911f3ac6fa"
" -kv 2"
" -cv invalid")
assert ret != 0
assert "usage:" in out
assert not exists("key")
================================================
FILE: tests/utils/__init__.py
================================================
================================================
FILE: tests/utils/utils.py
================================================
import os
from hashlib import sha512
from subprocess import Popen, STDOUT, PIPE
def Propen(command):
if isinstance(command, str):
command = command.split()
# split the command string in a list
p = Popen(command, stdout=PIPE, stderr=STDOUT, text=True)
return p.communicate()[0], p.returncode
def cmp_files(file1: str, file2: str):
with open(file1, 'rb') as f:
keyb_digest = sha512(f.read()).digest()
with open(file2, 'rb') as f:
orig_check = sha512(f.read()).digest()
return keyb_digest == orig_check
def rm_if_found(file: str):
if not os.path.exists(file):
return
if not os.path.isfile(file):
return
try:
os.remove(file)
except FileNotFoundError:
pass
================================================
FILE: utils/WA_HMACSHA256_Loop.java
================================================
package com.test;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
/*
The original loop WhatsApp uses to encode a encrypted_backup.key.
TODO make a python implementation of this function.
*/
public class WA_HMACSHA256_Loop {
public static byte[] nestedHMACSHA256NoKey(byte[] first_iteration_data, byte[] message, int permutations) {
return nestedHmacSHA256(first_iteration_data, new byte[32], message, permutations);
}
public static byte[] nestedHmacSHA256(byte[] first_iteration_data, byte[] privateHmacSHA256Key, byte[] message, int permutations) {
try {
Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
hmacSHA256.init(new SecretKeySpec(privateHmacSHA256Key, "HmacSHA256"));
byte[] hmacsha256header = hmacSHA256.doFinal(first_iteration_data);
try {
/*The permutation number is actually divided by 32.
Be sure to give *32 the number of permutations you actually want!*/
int numPermutations = (int) Math.ceil(((double) permutations) / 32.0d);
byte[] existingData = new byte[0];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
for (int i = 1; i < numPermutations + 1; i++) {
Mac hasher = Mac.getInstance("HmacSHA256");
hasher.init(new SecretKeySpec(hmacsha256header, "HmacSHA256"));
hasher.update(existingData);
if (message != null) {
hasher.update(message);
}
// Mettiamoci dentro anche l'indice
byte one = (byte) i;
System.out.println((byte) i);
hasher.update((byte) i);
existingData = hasher.doFinal();
int min = Math.min(permutations, existingData.length);
byteArrayOutputStream.write(existingData, 0, min);
permutations -= min;
}
return byteArrayOutputStream.toByteArray();
} catch (InvalidKeyException | NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
} catch (InvalidKeyException | NoSuchAlgorithmException e2) {
throw new AssertionError(e2);
}
}
}
================================================
FILE: utils/password_data_key_to_hashcat.py
================================================
#!/usr/bin/env python
"""
This script transforms a password_data.key file into a hashcat hash.
"""
from __future__ import annotations
import argparse
# noinspection PyPackageRequirements
# This is from javaobj-py3
import javaobj.v2 as javaobj
from base64 import b64encode
# password_data.key file format:
# The password_data.key file is a serialized Java object, composed by:
# 1) An int (4 bytes), which should be the version of the format.
# The only known value for now is 1, so we only support this version.
# 2) The encoded password (32 bytes), encoded with PBKDF2-HMAC-SHA512.
# PBKDF2 needs a salt and a permutation number, which are written after:
# 3) The salt (32 bytes), which is a random byte array.
# 4) The permutation number (4 bytes), which is an int. For now seems to be fixed at 100000.
# The script parses the permutation number for the file, so if it changes, no problem.
class Log:
"""Simpler logger class. Supports 2 verbosity levels."""
@staticmethod
def i(msg: str):
"""Always prints message."""
print('[I] {}'.format(msg))
@staticmethod
def f(msg: str):
"""Always prints message and exit."""
print('[F] {}'.format(msg))
exit(1)
def parsecmdline() -> argparse.Namespace:
"""Sets up the argument parser"""
parser = argparse.ArgumentParser(description='Gives a hashcat representation of the password data key')
parser.add_argument('passworddatakeyfile', nargs='?', type=argparse.FileType('rb'), default="password_data.key",
help='The WhatsApp password data keyfile. Default: password_data.key')
return parser.parse_args()
def barrtoint(barr: javaobj.beans.BlockData) -> int:
"""Converts a javaobj BlockData to an int"""
return int.from_bytes(barr.data, byteorder='big', signed=False)
def javaintlist2bytes(barr: javaobj.beans.JavaArray) -> bytes:
"""Converts a javaobj bytearray which somehow became a list of signed integers back to a Python byte array"""
out: bytes = b''
for i in barr.data:
out += i.to_bytes(1, byteorder='big', signed=True)
return out
def read_password_data_key(passworddatakeyfilestream) -> str:
# Assign variables to suppress warnings
deserialized: list = list()
try:
deserialized: list = javaobj.load(passworddatakeyfilestream)
except OSError as e:
Log.f("Couldn't read keyfile: {}".format(e))
except (ValueError, RuntimeError) as e:
Log.f("The keyfile is not a valid Java object: {}".format(e))
if len(deserialized) != 4:
Log.f("The keyfile has more fields than expected.")
version: int = barrtoint(deserialized[0])
if version != 1:
Log.f("Unexpected key version: {}".format(version))
encoded = javaintlist2bytes(deserialized[1])
if len(encoded) != 64:
Log.f("The encoded password has the wrong length")
salt = javaintlist2bytes(deserialized[2])
if len(salt) != 64:
Log.f("The salt has the wrong length")
permutations: int = barrtoint(deserialized[3])
if permutations != 100000:
Log.i("Unexpected permutation number: {}".format(permutations))
return "sha512:{}:{}:{}".format(
permutations,
b64encode(salt).decode('ascii'),
b64encode(encoded).decode('ascii')
)
def main():
args = parsecmdline()
Log.i("Remember: hashcat mode is 12100 (PBKDF2-HMAC-SHA512)")
pwd_hash = read_password_data_key(args.passworddatakeyfile)
print(pwd_hash)
if __name__ == "__main__":
main()
================================================
FILE: utils/protobuf_bruteforce.py
================================================
"""
This script tries to find protobuf messages in a file.
Props to protobuf_inspector for the parser.
"""
from __future__ import annotations
from protobuf_inspector.types import StandardParser
from io import BytesIO
from os.path import getsize
import argparse
def parsecmdline() -> argparse.Namespace:
"""Sets up the argument parser"""
parser = argparse.ArgumentParser(description='Find protocol buffers in a file.')
parser.add_argument('file_name', type=str, help='A file that you believe contains protobuf messages.')
parser.add_argument('-k', '--keep-going', action='store_true', help='Don\'t stop after the first result.')
parser.add_argument('-r', '--range', type=int, default=512, help='The number of bytes to search. Ignored if -w is '
'set.')
parser.add_argument('-w', '--whole-file', action='store_true', help='Search the whole file. Not advised for large '
'files')
return parser.parse_args()
def load_file(file_name: str, byte_range=0, reverse=False) -> bytes:
""" Loads a file and returns it as a byte array.
If byte_range is set, it will return the first byte_range bytes of the file.
If reverse is set, it will return the last byte_range bytes of the file.
"""
try:
size = getsize(file_name)
if byte_range > size / 2:
raise ValueError("Range provided is bigger than half of file. Use -w or lower the range.")
with open(file_name, 'rb') as f:
if byte_range < 1:
if reverse:
raise ValueError("Cannot read the whole file from end")
return f.read()
if reverse:
f.seek(size - byte_range)
return f.read(byte_range)
return f.read(byte_range)
except IOError:
print("File not found or other IO error")
exit(1)
def get_truncated_stream(content: bytes, start: int, end: int) -> BytesIO:
""" Returns a BytesIO object with the content truncated to the given range. """
return BytesIO(content[start:end])
def main():
args = parsecmdline()
if args.whole_file:
whole_file = load_file(args.file_name)
search(whole_file, args.keep_going)
else:
# We first try the first "range" bytes.
whole_file = load_file(args.file_name, args.range)
search(whole_file, args.keep_going)
print("Now searching at the end of the file")
# Then we try the last "range" bytes.
size = getsize(args.file_name)
whole_file = load_file(args.file_name, args.range, reverse=True)
search(whole_file, args.keep_going, size - len(whole_file))
if args.keep_going:
print("Finished")
else:
print("Nothing found")
exit(1)
def protoparse(stream):
return StandardParser().parse_message(stream, "message")
class Message:
last_good_i = 0
last_good_j = 0
output = ""
def search(whole_file: bytes, keep_going: bool, offset=0):
""" Searches for protobuf messages in the given byte array. """
for i in range(len(whole_file)):
message = Message()
for j in range(i + 1, len(whole_file)):
candidate = get_truncated_stream(whole_file, i, j)
try:
message.output = protoparse(candidate)
message.last_good_j = j
message.last_good_i = i
except Exception:
pass
if message.last_good_j and message.last_good_i == i:
print("\n Message from byte {} to {}".format(message.last_good_i + offset, message.last_good_j + offset))
print(message.output)
if not keep_going:
exit(0)
if __name__ == "__main__":
main()