diff --git a/_example/aes/main.go b/_example/aes/main.go index 4727f21..16916e0 100644 --- a/_example/aes/main.go +++ b/_example/aes/main.go @@ -78,4 +78,52 @@ func main() { return } fmt.Println("plaintext:", plaintext) + + // encrypt the data with AES-128 in GCM using EncryptAesGcmWithNonceAppended function + ciphertext128, err = crypt.EncryptAesGcmWithNonceAppended(key128, text) + if err != nil { + fmt.Println(err) + return + } + fmt.Println("ciphertext (AES-128):", ciphertext128) + + // decrypt the data with AES-128 in GCM using DecryptAesGcmWithNonceAppended function + plaintext, err = crypt.DecryptAesGcmWithNonceAppended(key128, ciphertext128) + if err != nil { + fmt.Println(err) + return + } + fmt.Println("plaintext:", plaintext) + + // encrypt the data with AES-192 in GCM using EncryptAesGcmWithNonceAppended function + ciphertext192, err = crypt.EncryptAesGcmWithNonceAppended(key192, text) + if err != nil { + fmt.Println(err) + return + } + fmt.Println("ciphertext (AES-192):", ciphertext192) + + // decrypt the data with AES-192 in GCM using DecryptAesGcmWithNonceAppended function + plaintext, err = crypt.DecryptAesGcmWithNonceAppended(key192, ciphertext192) + if err != nil { + fmt.Println(err) + return + } + fmt.Println("plaintext:", plaintext) + + // encrypt the data with AES-256 in GCM using EncryptAesGcmWithNonceAppended function + ciphertext256, err = crypt.EncryptAesGcmWithNonceAppended(key256, text) + if err != nil { + fmt.Println(err) + return + } + fmt.Println("ciphertext (AES-256):", ciphertext256) + + // decrypt the data with AES-256 in GCM using DecryptAesGcmWithNonceAppended function + plaintext, err = crypt.DecryptAesGcmWithNonceAppended(key256, ciphertext256) + if err != nil { + fmt.Println(err) + return + } + fmt.Println("plaintext:", plaintext) } diff --git a/aes.go b/aes.go index e4b4479..c72d60d 100644 --- a/aes.go +++ b/aes.go @@ -72,3 +72,29 @@ func DecryptAesGcm(key, nonce, ciphertext []byte) (text string, err error) { return } + +// EncryptAesGcmWithNonceAppended encrypts and authenticates the given message with AES in GCM mode +// using the given 128, 192 or 256-bit key. +// It appends the ciphertext to the nonce. +func EncryptAesGcmWithNonceAppended(key []byte, text string) (ciphertext []byte, err error) { + ciphertext, nonce, err := EncryptAesGcm(key, text) + if err != nil { + return + } + ciphertext = append(nonce, ciphertext...) + return +} + +// DecryptAesGcmWithNonceAppended decrypts and authenticates the given message with AES in GCM mode +// using the given 128, 192 or 256-bit key. +// It expects the ciphertext to have the nonce appended. +func DecryptAesGcmWithNonceAppended(key, ciphertext []byte) (text string, err error) { + nonceSize := 12 + if len(ciphertext) < nonceSize { + err = fmt.Errorf("ciphertext is too short") + return + } + nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:] + text, err = DecryptAesGcm(key, nonce, ciphertext) + return +}