github.com/benoitkugler/goacve@v0.0.0-20201217100549-151ce6e55dc8/server/shared/security.go (about) 1 package shared 2 3 import ( 4 "encoding/base64" 5 "encoding/json" 6 "fmt" 7 8 rd "github.com/benoitkugler/goACVE/server/core/rawdata" 9 "github.com/benoitkugler/goACVE/logs" 10 ) 11 12 const ( 13 OrDocument Origine = iota 14 OrMiniature 15 OrPersonne 16 OrParticipant 17 OrFacture 18 OrAide 19 OrStructureaide 20 OrPreIdentification 21 OrValidationMail 22 OrEquipier 23 OrContrainte 24 OrSondage 25 ) 26 27 type Origine int 28 29 type cryptedId struct { 30 Origine Origine `json:"o"` 31 Id int64 `json:"i"` 32 } 33 34 type crypteur struct { 35 Salt string `json:"s"` 36 Data interface{} 37 } 38 39 func Encode(p logs.Encrypteur, data interface{}) (string, error) { 40 c2 := crypteur{Data: data} 41 c2.Salt = rd.RandString(5, true) 42 b, err := json.Marshal(c2) 43 if err != nil { 44 return "", err 45 } 46 return encrypt(p, b) 47 } 48 49 func Decode(p logs.Encrypteur, in string, out interface{}) error { 50 b, err := decrypt(p, in) 51 if err != nil { 52 return err 53 } 54 c := crypteur{Data: out} 55 return json.Unmarshal(b, &c) 56 } 57 58 func EncodeID(p logs.Encrypteur, origine Origine, id int64) (string, error) { 59 return Encode(p, cryptedId{Origine: origine, Id: id}) 60 } 61 62 func DecodeID(p logs.Encrypteur, in string, origine Origine) (int64, error) { 63 var out cryptedId 64 if err := Decode(p, in, &out); err != nil { 65 return 0, err 66 } 67 if out.Origine != origine { 68 return 0, fmt.Errorf("wrong origine : expected %d, got %d", origine, out.Origine) 69 } 70 return out.Id, nil 71 } 72 73 func encrypt(p logs.Encrypteur, data []byte) (string, error) { 74 ciphertext, err := p.Encrypt(data) 75 return base64.RawURLEncoding.EncodeToString(ciphertext), err 76 } 77 78 func decrypt(p logs.Encrypteur, dataStr string) ([]byte, error) { 79 data, err := base64.RawURLEncoding.DecodeString(dataStr) 80 if err != nil { 81 return nil, err 82 } 83 return p.Decrypt(data) 84 }