Skip to main content

📦 br-cpf-cnpj

Tests codecov

A Python library for CPF and CNPJ validation and generation, with support for the new alphanumeric CNPJ standard.


✨ Features

  • ✅ CPF validation
  • ✅ CNPJ validation (numeric and alphanumeric)
  • 🔢 Random CPF generator
  • 🔡 Random CNPJ generator (numeric or alphanumeric)
  • 🧪 Fully tested with pytest

📥 Installation

pip install br-cpf-cnpj

🚀 Usage

Validate CPF

from br_cpf_cnpj import is_valid_cpf

is_valid_cpf("529.982.247-25")
# True

# Validate unmasked CPF
is_valid_cpf("55782724366")
# True

Validate CNPJ

from br_cpf_cnpj import is_valid_cnpj

# Validate numeric CNPJ
is_valid_cnpj("11.222.333/0001-81")
# True

# Validate alphanumeric CNPJ
is_valid_cnpj("2P.76B.MNX/0001-66")
# True

# Validate unmasked CNPJ
is_valid_cnpj("B4ESBMHS000102")
# True

# Validate alphanumeric CNPJ with lowercase letters
is_valid_cnpj("mn.ahm.asb/0001-64")
# True

NOTE: By convention, if the CNPJ contains lowercase letters, it will be converted to uppercase before validation. Thus, the CNPJ mn.ahm.asb/0001-64 is considered valid because it is converted to MN.AHM.ASB/0001-64 during validation.

Generate Random CPF

from br_cpf_cnpj import generate_random_cpf

cpf = generate_random_cpf(masked=True)
print(cpf)
# e.g., "123.456.789-09"

cpf_unmasked = generate_random_cpf(masked=False)
print(cpf_unmasked)
# e.g., "12345678909"

Generate Random CNPJ

from br_cpf_cnpj import generate_random_cnpj

# Generate numeric CNPJ
cnpj_numeric = generate_random_cnpj(alphanumeric=False, masked=True)
print(cnpj_numeric)
# e.g., "12.345.678/0001-95"

# Generate alphanumeric CNPJ
cnpj_alphanumeric = generate_random_cnpj(alphanumeric=True, masked=False)
print(cnpj_alphanumeric)
# e.g., "RSASKDDW000100"

Formatter CPF/CNPJ

from br_cpf_cnpj import format_cpf_cnpj

cpf = "07368395690"
cnpj = "NXBZ38V0000172"
invalid_cpf = "123"

formatted_cpf = format_cpf_cnpj(cpf)
formatted_cnpj = format_cpf_cnpj(cnpj)
formatted_invalid_cpf = format_cpf_cnpj(invalid_cpf)

print(formatted_cpf)  # Output: "073.683.956-90"
print(formatted_cnpj) # Output: "NX.BZ3.8V0/0001-72"
print(formatted_invalid_cpf) # Output: "123" (Unchanged because it doesn't match a valid CPF/CNPJ format)

NOTE: The format_cpf_cnpj formatter automatically detects whether the string is a CPF or CNPJ and applies the correct formatting. If the string does not match a valid CPF or CNPJ format, it will be returned unchanged.

🧠 How it works

CPF

  • Uses fixed weights (10 → 2, then 11 → 2)
  • Applies the official modulo 11 algorithm
  • Prevents invalid repeated-digit CPFs (e.g. 11111111111)

CNPJ (Alphanumeric)

  • Supports digits (0–9) and uppercase letters (A–Z)
  • Characters are converted using: value = ord(char) - ord('0')
  • Weights cycle from 2 → 9

🤝 Contributing

Contributions are very welcome!

Development Setup

This project uses uv for dependency management. To set up your development environment:

  1. Clone the repository
  2. Install dependencies: uv sync --extra dev
  3. Run tests: uv run pytest

📄 License

MIT License.


Versão em Português

📦 br-cpf-cnpj

Uma biblioteca Python para validação e geração de CPF e CNPJ, com suporte ao novo padrão de CNPJ alfanumérico.


✨ Funcionalidades

  • ✅ Validação de CPF
  • ✅ Validação de CNPJ (numérico e alfanumérico)
  • 🔢 Gerador de CPF aleatório
  • 🔡 Gerador de CNPJ aleatório (numérico ou alfanumérico)
  • 🧪 Testes automatizados com pytest

📥 Instalação

pip install br-cpf-cnpj

🚀 Uso

Validar CPF

from br_cpf_cnpj import is_valid_cpf

is_valid_cpf("529.982.247-25")
# True

# Validar CPF sem máscara
is_valid_cpf("55782724366")
# True

Validar CNPJ

from br_cpf_cnpj import is_valid_cnpj

