Skip to content

Commit 24a55b7

Browse files
committed
feat: support selection of encryption and decryption methods, add gm sm4 crypto type
1 parent 5e909f1 commit 24a55b7

File tree

1 file changed

+18
-8
lines changed

1 file changed

+18
-8
lines changed

pkg/misc/crypto.go

+18-8
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,9 @@ import (
2222
"crypto/cipher"
2323
"crypto/rand"
2424
"fmt"
25-
"io"
26-
2725
"github.com/pkg/errors"
2826
"github.com/tjfoc/gmsm/sm4"
27+
"io"
2928
)
3029

3130
type CryptoType int
@@ -314,43 +313,54 @@ func Sm4DecryptECB(encrypted, key []byte) (decrypted []byte, err error) {
314313
}
315314

316315
func Sm4EncryptCBC(origData, key, iv []byte) (encrypted []byte, err error) {
317-
if err = sm4.SetIV(iv); err != nil {
316+
if err = sm4.SetIV(EnsureByteArrayLength16(iv)); err != nil {
318317
return nil, err
319318
}
320319
return sm4.Sm4Cbc(key, origData, true)
321320
}
322321

323322
func Sm4DecryptCBC(encrypted, key, iv []byte) (decrypted []byte, err error) {
324-
if err = sm4.SetIV(iv); err != nil {
323+
if err = sm4.SetIV(EnsureByteArrayLength16(iv)); err != nil {
325324
return nil, err
326325
}
327326
return sm4.Sm4Cbc(key, encrypted, false)
328327
}
329328

330329
func Sm4EncryptCFB(origData, key, iv []byte) (encrypted []byte, err error) {
331-
if err = sm4.SetIV(iv); err != nil {
330+
if err = sm4.SetIV(EnsureByteArrayLength16(iv)); err != nil {
332331
return nil, err
333332
}
334333
return sm4.Sm4CFB(key, origData, true)
335334
}
336335

337336
func Sm4DecryptCFB(encrypted, key, iv []byte) (decrypted []byte, err error) {
338-
if err = sm4.SetIV(iv); err != nil {
337+
if err = sm4.SetIV(EnsureByteArrayLength16(iv)); err != nil {
339338
return nil, err
340339
}
341340
return sm4.Sm4CFB(key, encrypted, false)
342341
}
343342

344343
func Sm4EncryptOFB(origData, key, iv []byte) (encrypted []byte, err error) {
345-
if err = sm4.SetIV(iv); err != nil {
344+
if err = sm4.SetIV(EnsureByteArrayLength16(iv)); err != nil {
346345
return nil, err
347346
}
348347
return sm4.Sm4OFB(key, origData, true)
349348
}
350349

351350
func Sm4DecryptOFB(encrypted, key, iv []byte) (decrypted []byte, err error) {
352-
if err = sm4.SetIV(iv); err != nil {
351+
if err = sm4.SetIV(EnsureByteArrayLength16(iv)); err != nil {
353352
return nil, err
354353
}
355354
return sm4.Sm4OFB(key, encrypted, false)
356355
}
356+
357+
func EnsureByteArrayLength16(input []byte) []byte {
358+
if len(input) == 16 {
359+
return input
360+
}
361+
repeated := append(input, input...)
362+
for len(repeated) < 16 {
363+
repeated = append(repeated, input...)
364+
}
365+
return repeated[:16]
366+
}

0 commit comments

Comments
 (0)