@@ -155,10 +155,10 @@ const (
155
155
// or data key provided as plaintext.
156
156
//
157
157
// The returned ciphertext data consists of:
158
- // iv | AEAD ID | nonce | encrypted data
159
- // 32 1 12 ~ len(data)
158
+ // AEAD ID | iv | nonce | encrypted data
159
+ // 1 16 12 ~ len(data)
160
160
func encrypt (plaintext , associatedData []byte ) ([]byte , error ) {
161
- iv , err := sioutil .Random (32 ) // 32 bytes IV
161
+ iv , err := sioutil .Random (16 ) // 16 bytes IV
162
162
if err != nil {
163
163
return nil , err
164
164
}
@@ -186,7 +186,7 @@ func encrypt(plaintext, associatedData []byte) ([]byte, error) {
186
186
}
187
187
case c20p1305 :
188
188
var sealingKey []byte
189
- sealingKey , err = chacha20 .HChaCha20 (derivedKey , iv [: 16 ] ) // HChaCha20 expects nonce of 16 bytes
189
+ sealingKey , err = chacha20 .HChaCha20 (derivedKey , iv ) // HChaCha20 expects nonce of 16 bytes
190
190
if err != nil {
191
191
return nil , err
192
192
}
@@ -202,11 +202,11 @@ func encrypt(plaintext, associatedData []byte) ([]byte, error) {
202
202
203
203
sealedBytes := aead .Seal (nil , nonce , plaintext , associatedData )
204
204
205
- // ciphertext = iv | AEAD ID | nonce | sealed bytes
205
+ // ciphertext = AEAD ID | iv | nonce | sealed bytes
206
206
207
207
var buf bytes.Buffer
208
- buf .Write (iv )
209
208
buf .WriteByte (algorithm )
209
+ buf .Write (iv )
210
210
buf .Write (nonce )
211
211
buf .Write (sealedBytes )
212
212
@@ -218,16 +218,16 @@ func encrypt(plaintext, associatedData []byte) ([]byte, error) {
218
218
// and a pbkdf2 derived key
219
219
func decrypt (ciphertext []byte , associatedData []byte ) ([]byte , error ) {
220
220
var (
221
- iv [32 ]byte
222
221
algorithm [1 ]byte
222
+ iv [16 ]byte
223
223
nonce [12 ]byte // This depends on the AEAD but both used ciphers have the same nonce length.
224
224
)
225
225
226
226
r := bytes .NewReader (ciphertext )
227
- if _ , err := io .ReadFull (r , iv [:]); err != nil {
227
+ if _ , err := io .ReadFull (r , algorithm [:]); err != nil {
228
228
return nil , err
229
229
}
230
- if _ , err := io .ReadFull (r , algorithm [:]); err != nil {
230
+ if _ , err := io .ReadFull (r , iv [:]); err != nil {
231
231
return nil , err
232
232
}
233
233
if _ , err := io .ReadFull (r , nonce [:]); err != nil {
@@ -249,7 +249,7 @@ func decrypt(ciphertext []byte, associatedData []byte) ([]byte, error) {
249
249
return nil , err
250
250
}
251
251
case c20p1305 :
252
- sealingKey , err := chacha20 .HChaCha20 (derivedKey , iv [:16 ]) // HChaCha20 expects nonce of 16 bytes
252
+ sealingKey , err := chacha20 .HChaCha20 (derivedKey , iv [:]) // HChaCha20 expects nonce of 16 bytes
253
253
if err != nil {
254
254
return nil , err
255
255
}
0 commit comments