github.com/aaabigfish/gopkg@v1.1.0/crypto/sm4.go (about)

     1  package crypto
     2  
     3  import (
     4  	"crypto/cipher"
     5  	"errors"
     6  
     7  	"github.com/tjfoc/gmsm/sm4"
     8  )
     9  
    10  func Sm4Encrypt(key, iv, plantText []byte, paddingStatus bool) ([]byte, error) {
    11  	block, err := sm4.NewCipher(key)
    12  	if err != nil {
    13  		return nil, err
    14  	}
    15  
    16  	if paddingStatus {
    17  		plantText = pkcs5Padding(plantText, block.BlockSize())
    18  	}
    19  
    20  	blockModel := cipher.NewCBCEncrypter(block, iv)
    21  	ciphertext := make([]byte, len(plantText))
    22  	blockModel.CryptBlocks(ciphertext, plantText)
    23  	return ciphertext, nil
    24  }
    25  
    26  func Sm4Decrypt(key, iv, ciphertext []byte, paddingStatus bool) ([]byte, error) {
    27  	block, err := sm4.NewCipher(key)
    28  	if err != nil {
    29  		return nil, err
    30  	}
    31  
    32  	if len(ciphertext) < block.BlockSize() {
    33  		return nil, errors.New("Sm4Decrypt crypto/cipher: ciphertext too short")
    34  	}
    35  
    36  	if len(ciphertext)%block.BlockSize() != 0 {
    37  		return nil, errors.New("Sm4Decrypt crypto/cipher: ciphertext is not a multiple of the block size")
    38  	}
    39  
    40  	blockModel := cipher.NewCBCDecrypter(block, iv)
    41  	plantText := make([]byte, len(ciphertext))
    42  	blockModel.CryptBlocks(plantText, ciphertext)
    43  	if paddingStatus {
    44  		return pkcs5UnPadding(plantText)
    45  	}
    46  
    47  	return plantText, nil
    48  }