Skip to content

Commit fa74f14

Browse files
authored
Merge pull request #92 from microsoft/add-sealrandomwithnonce-method
Add: SealWithRandomNonce logic
2 parents 9b8dc63 + 3edf1de commit fa74f14

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

cng/aes.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,40 @@ func (g *aesGCM) Seal(dst, nonce, plaintext, additionalData []byte) []byte {
337337
return ret
338338
}
339339

340+
func (g *aesGCM) SealWithRandomNonce(out, nonce, plaintext, additionalData []byte) {
341+
if uint64(len(plaintext)) > uint64((1<<32)-2)*aesBlockSize {
342+
panic("crypto/cipher: message too large for GCM")
343+
}
344+
if len(nonce) != gcmStandardNonceSize {
345+
panic("crypto/cipher: incorrect nonce length given to GCMWithRandomNonce")
346+
}
347+
if len(out) != len(plaintext)+gcmTagSize {
348+
panic("crypto/cipher: incorrect output length given to GCMWithRandomNonce")
349+
}
350+
if subtle.InexactOverlap(out, plaintext) {
351+
panic("crypto/cipher: invalid buffer overlap of output and input")
352+
}
353+
if subtle.AnyOverlap(out, additionalData) {
354+
panic("crypto/cipher: invalid buffer overlap of output and additional data")
355+
}
356+
357+
if g.tls != cipherGCMTLSNone {
358+
panic("cipher: TLS 1.2 and 1.3 modes do not support random nonce")
359+
}
360+
361+
RandReader.Read(nonce)
362+
info := bcrypt.NewAUTHENTICATED_CIPHER_MODE_INFO(nonce, additionalData, out[len(out)-gcmTagSize:])
363+
var encSize uint32
364+
err := bcrypt.Encrypt(g.kh, plaintext, unsafe.Pointer(info), nil, out, &encSize, 0)
365+
if err != nil {
366+
panic(err)
367+
}
368+
if int(encSize) != len(plaintext) {
369+
panic("crypto/cipher: plaintext not fully encrypted")
370+
}
371+
runtime.KeepAlive(g)
372+
}
373+
340374
var errOpen = errors.New("cipher: message authentication failed")
341375

342376
func (g *aesGCM) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {

0 commit comments

Comments
 (0)