Skip to content

Commit

Permalink
Implement go version of the Bolivian invoice code algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
pcriv committed Jan 21, 2020
1 parent efd26b7 commit 6c12236
Show file tree
Hide file tree
Showing 5 changed files with 215 additions and 0 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2020 Pablo Crivella.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
162 changes: 162 additions & 0 deletions complicode.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
package complicode

import (
"crypto/rc4"
"encoding/hex"
"math"
"strconv"
"strings"
"time"

"github.com/chtison/baseconverter"
"github.com/osamingo/checkdigit"
)

var verhoeff = checkdigit.NewVerhoeff()

type Invoice struct {
Nit int
Number int
Amount float64
Date time.Time
}

type asciiSums struct {
total int
partials []int
}

const base64 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/"

// Generate a code for the given authCode, key and invoice
func Generate(authCode string, key string, inv Invoice) string {
seed1 := strconv.Itoa(inv.Number)
seed2 := strconv.Itoa(inv.Nit)
seed3 := inv.Date.Format("20060102")
seed4 := strconv.FormatFloat(math.Round(inv.Amount), 'f', -1, 64)

seeds := []string{seed1, seed2, seed3, seed4}
seeds = appendVerificationsDigits(seeds, 2)
digits := generateVerificationDigits(seeds)
partialKeys := generatePartialKeys(key, digits)

seeds = append([]string{authCode}, seeds...)
seeds = appendPartialKeys(seeds, partialKeys)

encryptionKey := key + digits
encryptedData := encrypt(strings.Join(seeds, ""), encryptionKey)
asciiSums := generateASCIISums(encryptedData, len(partialKeys))

sum := 0

for i, partialSum := range asciiSums.partials {
sum += (asciiSums.total * partialSum / len(partialKeys[i]))
}

data := changeBase(sum)
code := encrypt(data, encryptionKey)

return format(code)
}

func appendVerificationsDigits(seeds []string, count int) []string {
for index, seed := range seeds {
seeds[index] = appendVerificationDigits(seed, count)
}

return seeds
}

func appendVerificationDigits(seed string, count int) string {
for i := 1; i <= count; i++ {
digit, _ := verhoeff.Generate(seed)
seed += strconv.Itoa(digit)
}

return seed
}

func generateVerificationDigits(seeds []string) string {
sum := sumSeeds(seeds)
digits := appendVerificationDigits(strconv.Itoa(sum), 5)

return digits[len(digits)-5:]
}

func sumSeeds(seeds []string) int {
sum := 0

for _, seed := range seeds {
number, _ := strconv.Atoi(seed)
sum += number
}

return sum
}

func generatePartialKeys(key string, verificationDigits string) []string {
var partialKeySizes []int

for _, digit := range strings.Split(verificationDigits, "") {
size, _ := strconv.Atoi(digit)
partialKeySizes = append(partialKeySizes, size+1)
}

var partialKeys []string

start := 0
for _, size := range partialKeySizes {
end := start + size
pk := key[start:end]
partialKeys = append(partialKeys, pk)
start += size
}

return partialKeys
}

func appendPartialKeys(seeds []string, partialKeys []string) []string {
for index, seed := range seeds {
seeds[index] = seed + partialKeys[index]
}

return seeds
}

func encrypt(data string, key string) string {
cipher, _ := rc4.NewCipher([]byte(key))
encrypted := make([]byte, len(data))
cipher.XORKeyStream(encrypted, []byte(data))

return strings.ToUpper(hex.EncodeToString(encrypted))
}

func generateASCIISums(data string, partialsCount int) asciiSums {
sums := asciiSums{total: 0, partials: make([]int, partialsCount)}

for i, b := range []byte(data) {
sums.total += int(b)
sums.partials[i%partialsCount] += int(b)
}

return sums
}

func changeBase(number int) string {
result, _ := baseconverter.UInt64ToBase(uint64(number), base64)

return result
}

func format(code string) string {
formatted := ""

for i, char := range code {
if i != 0 && i%2 == 0 {
formatted += "-"
}
formatted += string(char)
}

return formatted
}
20 changes: 20 additions & 0 deletions complicode_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package complicode

import (
"testing"
"time"
)

func TestGenerate(t *testing.T) {
authCode := "29040011007"
key := "9rCB7Sv4X29d)5k7N%3ab89p-3(5[A"
date, _ := time.Parse("20060102", "20070702")
inv := Invoice{Number: 1503, Nit: 4189179011, Date: date, Amount: 2500}
code := Generate(authCode, key, inv)

expected := "6A-DC-53-05-14"

if code != expected {
t.Errorf("Generate() = %q, expected %q", code, expected)
}
}
8 changes: 8 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module github.com/pablocrivella/complicode-go

go 1.13

require (
github.com/chtison/baseconverter v1.1.0
github.com/osamingo/checkdigit v1.0.0
)
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
github.com/chtison/baseconverter v1.1.0 h1:sQU2ajzqQ9SRL/Bu7pYO8WriYUaGhO2tkJ5mEYVZn2A=
github.com/chtison/baseconverter v1.1.0/go.mod h1:5dP/UBFmWK2kow1iJj1N0HxArisokPO54a5WdI6b/PY=
github.com/osamingo/checkdigit v1.0.0 h1:c5vj+swZrFKWtQEUqj9DbgzTGYa1UscZO5Rwz9L8RKU=
github.com/osamingo/checkdigit v1.0.0/go.mod h1:1YyIqzN+gc5pRmqS39JtDY8Wz0CWY4+VOpR4dtQLUAY=

0 comments on commit 6c12236

Please sign in to comment.