🛠️

Whiz Tools

Build • Create • Innovate

Brazilian CNPJ Generator and Validator Tool for Testing

Generate valid Brazilian CNPJ numbers and validate existing ones with this simple tool designed for developers and testers working with Brazilian business IDs.

Brazilian CNPJ Generator and Validator

CNPJ Generator

Generate a valid Brazilian CNPJ number for testing purposes.

CNPJ Validator

Check if a Brazilian CNPJ number is valid.

📚

Documentation

Brazilian CNPJ Generator and Validator Tool

Introduction

The Brazilian CNPJ (Cadastro Nacional da Pessoa Jurídica) is a unique identification number assigned to businesses and legal entities in Brazil. This Brazilian CNPJ generator and validator tool provides a simple, efficient way to generate valid CNPJ numbers for testing purposes and validate existing CNPJ numbers according to the official Brazilian algorithm. Whether you're a developer testing applications that handle Brazilian business data, a QA professional creating test cases, or anyone working with Brazilian company information, this tool streamlines the process of working with CNPJ numbers.

Unlike real CNPJ numbers that are officially issued by the Brazilian Federal Revenue Service (Receita Federal), the CNPJs generated by this tool are mathematically valid but not registered to actual companies. This makes them perfect for testing scenarios, sample data, and development environments where you need properly formatted and valid CNPJ numbers without using real business identifiers.

What is a CNPJ?

A CNPJ (Cadastro Nacional da Pessoa Jurídica) is a 14-digit identification number assigned to businesses and legal entities by the Brazilian Federal Revenue Service. It serves as the Brazilian equivalent of a company registration number or tax ID. Every business operating legally in Brazil must have a CNPJ, which is used for:

  • Tax reporting and compliance
  • Business registration with government agencies
  • Opening bank accounts
  • Issuing invoices and receipts
  • Participating in government tenders
  • Importing and exporting goods

The CNPJ is an essential identifier in Brazil's business ecosystem and appears on official documents, contracts, and financial records.

CNPJ Structure and Format

A Brazilian CNPJ consists of 14 digits, typically formatted as: XX.XXX.XXX/YYYY-ZZ

The structure breaks down as follows:

  1. First 8 digits (XX.XXX.XXX): Base number assigned to the company
  2. 4 digits after the slash (YYYY): Branch identifier (0001 for headquarters, other numbers for branches)
  3. Last 2 digits (ZZ): Check digits for validation

For example, a properly formatted CNPJ might look like: 12.345.678/0001-95

The check digits (the last two numbers) are calculated using a specific mathematical algorithm that validates the CNPJ's authenticity. This algorithm ensures that randomly generated numbers cannot pass validation without following the proper calculation method.

How the CNPJ Validation Works

The CNPJ validation algorithm uses a weighted calculation to determine the check digits. Here's how it works:

First Check Digit Calculation

  1. Multiply each of the first 12 digits by a weight sequence: 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2
  2. Sum the results of these multiplications
  3. Calculate the remainder of this sum divided by 11
  4. If the remainder is less than 2, the first check digit is 0; otherwise, it's 11 minus the remainder

Second Check Digit Calculation

  1. Multiply each of the first 13 digits (including the first check digit) by a weight sequence: 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2
  2. Sum the results of these multiplications
  3. Calculate the remainder of this sum divided by 11
  4. If the remainder is less than 2, the second check digit is 0; otherwise, it's 11 minus the remainder

For a CNPJ to be valid, both check digits must match the calculated values.

How to Use This Tool

Our Brazilian CNPJ Generator and Validator tool offers two main functions: generating valid CNPJs and validating existing CNPJ numbers.

Generating a CNPJ

To generate a valid CNPJ for testing purposes:

  1. Navigate to the "CNPJ Generator" section of the tool
  2. Click the "Generate CNPJ" button
  3. A mathematically valid CNPJ will appear in the formatted display
  4. Use the "Copy" button to copy the generated CNPJ to your clipboard

The generated CNPJ will follow all the mathematical validation rules of a real CNPJ but is not registered with the Brazilian Federal Revenue Service.

Validating a CNPJ

To check if a CNPJ is mathematically valid:

  1. Navigate to the "CNPJ Validator" section of the tool
  2. Enter the CNPJ you want to validate in the input field
    • The tool accepts CNPJs with or without formatting (periods, slashes, and hyphens)
  3. Click the "Validate" button
  4. The tool will display whether the CNPJ is valid or invalid based on the check digit algorithm

The validator checks if the CNPJ follows the correct format and if the check digits match the expected values according to the validation algorithm.

Use Cases

This Brazilian CNPJ generator and validator tool is particularly useful in the following scenarios:

Software Development and Testing

  • Creating Test Data: Generate valid CNPJs for populating test databases without using real company identifiers
  • Unit Testing: Validate CNPJ handling functions in your code with known valid and invalid examples
  • QA Testing: Create test cases for forms and interfaces that require CNPJ input
  • Integration Testing: Test systems that exchange data with Brazilian government services or financial institutions

Education and Training

  • Learning the CNPJ Format: Understand how Brazilian business identifiers are structured
  • Algorithm Study: Examine how check digit validation works in practice
  • Data Validation Techniques: Study real-world examples of data validation requirements

Data Processing

  • Data Cleaning: Validate CNPJs in existing datasets to identify potential errors
  • Form Validation: Implement client-side or server-side validation for CNPJ inputs
  • Data Anonymization: Replace real CNPJs with valid generated ones when preparing datasets for analysis

International Business

  • Market Entry Preparation: Understand Brazilian business identification requirements
  • Document Preparation: Ensure proper formatting when preparing business documents for Brazil
  • Compliance Checking: Verify that collected CNPJ numbers are at least mathematically valid

Alternatives

While our tool provides a simple, browser-based solution for generating and validating CNPJs, there are several alternatives depending on your specific needs:

Programming Libraries

For developers integrating CNPJ validation directly into applications, several language-specific libraries are available:

  • JavaScript: cpf_cnpj.js, validator.js
  • Python: python-cnpj, validate-docbr
  • PHP: brazilianutils, respect/validation
  • Java: caelum-stella, commons-validator
  • Ruby: cpf_cnpj, brazilian-rails

These libraries often provide additional functionality like formatting, parsing, and validation of other Brazilian documents.

API Services

For applications requiring validation without implementing the algorithm:

  • Brazilian government APIs (requires registration)
  • Commercial validation APIs that include CNPJ checking
  • Business information services that validate against the official database

Manual Calculation

For educational purposes or one-off validations, you can manually apply the algorithm:

  1. Extract the first 12 digits of the CNPJ
  2. Perform the weighted calculations as described earlier
  3. Compare the calculated check digits with the actual check digits

However, manual calculation is error-prone and inefficient for regular use.

Technical Implementation

The CNPJ generator and validator in this tool are implemented using JavaScript, making it fast and capable of running entirely in your browser without sending your data to a server. Here's how the core functions work:

CNPJ Generation Algorithm

