passage-go/passage.go

85 lines
1.5 KiB
Go
Raw Permalink Normal View History

2017-01-25 17:58:37 +00:00
package passage
import (
"crypto/sha256"
"strconv"
)
const (
UseLower = 1 << iota
UseUpper
UseNumber
UseSymbol
)
type Passage struct {
valids int
length int
pin string
}
func CreatePassage(pin string) *Passage {
p := new(Passage)
p.length = 20
p.valids = UseLower | UseUpper | UseNumber
2017-01-25 17:58:37 +00:00
p.pin = pin
return p
}
func (p *Passage) SetPin(pin string) {
p.pin = pin
}
func (p *Passage) EnableChars(which int) {
p.valids |= which
}
func (p *Passage) DisableChars(which int) {
p.valids ^= which
}
func (p *Passage) GetValidChars() string {
2017-01-25 17:58:37 +00:00
validChars := ""
if p.valids&UseLower == UseLower {
validChars += "abcdefghijklmnopqrstuvwxyz"
}
if p.valids&UseUpper == UseUpper {
validChars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
}
if p.valids&UseNumber == UseNumber {
validChars += "1234567890"
}
if p.valids&UseSymbol == UseSymbol {
validChars += "~!@#$%^&*()[]{}|;:,<.>/?"
}
return validChars
}
func (p *Passage) GetPassword(door string) string {
ret := ""
validChars := p.GetValidChars()
2017-01-25 17:58:37 +00:00
hashing := p.pin + " - " + door
shaArr := sha256.Sum256([]byte(hashing))
var sha []byte
for i := range shaArr {
sha = append(sha, shaArr[i])
}
for i := 0; i < p.length; i++ {
ret += string(validChars[int(sha[i])%len(validChars)])
}
return ret
}
func (p *Passage) GetChecksum() int {
ret := 0
sha := sha256.Sum256([]byte(p.pin))
for i := range sha {
ret += int(sha[i])
}
return ret
}
func (p *Passage) GetChecksumAsString() string {
return strconv.Itoa(p.GetChecksum())
}