checksums.py 730 B

12345678910111213141516171819202122232425
  1. """
  2. Common checksum routines.
  3. """
  4. __all__ = ['luhn']
  5. from django.utils import six
  6. LUHN_ODD_LOOKUP = (0, 2, 4, 6, 8, 1, 3, 5, 7, 9) # sum_of_digits(index * 2)
  7. def luhn(candidate):
  8. """
  9. Checks a candidate number for validity according to the Luhn
  10. algorithm (used in validation of, for example, credit cards).
  11. Both numeric and string candidates are accepted.
  12. """
  13. if not isinstance(candidate, six.string_types):
  14. candidate = str(candidate)
  15. try:
  16. evens = sum(int(c) for c in candidate[-1::-2])
  17. odds = sum(LUHN_ODD_LOOKUP[int(c)] for c in candidate[-2::-2])
  18. return ((evens + odds) % 10 == 0)
  19. except ValueError: # Raised if an int conversion fails
  20. return False