The CNPJ (National Register of Legal Entities) is a unique number made up of fourteen digits that identifies a legal entity with the Brazilian Federal Revenue Service (an agency of the Ministry of Finance), which is necessary for the legal entity to be able to enter into contracts and sue or be sued.
The CNPJ is validated in the same way as the CPF, the only difference being in the default vectors. It’s the last two digits that validate all 12 previous digits.
For the algorithm below we will use the following CNPJ as an example: 44.038.188/0001-32.
Algorithm for CNPJ Generation:
- Calculation of the first check digit:
Let’s take a vector [latex] a E R^12 [/latex] whose components are the first 12 digits of the CNPJ number. For the CNPJ that will be used in this example (44.038.188/0001-32) we will have the following vector:
[latex] a = (4, 4, 0, 3, 8, 1, 8, 8, 0, 0, 0, 1) [/latex]
We determine the scalar product of this vector with the standard vector:
[latex] b = (5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2) [/latex]
OBS:
The default vector, as the name implies, will always be the same when the check digit is calculated.
[latex] a.b = a = (4, 4, 0, 3, 8, 1, 8, 8, 0, 0, 0, 1) . b = (5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2) = 20 + 16 + 0 + 6 + 72 + 8 + 56 + 48 + 0 + 0 + 0 + 2 = 228 [/latex]
Now we take the remainder of the division of the scalar product by 11, i.e. 228 divided by 11 will give us an integer remainder equal to 8. The first check digit is given by subtracting [latex] 11 – remainder[/latex] and the result is the number 3.
- Calculation of the second check digit:
Let’s take a vector [latex] c E R^13 [/latex] whose components are the first 12 digits that make up the CNPJ number plus the first check digit 3, calculated previously:
[latex] c = (4, 4, 0, 3, 8, 1, 8, 8, 0, 0, 0, 1, 3) [/latex]
We determine the scalar product of this vector with the standard vector:
[latex] d = (6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2) [/latex]
OBS:
In the second standard vector, the number 6 must be added to the first component of the vector.
[latex] c.d = (4, 4, 0, 3, 8, 1, 8, 8, 0, 0, 0, 1, 3) . (6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2) = 24 + 20 + 0 + 9 + 16 + 9 + 64 + 56 + 0 + 0 + 0 + 3 + 6 = 207 [/latex]
Now we take the remainder of the division of the scalar product by 11, i.e. 207 divided by 11 will give us an integer remainder equal to 9. The second check digit is given by subtracting [latex] 11 – remainder[/latex] and the result is the number 2.
Completing our CNPJ 44.038.188/0001-xx with the two calculated check digits will give us 44.038.188/0001-32.