This commit is contained in:
2023-04-01 16:16:07 +11:00
parent 7184eba5f3
commit b19aeeb30d
5 changed files with 46 additions and 352 deletions

View File

@@ -1,6 +1,13 @@
package models
import "fmt"
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
"os"
)
type Secret struct {
SecretId int `db:"SecretId"`
@@ -29,3 +36,38 @@ func (s *Secret) SaveSecret() (*Secret, error) {
return s, nil
}
func (s *Secret) EncryptSecret() (*Secret, error) {
keyString := os.Getenv("SECRETS_KEY")
// The key argument should be the AES key, either 16 or 32 bytes
// to select AES-128 or AES-256.
key := []byte(keyString)
plaintext := []byte(s.Secret)
fmt.Printf("EncryptSecret applying key '%v' to plaintext secret '%s'\n", keyString, s.Secret)
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
// Never use more than 2^32 random nonces with a given key because of the risk of a repeat.
nonce := make([]byte, 12)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
fmt.Printf("EncryptSecret generated ciphertext '%x'\n", ciphertext)
s.Secret = string(ciphertext)
return s, nil
//return string(ciphertext[:]), nil
}