diff --git a/README.md b/README.md index 375825b..fb816c6 100644 --- a/README.md +++ b/README.md @@ -75,4 +75,12 @@ This is also a **SM3** implementation whose performance is similar like golang n PASS ok github.com/emmansun/gmsm/sm3 3.043s - \ No newline at end of file +**SM4 Benchmark** + + Pure golang version + goos: windows + goarch: amd64 + pkg: github.com/emmansun/gmsm/sm4 + BenchmarkEncrypt-6 2671431 441 ns/op 36.28 MB/s 0 B/op 0 allocs/op + BenchmarkDecrypt-6 2709132 440 ns/op 36.40 MB/s 0 B/op 0 allocs/op + BenchmarkExpand-6 2543746 471 ns/op 16 B/op 1 allocs/op diff --git a/sm4/cipher_test.go b/sm4/cipher_test.go index 6767607..e93da01 100644 --- a/sm4/cipher_test.go +++ b/sm4/cipher_test.go @@ -10,6 +10,21 @@ import ( "testing" ) +type CryptTest struct { + key []byte + in []byte + out []byte +} + +var encryptTests = []CryptTest{ + { + // Appendix 1. + []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10}, + []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10}, + []byte{0x68, 0x1e, 0xdf, 0x34, 0xd2, 0x06, 0x96, 0x5e, 0x86, 0xb3, 0xe9, 0x4f, 0x53, 0x6e, 0x42, 0x46}, + }, +} + func Test_sample1(t *testing.T) { src := []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10} expected := []byte{0x68, 0x1e, 0xdf, 0x34, 0xd2, 0x06, 0x96, 0x5e, 0x86, 0xb3, 0xe9, 0x4f, 0x53, 0x6e, 0x42, 0x46} @@ -46,6 +61,43 @@ func Test_sample2(t *testing.T) { } } +func BenchmarkEncrypt(b *testing.B) { + tt := encryptTests[0] + c, err := NewCipher(tt.key) + if err != nil { + b.Fatal("NewCipher:", err) + } + out := make([]byte, len(tt.in)) + b.SetBytes(int64(len(out))) + b.ResetTimer() + for i := 0; i < b.N; i++ { + c.Encrypt(out, tt.in) + } +} + +func BenchmarkDecrypt(b *testing.B) { + tt := encryptTests[0] + c, err := NewCipher(tt.key) + if err != nil { + b.Fatal("NewCipher:", err) + } + out := make([]byte, len(tt.out)) + b.SetBytes(int64(len(out))) + b.ResetTimer() + for i := 0; i < b.N; i++ { + c.Decrypt(out, tt.out) + } +} + +func BenchmarkExpand(b *testing.B) { + tt := encryptTests[0] + c := &sm4Cipher{make([]uint32, rounds), make([]uint32, rounds)} + b.ResetTimer() + for i := 0; i < b.N; i++ { + expandKeyGo(tt.key, c.enc, c.dec) + } +} + func paddingPKCS7(buf []byte, blockSize int) []byte { bufLen := len(buf) padLen := blockSize - bufLen%blockSize