# Validar CNPJ numérico
is_valid_cnpj("11.222.333/0001-81")
# True

# Validar CNPJ alfanumérico
is_valid_cnpj("2P.76B.MNX/0001-66")
# True

# Validar CNPJ sem máscara
is_valid_cnpj("B4ESBMHS000102")
# True

# Validar CNPJ alfanumérico com letras minúsculas
is_valid_cnpj("mn.ahm.asb/0001-64")
# True

NOTA: Por convenção, se o CNPJ tiver letras minusculas, ele será convertido para maiúsculas antes da validação. Dessa forma, o CNPJ mn.ahm.asb/0001-64 é considerado válido, pois é convertido para MN.AHM.ASB/0001-64 durante a validação.

Gerar CPF Aleatório

from br_cpf_cnpj import generate_random_cpf

cpf = generate_random_cpf(masked=True)
print(cpf)
# e.g., "123.456.789-09"

cpf_unmasked = generate_random_cpf(masked=False)
print(cpf_unmasked)
# e.g., "12345678909"

Gerar CNPJ Aleatório

from br_cpf_cnpj import generate_random_cnpj

# Gerar CNPJ numérico
cnpj_numeric = generate_random_cnpj(alphanumeric=False, masked=True)
print(cnpj_numeric)
# e.g., "12.345.678/0001-95"

# Gerar CNPJ alfanumérico
cnpj_alphanumeric = generate_random_cnpj(alphanumeric=True, masked=False)
print(cnpj_alphanumeric)
# e.g., "RSASKDDW000100"

Formatar CPF/CNPJ

from br_cpf_cnpj import format_cpf_cnpj

cpf = "07368395690"
cnpj = "NXBZ38V0000172"
invalid_cpf = "123"

formatted_cpf = format_cpf_cnpj(cpf)
formatted_cnpj = format_cpf_cnpj(cnpj)
formatted_invalid_cpf = format_cpf_cnpj(invalid_cpf)

print(formatted_cpf)  # Saída: "073.683.956-90"
print(formatted_cnpj) # Saída: "NX.BZ3.8V0/0001-72"
print(formatted_invalid_cpf) # Saída: "123" (Permanece inalterado porque não corresponde a um formato válido de CPF/CNPJ)

NOTA: O formatador format_cpf_cnpj detecta automaticamente se a string é um CPF ou CNPJ e aplica a formatação correta. Se a string não corresponder a um formato válido de CPF ou CNPJ, ela será retornada inalterada.


🧠 Como Funciona

CPF

  • Pesos fixos (10 → 2 e 11 → 2)
  • Algoritmo módulo 11
  • Rejeita CPFs inválidos com dígitos repetidos (e.g. 11111111111)

CNPJ (Alfanumérico)

  • Aceita números (0–9) e letras (A–Z)
  • Conversão baseada em valor ASCII: value = ord(char) - ord('0')
  • Pesos cíclicos de 2 → 9

🤝 Contribuindo

Contribuições são muito bem-vindas!

Configuração do Ambiente de Desenvolvimento

Este projeto utiliza uv para gerenciamento de dependências. Para configurar seu ambiente de desenvolvimento:

  1. Clone o repositório
  2. Instale as dependências: uv sync --extra dev
  3. Execute os testes: uv run pytest

📄 License

MIT License.

Metadata

Release files for br-cpf-cnpj 1.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for br-cpf-cnpj 1.1.0
File Size Uploaded
br_cpf_cnpj-1.1.0.tar.gz 5.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for br-cpf-cnpj 1.1.0
File Interpreter ABI Platform
br_cpf_cnpj-1.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 11.9 kB

Release files / br_cpf_cnpj-1.1.0.tar.gz

Download URL br_cpf_cnpj-1.1.0.tar.gz
Size 5.2 kB
Tags Source
SHA-256 checksum
How to use checksums
15902489ca44dd303fb2d442a7c251acf349a1ebc063c9ca5abe9bde9d1bb232
BLAKE2b-256 checksum
How to use checksums
992af7d0d0260c866f8d4d9901c02008f78c56a1624412a20381d41bef1d5209
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Mar 23, 2026.

Transparency log

Release files / br_cpf_cnpj-1.1.0-py3-none-any.whl

Download URL br_cpf_cnpj-1.1.0-py3-none-any.whl
Size 6.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ef3addc0717b60b4a9c61ff63efe3963394d420ba786db1d7b26d20b1fe2b616
BLAKE2b-256 checksum
How to use checksums
34deda79c0a16155d208883f1fbff98aae969a381f11c73364a61732544aafb3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Mar 23, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

1.1.0 This release

2 release files

1.0.0

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.2

2 release files

0.1.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page