Skip to main content

CPF and CNPJ validation and generation with support for alphanumeric CNPJ

Project description

📦 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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

br_cpf_cnpj-1.1.0.tar.gz (5.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

br_cpf_cnpj-1.1.0-py3-none-any.whl (6.8 kB view details)

Uploaded Python 3

File details

Details for the file br_cpf_cnpj-1.1.0.tar.gz.

File metadata

  • Download URL: br_cpf_cnpj-1.1.0.tar.gz
  • Upload date:
  • Size: 5.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for br_cpf_cnpj-1.1.0.tar.gz
Algorithm Hash digest
SHA256 15902489ca44dd303fb2d442a7c251acf349a1ebc063c9ca5abe9bde9d1bb232
MD5 172e1ebb1df8e477287550a30f361b30
BLAKE2b-256 992af7d0d0260c866f8d4d9901c02008f78c56a1624412a20381d41bef1d5209

See more details on using hashes here.

Provenance

The following attestation bundles were made for br_cpf_cnpj-1.1.0.tar.gz:

Publisher: publish.yml on iupi-ip/br-cpf-cnpj

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file br_cpf_cnpj-1.1.0-py3-none-any.whl.

File metadata

  • Download URL: br_cpf_cnpj-1.1.0-py3-none-any.whl
  • Upload date:
  • Size: 6.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for br_cpf_cnpj-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ef3addc0717b60b4a9c61ff63efe3963394d420ba786db1d7b26d20b1fe2b616
MD5 c30c9b3221401b55c91f2718df0bbba1
BLAKE2b-256 34deda79c0a16155d208883f1fbff98aae969a381f11c73364a61732544aafb3

See more details on using hashes here.

Provenance

The following attestation bundles were made for br_cpf_cnpj-1.1.0-py3-none-any.whl:

Publisher: publish.yml on iupi-ip/br-cpf-cnpj

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page