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: optimize pkcs7Padding #212

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
7 changes: 4 additions & 3 deletions sm4/sm4.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ modified by Jack, 2017 Oct
package sm4

import (
"bytes"
"crypto/cipher"
"errors"
"strconv"
Expand Down Expand Up @@ -268,8 +267,10 @@ func xor(in, iv []byte) (out []byte) {

func pkcs7Padding(src []byte) []byte {
padding := BlockSize - len(src)%BlockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(src, padtext...)
for i := 0; i < padding; i++ {
src = append(src, byte(padding))
}
return src
}

func pkcs7UnPadding(src []byte) ([]byte, error) {
Expand Down
19 changes: 19 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,21 @@ func testCompare(key1, key2 []byte) bool {
}
return true
}

func TestPkcs7Padding(t *testing.T) {
src := []byte("0123456789abcdef")
src = pkcs7Padding(src)

want := []byte{48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16}
if !bytes.Equal(src, want) {
t.Errorf("want %v, got %v", want, src)
}
}

func BenchmarkPkcs7Padding(b *testing.B) {
for i := 0; i < b.N; i++ {
src := []byte("0123456789abcdef")
src = pkcs7Padding(src)
_ = src
}
}