Skip to content

Commit df34be2

Browse files
committed
XChaCha20-Poly1305: encryption with nonce appended to ciphertext
1 parent 886a60f commit df34be2

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

_example/xchacha20poly1305/main.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,20 @@ func main() {
4545
return
4646
}
4747
fmt.Println("plaintext:", plaintext)
48+
49+
// encrypt the data using EncryptXChacha20poly1305WithNonceAppended function
50+
ciphertext, err = crypt.EncryptXChacha20poly1305WithNonceAppended(key, text)
51+
if err != nil {
52+
fmt.Println(err)
53+
return
54+
}
55+
fmt.Println("ciphertext:", ciphertext)
56+
57+
// decrypt the data using DecryptXChacha20poly1305WithNonceAppended function
58+
plaintext, err = crypt.DecryptXChacha20poly1305WithNonceAppended(key, ciphertext)
59+
if err != nil {
60+
fmt.Println(err)
61+
return
62+
}
63+
fmt.Println("plaintext:", plaintext)
4864
}

chaCha20.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,3 +129,29 @@ func DecryptXChacha20poly1305(key, nonce, ciphertext []byte) (text string, err e
129129

130130
return
131131
}
132+
133+
// EncryptXChacha20poly1305WithNonceAppended encrypts and authenticates the given message with
134+
// XChaCha20-Poly1305 AEAD using the given 256-bit key and 192-bit nonce.
135+
// It appends the ciphertext to the nonce [ciphertext = nonce + ciphertext].
136+
func EncryptXChacha20poly1305WithNonceAppended(key []byte, text string) (ciphertext []byte, err error) {
137+
ciphertext, nonce, err := EncryptXChacha20poly1305(key, text)
138+
if err != nil {
139+
return
140+
}
141+
ciphertext = append(nonce, ciphertext...)
142+
return
143+
}
144+
145+
// DecryptXChacha20poly1305WithNonceAppended decrypts and authenticates the given message with
146+
// XChaCha20-Poly1305 AEAD using the given 256-bit key and 192-bit nonce.
147+
// It expects the ciphertext along with the nonce [ciphertext = nonce + ciphertext].
148+
func DecryptXChacha20poly1305WithNonceAppended(key, ciphertext []byte) (text string, err error) {
149+
nonceSize := chacha20poly1305.NonceSizeX
150+
if len(ciphertext) < nonceSize {
151+
err = errors.New("ciphertext is too short")
152+
return
153+
}
154+
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
155+
text, err = DecryptXChacha20poly1305(key, nonce, ciphertext)
156+
return
157+
}

0 commit comments

Comments
 (0)