sm4: use new functions: clear(), bytes.Clone()

This commit is contained in:
Sun Yimin 2025-02-26 10:19:56 +08:00 committed by GitHub
parent ec8580b01f
commit 27e7ceacbc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 18 additions and 32 deletions

View File

@ -3,6 +3,7 @@
package sm4
import (
"bytes"
"crypto/cipher"
"github.com/emmansun/gmsm/internal/alias"
@ -23,21 +24,19 @@ type cbc struct {
}
func (b *sm4CipherAsm) NewCBCEncrypter(iv []byte) cipher.BlockMode {
var c cbc
c.b = b
c.enc = cbcEncrypt
c.iv = make([]byte, BlockSize)
copy(c.iv, iv)
return &c
return &cbc{
b: b,
iv: bytes.Clone(iv),
enc: cbcEncrypt,
}
}
func (b *sm4CipherAsm) NewCBCDecrypter(iv []byte) cipher.BlockMode {
var c cbc
c.b = b
c.enc = cbcDecrypt
c.iv = make([]byte, BlockSize)
copy(c.iv, iv)
return &c
return &cbc{
b: b,
iv: bytes.Clone(iv),
enc: cbcDecrypt,
}
}
func (x *cbc) BlockSize() int { return BlockSize }

View File

@ -3,6 +3,7 @@
package sm4
import (
"bytes"
"crypto/cipher"
"github.com/emmansun/gmsm/internal/alias"
@ -33,11 +34,10 @@ func (c *sm4CipherAsm) NewCTR(iv []byte) cipher.Stream {
}
s := &ctr{
b: c,
ctr: make([]byte, c.blocksSize),
ctr: bytes.Clone(iv),
out: make([]byte, 0, bufSize),
outUsed: 0,
}
copy(s.ctr, iv)
for i := 1; i < c.batchBlocks; i++ {
s.genCtr(i * BlockSize)
}

View File

@ -33,17 +33,11 @@ func (x *ecb) validate(dst, src []byte) {
}
func (b *sm4CipherAsm) NewECBEncrypter() cipher.BlockMode {
var c ecb
c.b = b
c.enc = ecbEncrypt
return &c
return &ecb{b: b, enc: ecbEncrypt}
}
func (b *sm4CipherAsm) NewECBDecrypter() cipher.BlockMode {
var c ecb
c.b = b
c.enc = ecbDecrypt
return &c
return &ecb{b: b, enc: ecbDecrypt}
}
func (x *ecb) BlockSize() int { return BlockSize }

View File

@ -152,9 +152,7 @@ func (g *gcm) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) {
// so overwrites dst in the event of a tag mismatch. That
// behavior is mimicked here in order to be consistent across
// platforms.
for i := range out {
out[i] = 0
}
clear(out)
return nil, errOpen
}

View File

@ -237,10 +237,7 @@ func (g *gcmAsm) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) {
}
if _subtle.ConstantTimeCompare(expectedTag[:g.tagSize], tag) != 1 {
// clear(out)
for i := range out {
out[i] = 0
}
clear(out)
return nil, errOpen
}

View File

@ -135,9 +135,7 @@ func (g *gcmNI) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) {
gcmSm4Finish(&g.bytesProductTable, &tagMask, &expectedTag, uint64(len(ciphertext)), uint64(len(data)))
if subtle.ConstantTimeCompare(expectedTag[:g.tagSize], tag) != 1 {
for i := range out {
out[i] = 0
}
clear(out)
return nil, errOpen
}
return ret, nil