# Sunday, 21 February 2010

There are several bank specific rules for validating credit cards, but all card numbers can be validated using the Luhn algorithm. The Luhn algorithm, aka the Luhn formula or "modulus 10" algorithm, is a simple checksum formula used to validate a variety of identification numbers.

It is not intended to be a cryptographically secure hash function; it was designed to protect against accidental errors, not malicious attacks. Most credit cards and many government identification numbers use the algorithm as a simple method of distinguishing valid numbers from collections of random digits.

Programmers accustomed to using '%' as a modulus operator need only to shift gears slightly and use the Math.mod(int1, int2) library function when working with Apex.

public static boolean isValidCheckSum(List<integer> numbers){
	integer sum = 0;
	integer len = numbers.size();
	
	for (integer i = len - 1; i >= 0; i--)
	{
		if (math.mod(i , 2) == math.mod(len,  2) )
		{
			integer n = numbers[i] * 2;
			sum += (n / 10) + ( math.mod(n, 10));
		}
		else
			sum += numbers[i];
	}
	return ( math.mod( sum, 10) == 0 );
}