From dbf4de8913d52e8190d2738fdc6751db6b5e11dd Mon Sep 17 00:00:00 2001 From: fcoufour Date: Wed, 9 Jun 2021 11:27:13 +0200 Subject: [PATCH] =?UTF-8?q?feat:=20ajout=20de=20param=C3=A8tres=20anchor?= =?UTF-8?q?=20et=20username=20pour=20FCE=20(#76)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fce.go | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 60 insertions(+), 3 deletions(-) diff --git a/fce.go b/fce.go index c656221e..30d0182e 100644 --- a/fce.go +++ b/fce.go @@ -9,6 +9,12 @@ import ( "net/url" "strconv" "time" + "io" + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "encoding/hex" + "fmt" ) // Fce type pour l'API Fiche Commune Entreprise @@ -57,14 +63,65 @@ func getFceURL(c *gin.Context) { c.JSON(500, err.Error()) return } - fceVisitURL := makeFceVisitURL(siret, fce.Credential) + username := c.GetString("username") + fceVisitURL, err := makeFceVisitURL(siret, fce.Credential, username) + if err != nil { + c.JSON(500, err.Error()) + return + } c.String(200, fceVisitURL) } -func makeFceVisitURL(siret string, credential string) (string) { +func encrypt(stringToEncrypt string, key string) (string, error) { + bytesToEncrypt := []byte(stringToEncrypt) + keyBytes := []byte(key) + cipherBlock, err := aes.NewCipher(keyBytes) + if err != nil { + return "", err + } + aesGCM, err := cipher.NewGCM(cipherBlock) + if err != nil { + return "", err + } + nonce := make([]byte, aesGCM.NonceSize()) + if _, err = io.ReadFull(rand.Reader, nonce); err != nil { + return "", err + } + encryptedBytes := aesGCM.Seal(nonce, nonce, bytesToEncrypt, nil) + return fmt.Sprintf("%x", encryptedBytes), nil +} + +func decrypt(encryptedString string, key string) (string, error) { + encryptedBytes, _ := hex.DecodeString(encryptedString) + keyBytes := []byte(key) + cipherBlock, err := aes.NewCipher(keyBytes) + if err != nil { + return "", err + } + aesGCM, err := cipher.NewGCM(cipherBlock) + if err != nil { + return "", err + } + nonceSize := aesGCM.NonceSize() + nonce, data := encryptedBytes[:nonceSize], encryptedBytes[nonceSize:] + decryptedBytes, err := aesGCM.Open(nil, nonce, data, nil) + if err != nil { + return "", err + } + return fmt.Sprintf("%s", decryptedBytes), nil +} + +func makeFceVisitURL(siret string, credential string, username string) (string, error) { fceVisitURL := viper.GetString("fceVisitURL") + "establishment/" + siret params := url.Values{} + params.Add("anchor", "direccte") params.Add("credential", credential) + apiKey := viper.GetString("apiFceKey") + encryptedUsername, err := encrypt(username, apiKey) + params.Add("username", encryptedUsername) + if err != nil { + return "", err + } fceVisitURL += "?" + params.Encode() - return fceVisitURL + return fceVisitURL, nil } \ No newline at end of file