Skip to content

Instantly share code, notes, and snippets.

@arkanister
Last active August 10, 2020 19:58
Show Gist options
  • Save arkanister/1fcd4672ef4d8e43798964cf875a86bc to your computer and use it in GitHub Desktop.
Save arkanister/1fcd4672ef4d8e43798964cf875a86bc to your computer and use it in GitHub Desktop.
CPF Generator
import random
def _cpf_dv(digits):
"""
Returns the calculated verification digit.
"""
mod = sum(a * b for a, b in zip(digits, range(len(digits) + 1, 1, -1))) % 11
return 0 if mod < 2 else 11 - mod
def mask_cpf(value):
digits = ''.join(filter(lambda x: x.isdigit(), map(str, value or '')))
length = len(digits)
if not digits or length > 11:
return value
digits = '%011s' % digits
return '%s.%s.%s-%s' % (digits[:3], digits[3:6], digits[6:9], digits[9:])
def generate_cpf(mask=False):
digits = [random.randint(0, 9) for _ in range(9)]
digits.append(_cpf_dv(digits))
digits.append(_cpf_dv(digits))
value = ''.join(map(str, digits))
return mask_cpf(value) if mask else value
def validate_cpf(value):
digits = list(map(int, filter(lambda x: x.isdigit(), value or '')))
length = len(digits)
if not digits or length > 11:
return False
digits = ([0] * (11 - length)) + digits
return digits[9] == _cpf_dv(digits[:9]) and digits[10] == _cpf_dv(digits[:10])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment