keycard-go/secrets.go

95 lines
2.0 KiB
Go
Raw Permalink Normal View History

2019-03-11 10:05:28 +00:00
package keycard
2018-10-04 10:10:19 +00:00
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"fmt"
"math/big"
2019-03-13 12:49:49 +00:00
"github.com/status-im/keycard-go/crypto"
2018-10-04 10:10:19 +00:00
"golang.org/x/crypto/pbkdf2"
"golang.org/x/text/unicode/norm"
)
const (
2019-03-13 12:49:49 +00:00
maxPukNumber = int64(999999999999)
maxPinNumber = int64(999999)
2018-10-04 10:10:19 +00:00
)
2018-10-05 14:40:32 +00:00
// Secrets contains the secret data needed to pair a client with a card.
2018-10-04 10:10:19 +00:00
type Secrets struct {
2018-10-22 17:33:53 +00:00
pin string
2018-10-04 10:10:19 +00:00
puk string
pairingPass string
pairingToken []byte
}
2019-03-14 15:04:36 +00:00
func NewSecrets(pin, puk, pairingPass string) *Secrets {
return &Secrets{
2019-03-19 14:11:39 +00:00
pin: pin,
puk: puk,
pairingPass: pairingPass,
pairingToken: generatePairingToken(pairingPass),
2019-03-14 15:04:36 +00:00
}
}
// GenerateSecrets generate a new Secrets with random puk and pairing password.
func GenerateSecrets() (*Secrets, error) {
2018-10-04 10:10:19 +00:00
pairingPass, err := generatePairingPass()
if err != nil {
return nil, err
}
puk, err := rand.Int(rand.Reader, big.NewInt(maxPukNumber))
if err != nil {
return nil, err
}
2018-10-22 17:33:53 +00:00
pin, err := rand.Int(rand.Reader, big.NewInt(maxPinNumber))
if err != nil {
return nil, err
}
2018-10-04 10:10:19 +00:00
return &Secrets{
2018-10-22 17:33:53 +00:00
pin: fmt.Sprintf("%06d", pin.Int64()),
2018-10-04 10:10:19 +00:00
puk: fmt.Sprintf("%012d", puk.Int64()),
pairingPass: pairingPass,
pairingToken: generatePairingToken(pairingPass),
}, nil
}
2018-10-22 17:33:53 +00:00
// Pin returns the pin string.
func (s *Secrets) Pin() string {
return s.pin
}
2018-10-05 14:40:32 +00:00
// Puk returns the puk string.
2018-10-04 10:10:19 +00:00
func (s *Secrets) Puk() string {
return s.puk
}
2018-10-05 14:40:32 +00:00
// PairingPass returns the pairing password string.
2018-10-04 10:10:19 +00:00
func (s *Secrets) PairingPass() string {
return s.pairingPass
}
2018-10-05 14:40:32 +00:00
// PairingToken returns the pairing token generated from the random pairing password.
2018-10-04 10:10:19 +00:00
func (s *Secrets) PairingToken() []byte {
return s.pairingToken
}
func generatePairingPass() (string, error) {
r := make([]byte, 12)
_, err := rand.Read(r)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(r), nil
}
func generatePairingToken(pass string) []byte {
2019-03-13 12:49:49 +00:00
return pbkdf2.Key(norm.NFKD.Bytes([]byte(pass)), norm.NFKD.Bytes([]byte(crypto.PairingTokenSalt)), 50000, 32, sha256.New)
2018-10-04 10:10:19 +00:00
}