LUHN checksum algorithm Lua implementation

September 12, 2009 | Jaime Blasco

I have wrote a LUA function that implements the LUHN checksum algorithm (requires bitlib), this algorithm checks that a sequence of digits is a valid credit card number. Here is the code:

local bit = require("bit")

local band, bor, bxor =, bit.bor, bit.bxor

function checksum(card)

	num = 0

	nDigits = card:len()

	odd = band(nDigits, 1)


	for count = 0,nDigits-1 do

		digit = tonumber(string.sub(card, count+1,count+1))

		if (bxor(band(count, 1),odd)) == 0 then

			digit = digit * 2



		if digit > 9 then

			digit = digit - 9	



		num = num + digit



	return ((num % 10) == 0)



Jaime Blasco

About the Author: Jaime Blasco

Jaime Blasco is a renowned Security Researcher with broad experience in network security, malware analysis and incident response. At AT&T Cybersecurity, Jaime leads the Alien Labs Intelligence and Research team that leads the charge of researching and integrating threat intelligence into detection mechanisms. Prior to working at AT&T, Jaime was Chief Scientist at AlienVault. Prior to that, he founded a couple of startups (Eazel, Aitsec) working on web application security, source code analysis and incident response. He is based in San Francisco. Jaime's work in emerging threats and targeted attacks is frequently cited in international publications such as New York Times, BBC, Washington Post and Al Jazeera.

Read more posts from Jaime Blasco ›


Get price Free trial