Skip to content

Instantly share code, notes, and snippets.

@c3l3si4n
Last active March 22, 2020 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save c3l3si4n/286f0c6dd9f1ad54cfb4e17f94d39437 to your computer and use it in GitHub Desktop.
Save c3l3si4n/286f0c6dd9f1ad54cfb4e17f94d39437 to your computer and use it in GitHub Desktop.
Java - algoritmo de verificação de cpf | cpf verification and validation algorithm
public class Cpf {
private static final int[] cpfWeight = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2}; // pesos do cpf, para uso no algoritmo de digito verificador
private static int calculateVerifierDigit(String input, int[] weight) { // funcao de digito verificador, recebe a mensagem a ser verificada e seu peso
int sum = 0; // declaracao da soma
for (int i = input.length() - 1, digit; i >= 0; i--) {
digit = Integer.parseInt(input.substring(i, i + 1)); // itera por cada digito do input
sum += digit * weight[weight.length - input.length() + index]; // 10 - 11 + index
}
sum = 11 - sum % 11; // pega o "módulo 11" da soma
return sum > 9 ? 0 : sum; // se a soma for 10, retornar 0.
}
public static boolean isValidCPF(String cpf) {
if ((cpf == null) || (cpf.length() != 11)) // validacao basica
return false;
Integer firstDigit = calculateVerifierDigit(cpf.substring(0, 9), cpfWeight); // resultado deve ser o primeiro digito verificador do cpf
Integer secondDigit = calculateVerifierDigit(cpf.substring(0, 9) + firstDigit, cpfWeight); // resultado deve ser o segundo digito verificador
return cpf.equals(cpf.substring(0, 9) + firstDigit.toString() + secondDigit.toString()); // se os digitos estiverem corretos, os dois cpfs comparados serão iguais e a função retornará true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment