changed public id format to be 128 bit length.

This commit is contained in:
didier amyot committed 2015-07-05 18:16:40 -04:00
1 parent 78d50d9a6d
commit d2cf9d7498
11 files changed
+187 -22

No files matched your search

+1 -1
View File
@@ -69,7 +69,7 @@ func (p *Params) InsertDefaultValues() *Params {
}
func LoadFromYamlFile(fileName string) (*Params, error) {
if !Exists(fileName) {
if !exists(fileName) {
return new(Params).InsertDefaultValues(), nil
}
data, err := ioutil.ReadFile(fileName)
+46 -2
View File
@@ -1,8 +1,17 @@
package shared
import "os"
import (
"crypto/subtle"
"encoding/base64"
"errors"
"github.com/dchest/siphash"
"gopkg.in/mgo.v2/bson"
"os"
)
func Exists(name string) bool {
var idHashKey []byte = []byte("semi-private-key")
func exists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
@@ -10,3 +19,38 @@ func Exists(name string) bool {
}
return true
}
func validateId(id []byte) error {
if len(id) != 16 {
return errors.New("valid ids are 16 bytes (126 bit) long.")
}
h := siphash.New(idHashKey)
h.Write(id[4:16])
if subtle.ConstantTimeCompare(h.Sum(nil)[0:4], id[0:4]) != 1 {
return errors.New("invalid id checksum")
}
return nil
}
func ObjectIdToPublicId(id bson.ObjectId) string {
if id == "" {
return ""
}
h := siphash.New(idHashKey)
h.Write([]byte(id))
return base64.URLEncoding.EncodeToString(append(h.Sum(nil)[0:4], []byte(id)...))
}
func PublicIdToObjectId(id string) (bson.ObjectId, error) {
if id == "" {
return "", nil
}
cypher, err := base64.URLEncoding.DecodeString(id)
if err != nil {
return "", err
}
if err := validateId(cypher); err != nil {
return "", err
}
return bson.ObjectId(cypher[4:16]), nil
}