Skip to content

Commit

Permalink
Add the nonce to the endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
Sewci0 committed Sep 5, 2023
1 parent 71f57e7 commit cee0ea2
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 11 deletions.
25 changes: 15 additions & 10 deletions endpoint/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,27 +29,32 @@ import (
log "github.com/sirupsen/logrus"
)

const standardGcmNonceSize = 12

// GenerateNonce creates a random nonce of a fixed size
func GenerateNonce() ([]byte, error) {
nonce := make([]byte, standardGcmNonceSize)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
return []byte(base64.StdEncoding.EncodeToString(nonce)), nil
}

// EncryptText gzip input data and encrypts it using the supplied AES key
func EncryptText(text string, aesKey []byte, nonceEncoded []byte) (string, error) {
block, err := aes.NewCipher(aesKey)
if err != nil {
return "", err
}

gcm, err := cipher.NewGCM(block)
gcm, err := cipher.NewGCMWithNonceSize(block, standardGcmNonceSize)
if err != nil {
return "", err
}

nonce := make([]byte, gcm.NonceSize())
if nonceEncoded == nil {
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
} else {
if _, err = base64.StdEncoding.Decode(nonce, nonceEncoded); err != nil {
return "", err
}
nonce := make([]byte, standardGcmNonceSize)
if _, err = base64.StdEncoding.Decode(nonce, nonceEncoded); err != nil {
return "", err
}

data, err := compressData([]byte(text))
Expand Down
10 changes: 9 additions & 1 deletion endpoint/labels.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,15 @@ func (l Labels) Serialize(withQuotes bool, txtEncryptEnabled bool, aesKey []byte
return l.SerializePlain(withQuotes)
}

var encryptionNonce []byte = nil
var encryptionNonce []byte
if extractedNonce, nonceExists := l[txtEncryptionNonce]; nonceExists {
encryptionNonce = []byte(extractedNonce)
} else {
var err error
encryptionNonce, err = GenerateNonce()
if err != nil {
log.Fatalf("Failed to generate cryptographic nonce %#v.", err)
}
}

text := l.SerializePlain(false)
Expand All @@ -150,6 +156,8 @@ func (l Labels) Serialize(withQuotes bool, txtEncryptEnabled bool, aesKey []byte
log.Fatalf("Failed to encrypt the text %#v using the encryption key %#v. Got error %#v.", text, aesKey, err)
}

l[txtEncryptionNonce] = string(encryptionNonce)

if withQuotes {
text = fmt.Sprintf("\"%s\"", text)
}
Expand Down

0 comments on commit cee0ea2

Please sign in to comment.