1function generateCNPJ() {
2  // Generate the first 12 digits randomly
3  const digits = Array.from({ length: 12 }, () => Math.floor(Math.random() * 10));
4  
5  // Calculate first check digit
6  const firstCheckDigit = calculateCheckDigit(digits);
7  digits.push(firstCheckDigit);
8  
9  // Calculate second check digit
10  const secondCheckDigit = calculateCheckDigit(digits);
11  digits.push(secondCheckDigit);
12  
13  // Format the CNPJ
14  return formatCNPJ(digits.join(''));
15}
16
17function calculateCheckDigit(digits) {
18  const weights = digits.length < 13 
19    ? [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2] 
20    : [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
21  
22  const sum = digits.reduce((acc, digit, index) => {
23    return acc + digit * weights[index];
24  }, 0);
25  
26  const remainder = sum % 11;
27  return remainder < 2 ? 0 : 11 - remainder;
28}
29

CNPJ Validation Algorithm

1function validateCNPJ(cnpj) {
2  // Remove non-numeric characters
3  const cleanCNPJ = cnpj.replace(/\D/g, '');
4  
5  // Check if it has the correct length
6  if (cleanCNPJ.length !== 14) return false;
7  
8  // Check for known invalid patterns (all same digits)
9  if (/^(\d)\1+$/.test(cleanCNPJ)) return false;
10  
11  // Convert to array of digits
12  const digits = cleanCNPJ.split('').map(Number);
13  
14  // Check first verification digit
15  const expectedFirstDigit = calculateCheckDigit(digits.slice(0, 12));
16  if (digits[12] !== expectedFirstDigit) return false;
17  
18  // Check second verification digit
19  const expectedSecondDigit = calculateCheckDigit(digits.slice(0, 13));
20  if (digits[13] !== expectedSecondDigit) return false;
21  
22  return true;
23}
24

CNPJ Formatting Function

1function formatCNPJ(cnpj) {
2  // Remove non-numeric characters
3  const cleanCNPJ = cnpj.replace(/\D/g, '');
4  
5  // Format based on length
6  if (cleanCNPJ.length <= 2) {
7    return cleanCNPJ;
8  } else if (cleanCNPJ.length <= 5) {
9    return `${cleanCNPJ.slice(0, 2)}.${cleanCNPJ.slice(2)}`;
10  } else if (cleanCNPJ.length <= 8) {
11    return `${cleanCNPJ.slice(0, 2)}.${cleanCNPJ.slice(2, 5)}.${cleanCNPJ.slice(5)}`;
12  } else if (cleanCNPJ.length <= 12) {
13    return `${cleanCNPJ.slice(0, 2)}.${cleanCNPJ.slice(2, 5)}.${cleanCNPJ.slice(5, 8)}/${cleanCNPJ.slice(8)}`;
14  } else {
15    return `${cleanCNPJ.slice(0, 2)}.${cleanCNPJ.slice(2, 5)}.${cleanCNPJ.slice(5, 8)}/${cleanCNPJ.slice(8, 12)}-${cleanCNPJ.slice(12, 14)}`;
16  }
17}
18

These core functions can be implemented in other programming languages following the same logic. Here are examples in Python and Java:

Python Implementation

1import random
2
3def calculate_check_digit(digits):
4    weights = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2] if len(digits) < 13 else [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
5    
6    total = 0
7    for i in range(len(digits)):
8        total += digits[i] * weights[i]
9    
10    remainder = total % 11
11    return 0 if remainder < 2 else 11 - remainder
12
13def generate_cnpj():
14    # Generate first 12 digits randomly
15    digits = [random.randint(0, 9) for _ in range(12)]
16    
17    # Calculate first check digit
18    first_check = calculate_check_digit(digits)
19    digits.append(first_check)
20    
21    # Calculate second check digit
22    second_check = calculate_check_digit(digits)
23    digits.append(second_check)
24    
25    # Format the CNPJ
26    cnpj = ''.join(map(str, digits))
27    return f"{cnpj[:2]}.{cnpj[2:5]}.{cnpj[5:8]}/{cnpj[8:12]}-{cnpj[12:]}"
28
29def validate_cnpj(cnpj):
30    # Remove non-numeric characters
31    cnpj = ''.join(filter(str.isdigit, cnpj))
32    
33    # Check length
34    if len(cnpj) != 14:
35        return False
36    
37    # Check if all digits are the same
38    if len(set(cnpj)) == 1:
39        return False
40    
41    # Convert to list of integers
42    digits = [int(d) for d in cnpj]
43    
44    # Validate first check digit
45    first_check = calculate_check_digit(digits[:12])
46    if digits[12] != first_check:
47        return False
48    
49    # Validate second check digit
50    second_check = calculate_check_digit(digits[:13])
51    if digits[13] != second_check:
52        return False
53    
54    return True
55

Java Implementation

1import java.util.Random;
2
3public class CNPJUtils {
4    
5    public static String generateCNPJ() {
6        Random random = new Random();
7        int[] digits = new int[14];
8        
9        // Generate first 12 digits randomly
10        for (int i = 0; i < 12; i++) {
11            digits[i] = random.nextInt(10);
12        }
13        
14        // Calculate first check digit
15        digits[12] = calculateCheckDigit(digits, 12);
16        
17        // Calculate second check digit
18        digits[13] = calculateCheckDigit(digits, 13);
19        
20        // Format the CNPJ
21        return String.format("%02d.%03d.%03d/%04d-%02d",
22                digits[0] * 10 + digits[1],
23                digits[2] * 100 + digits[3] * 10 + digits[4],
24                digits[5] * 100 + digits[6] * 10 + digits[7],
25                digits[8] * 1000 + digits[9] * 100 + digits[10] * 10 + digits[11],
26                digits[12] * 10 + digits[13]);
27    }
28    
29    private static int calculateCheckDigit(int[] digits, int length) {
30        int[] weights = length < 13 
31            ? new int[]{5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2}
32            : new int[]{6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2};
33        
34        int sum = 0;
35        for (int i = 0; i < length; i++) {
36            sum += digits[i] * weights[i];
37        }
38        
39        int remainder = sum % 11;
40        return remainder < 2 ? 0 : 11 - remainder;
41    }
42    
43    public static boolean validateCNPJ(String cnpj) {
44        // Remove non-numeric characters
45        cnpj = cnpj.replaceAll("\\D", "");
46        
47        // Check length
48        if (cnpj.length() != 14) {
49            return false;
50        }
51        
52        // Check if all digits are the same
53        boolean allDigitsSame = true;
54        for (int i = 1; i < cnpj.length(); i++) {
55            if (cnpj.charAt(i) != cnpj.charAt(0)) {
56                allDigitsSame = false;
57                break;
58            }
59        }
60        if (allDigitsSame) {
61            return false;
62        }
63        
64        // Convert to array of integers
65        int[] digits = new int[14];
66        for (int i = 0; i < 14; i++) {
67            digits[i] = Character.getNumericValue(cnpj.charAt(i));
68        }
69        
70        // Validate first check digit
71        int firstCheck = calculateCheckDigit(digits, 12);
72        if (digits[12] != firstCheck) {
73            return false;
74        }
75        
76        // Validate second check digit
77        int secondCheck = calculateCheckDigit(digits, 13);
78        if (digits[13] != secondCheck) {
79            return false;
80        }
81        
82        return true;
83    }
84}
85

Important Considerations

When using this CNPJ generator and validator tool, keep the following considerations in mind:

Legal and Ethical Considerations

  • Not for Fraud: Generated CNPJs should never be used for fraudulent purposes or misrepresentation
  • Testing Only: These CNPJs are for testing and development purposes only
  • Not Registered: Generated CNPJs are mathematically valid but not registered with Brazilian authorities
  • No Real-World Validity: They cannot be used for actual business registration or tax purposes

Technical Limitations

  • No Business Information: Generated CNPJs don't contain real business sector codes or location information
  • No Database Verification: The validator checks mathematical validity only, not registration status
  • Format Variations: While the tool handles common formatting variations, some systems may require specific formats

Security Considerations

  • Client-Side Processing: All processing happens in your browser; no data is sent to servers
  • No Data Storage: Generated CNPJs are not stored or logged
  • No Personal Data: The tool doesn't handle or process any personal information

Frequently Asked Questions

What is a CNPJ used for in Brazil?

A CNPJ is the national registration number for businesses and legal entities in Brazil. It's used for tax purposes, business registration, opening bank accounts, and identifying companies in official transactions.

Are the CNPJs generated by this tool real?

No. The CNPJs generated by this tool are mathematically valid according to the check digit algorithm, but they are not registered with the Brazilian Federal Revenue Service and do not belong to real companies.

Can I use generated CNPJs for my business?

No. To obtain a legitimate CNPJ for a business, you must register with the Brazilian Federal Revenue Service (Receita Federal) following the official process. Generated CNPJs are for testing purposes only.

How can I tell if a CNPJ belongs to a real company?

To verify if a CNPJ is registered to an actual company, you need to consult the Brazilian Federal Revenue Service database. Our tool only checks if a CNPJ is mathematically valid, not if it's officially registered.

Why does the validator reject a CNPJ with all the same digits?

CNPJs with all the same digits (like 11.111.111/1111-11) are automatically considered invalid, even if they mathematically pass the check digit algorithm. This is a rule established by the Brazilian Federal Revenue Service.

Does the tool store the CNPJs I generate or validate?

No. All processing happens in your browser, and we don't store or transmit any of the CNPJs you generate or validate.

Can I generate multiple CNPJs at once?

The current version of the tool generates one CNPJ at a time. For bulk generation, you might want to consider using one of the programming libraries mentioned in the Alternatives section.

Why is the format XX.XXX.XXX/XXXX-XX important?

This is the official format required by Brazilian authorities. The specific grouping helps identify different components of the CNPJ, such as the base number and branch identifier.

How do I validate a CNPJ programmatically?

You can implement the validation algorithm in your preferred programming language using the code examples provided in the Technical Implementation section, or use one of the libraries mentioned in the Alternatives section.

Are there special CNPJs for government entities?

Yes. Government entities in Brazil have specific CNPJ patterns. For example, federal government entities often start with specific digits. Our generator creates random CNPJs and does not specifically generate government entity CNPJs.

References

  1. Brazilian Federal Revenue Service (Receita Federal do Brasil) - Official Website
  2. "CNPJ - Cadastro Nacional da Pessoa Jurídica" - Wikipedia
  3. Brazilian Civil Code (Law No. 10.406/2002) - Legal framework for business entities in Brazil
  4. Brazilian Business Registration Normative Instruction (IN RFB No. 1863/2018) - Regulations on CNPJ registration

Try It Now

Our Brazilian CNPJ Generator and Validator tool makes working with these identification numbers simple and efficient. Whether you're testing applications, preparing sample data, or validating existing CNPJs, this tool provides a straightforward solution without the complexity of API integrations or advanced configurations.

Generate your first valid CNPJ now or validate an existing one using our simple interface!