Created
August 8, 2017 07:04
-
-
Save iwat/4a508fadf2da52b8f7abdccf89455642 to your computer and use it in GitHub Desktop.
Luhn Generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Given a first 6 digits and last 4 digits. | |
// It will generate full 16-digit PANs that satisfy Luhn algorithm. | |
package main | |
import ( | |
"flag" | |
"fmt" | |
"strconv" | |
"strings" | |
) | |
func main() { | |
flag.Parse() | |
args := flag.Args() | |
lead := args[0] | |
tail := args[1] | |
for i := 0; i <= 999999; i++ { | |
if luhnValid(fmt.Sprintf("%s%06d%s", lead, i, tail)) { | |
fmt.Printf("%s%06d%s\n", lead, i, tail) | |
} | |
} | |
} | |
func luhnValid(luhnString string) bool { | |
checksumMod := calculateChecksum(luhnString, false) % 10 | |
return checksumMod == 0 | |
} | |
func calculateChecksum(luhnString string, double bool) int { | |
source := strings.Split(luhnString, "") | |
checksum := 0 | |
for i := len(source) - 1; i > -1; i-- { | |
t, _ := strconv.ParseInt(source[i], 10, 8) | |
n := int(t) | |
if double { | |
n = n * 2 | |
} | |
double = !double | |
if n >= 10 { | |
n = n - 9 | |
} | |
checksum += n | |
} | |
return checksum | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment