github.com/iikira/iikira-go-utils@v0.0.0-20230610031953-f2cb11cde33a/utils/bdcrypto/ecb/ecb.go (about)

     1  // Copyright 2013 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Electronic Code Book (ECB) mode.
     6  
     7  // ECB provides confidentiality by assigning a fixed ciphertext block to each
     8  // plaintext block.
     9  
    10  // See NIST SP 800-38A, pp 08-09
    11  
    12  package ecb
    13  
    14  import (
    15  	"crypto/cipher"
    16  )
    17  
    18  type ecb struct {
    19  	b         cipher.Block
    20  	blockSize int
    21  }
    22  
    23  func newECB(b cipher.Block) *ecb {
    24  	return &ecb{
    25  		b:         b,
    26  		blockSize: b.BlockSize(),
    27  	}
    28  }
    29  
    30  type ecbEncrypter ecb
    31  
    32  // NewECBEncrypter returns a BlockMode which encrypts in electronic code book
    33  // mode, using the given Block.
    34  func NewECBEncrypter(b cipher.Block) cipher.BlockMode {
    35  	return (*ecbEncrypter)(newECB(b))
    36  }
    37  
    38  func (x *ecbEncrypter) BlockSize() int { return x.blockSize }
    39  
    40  func (x *ecbEncrypter) CryptBlocks(dst, src []byte) {
    41  	if len(src)%x.blockSize != 0 {
    42  		panic("crypto/cipher: input not full blocks")
    43  	}
    44  	if len(dst) < len(src) {
    45  		panic("crypto/cipher: output smaller than input")
    46  	}
    47  	for len(src) > 0 {
    48  		x.b.Encrypt(dst, src[:x.blockSize])
    49  		src = src[x.blockSize:]
    50  		dst = dst[x.blockSize:]
    51  	}
    52  }
    53  
    54  type ecbDecrypter ecb
    55  
    56  // NewECBDecrypter returns a BlockMode which decrypts in electronic code book
    57  // mode, using the given Block.
    58  func NewECBDecrypter(b cipher.Block) cipher.BlockMode {
    59  	return (*ecbDecrypter)(newECB(b))
    60  }
    61  
    62  func (x *ecbDecrypter) BlockSize() int { return x.blockSize }
    63  
    64  func (x *ecbDecrypter) CryptBlocks(dst, src []byte) {
    65  	if len(src)%x.blockSize != 0 {
    66  		panic("crypto/cipher: input not full blocks")
    67  	}
    68  	if len(dst) < len(src) {
    69  		panic("crypto/cipher: output smaller than input")
    70  	}
    71  	for len(src) > 0 {
    72  		x.b.Decrypt(dst, src[:x.blockSize])
    73  		src = src[x.blockSize:]
    74  		dst = dst[x.blockSize:]
    75  	}
    76  }