gitee.com/h79/goutils@v1.22.10/common/algorithm/cipher_ecb.go (about)

     1  package algorithm
     2  
     3  import (
     4  	"crypto/cipher"
     5  	"errors"
     6  )
     7  
     8  // CipherECB 模式加密
     9  type CipherECB struct {
    10  	cipherFunc func(key []byte) (cipher.Block, error)
    11  	//keySize    int
    12  	//blockSize  int
    13  	//identifier asn1.ObjectIdentifier
    14  }
    15  
    16  func NewECB(cipherFunc func(key []byte) (cipher.Block, error)) CipherECB {
    17  	return CipherECB{cipherFunc: cipherFunc}
    18  }
    19  
    20  //// 值大小
    21  //func (ecb CipherECB) KeySize() int {
    22  //	return ecb.keySize
    23  //}
    24  
    25  //// oid
    26  //func (ecb CipherECB) OID() asn1.ObjectIdentifier {
    27  //	return ecb.identifier
    28  //}
    29  
    30  // Encrypt 加密
    31  func (ecb CipherECB) Encrypt(plaintext, key []byte, iv []byte) ([]byte, error) {
    32  
    33  	block, err := ecb.cipherFunc(key)
    34  	if err != nil {
    35  		return nil, errors.New("pkcs/cipher:" + err.Error() + " failed to create cipher")
    36  	}
    37  	// 加密数据补码
    38  	plaintext = pkcs7Padding(plaintext, block.BlockSize())
    39  
    40  	// 需要保存的加密数据
    41  	encrypted := make([]byte, len(plaintext))
    42  	mode := NewECBEncrypt(block)
    43  	mode.CryptBlocks(encrypted, plaintext)
    44  
    45  	return encrypted, nil
    46  }
    47  
    48  // Decrypt 解密
    49  func (ecb CipherECB) Decrypt(ciphertext, key []byte, iv []byte) ([]byte, error) {
    50  	block, err := ecb.cipherFunc(key)
    51  	if err != nil {
    52  		return nil, err
    53  	}
    54  
    55  	// 判断数据是否为填充数据
    56  	l := len(ciphertext)
    57  	if l == 0 || l%block.BlockSize() != 0 {
    58  		return nil, errors.New("pkcs/cipher: invalid padding")
    59  	}
    60  
    61  	plaintext := make([]byte, len(ciphertext))
    62  	mode := NewECBDecrypter(block)
    63  	mode.CryptBlocks(plaintext, ciphertext)
    64  
    65  	return pkcs7UnPadding(plaintext), nil
    66  }