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

     1  package algorithm
     2  
     3  import "crypto/cipher"
     4  
     5  type ecb struct {
     6  	b         cipher.Block
     7  	blockSize int
     8  }
     9  
    10  func newECB(b cipher.Block) *ecb {
    11  	return &ecb{
    12  		b:         b,
    13  		blockSize: b.BlockSize(),
    14  	}
    15  }
    16  
    17  type ecbEncrypt ecb
    18  
    19  // NewECBEncrypt returns a BlockMode which encrypts in electronic code book
    20  // mode, using the given Block.
    21  func NewECBEncrypt(b cipher.Block) cipher.BlockMode {
    22  	return (*ecbEncrypt)(newECB(b))
    23  }
    24  
    25  func (e *ecbEncrypt) BlockSize() int {
    26  	return e.blockSize
    27  }
    28  
    29  func (e *ecbEncrypt) CryptBlocks(dst, src []byte) {
    30  	if len(src)%e.blockSize != 0 {
    31  		panic("cipher/ecb: input not full blocks")
    32  	}
    33  
    34  	if len(dst) < len(src) {
    35  		panic("cipher/ecb: output smaller than input")
    36  	}
    37  
    38  	for len(src) > 0 {
    39  		e.b.Encrypt(dst, src[:e.blockSize])
    40  		src = src[e.blockSize:]
    41  		dst = dst[e.blockSize:]
    42  	}
    43  }
    44  
    45  type ecbDecrypter ecb
    46  
    47  // NewECBDecrypter returns a BlockMode which decrypts in electronic code book
    48  // mode, using the given Block.
    49  func NewECBDecrypter(b cipher.Block) cipher.BlockMode {
    50  	return (*ecbDecrypter)(newECB(b))
    51  }
    52  
    53  func (e *ecbDecrypter) BlockSize() int {
    54  	return e.blockSize
    55  }
    56  
    57  func (e *ecbDecrypter) CryptBlocks(dst, src []byte) {
    58  	if len(src)%e.blockSize != 0 {
    59  		panic("cipher/ecb: input not full blocks")
    60  	}
    61  
    62  	if len(dst) < len(src) {
    63  		panic("cipher/ecb: output smaller than input")
    64  	}
    65  
    66  	for len(src) > 0 {
    67  		e.b.Decrypt(dst, src[:e.blockSize])
    68  		src = src[e.blockSize:]
    69  		dst = dst[e.blockSize:]
    70  	}
    71  }