Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 优化 Sm4Ecb 的内存占用 #211

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 2 additions & 8 deletions sm4/sm4.go
Original file line number Diff line number Diff line change
Expand Up @@ -355,17 +355,11 @@ func Sm4Ecb(key []byte, in []byte, mode bool) (out []byte, err error) {
}
if mode {
for i := 0; i < len(inData)/16; i++ {
in_tmp := inData[i*16 : i*16+16]
out_tmp := make([]byte, 16)
c.Encrypt(out_tmp, in_tmp)
copy(out[i*16:i*16+16], out_tmp)
c.Encrypt(out[i*16:i*16+16], inData[i*16:i*16+16])
}
} else {
for i := 0; i < len(inData)/16; i++ {
in_tmp := inData[i*16 : i*16+16]
out_tmp := make([]byte, 16)
c.Decrypt(out_tmp, in_tmp)
copy(out[i*16:i*16+16], out_tmp)
c.Decrypt(out[i*16:i*16+16], inData[i*16:i*16+16])
}
out, _ = pkcs7UnPadding(out)
}
Expand Down
25 changes: 25 additions & 0 deletions sm4/sm4_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ limitations under the License.
package sm4

import (
"bytes"
"fmt"
"reflect"
"testing"
Expand Down Expand Up @@ -151,3 +152,27 @@ func testCompare(key1, key2 []byte) bool {
}
return true
}

func BenchmarkSm4EcbEncode(b *testing.B) {
key := []byte("0123456789abcdef")
data := bytes.Repeat([]byte("0123456789abcdef"), 10)

for i := 0; i < b.N; i++ {
_, err := Sm4Ecb(key, data, true)
if err != nil {
b.Fatal(err)
}
}
}

func BenchmarkSm4EcbDecode(b *testing.B) {
key := []byte("0123456789abcdef")
data := []byte("13278c63b7305e3c131cdbbbe6f59b8613278c63b7305e3c131cdbbbe6f59b8613278c63b7305e3c131cdbbbe6f59b8613278c63b7305e3c131cdbbbe6f59b8613278c63b7305e3c131cdbbbe6f59b8613278c63b7305e3c131cdbbbe6f59b8613278c63b7305e3c131cdbbbe6f59b8613278c63b7305e3c131cdbbbe6f59b8613278c63b7305e3c131cdbbbe6f59b8613278c63b7305e3c131cdbbbe6f59b86d14d7078d2f3a67fe00d3221dbb1d556")

for i := 0; i < b.N; i++ {
_, err := Sm4Ecb(key, data, false)
if err != nil {
b.Fatal(err)
}
}
}