github.com/aacfactory/fns@v1.2.85/commons/cryptos/ciphers/ebc.go (about)

     1  /*
     2   * Copyright 2023 Wang Min Xiang
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   * 	http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   *
    16   */
    17  
    18  package ciphers
    19  
    20  import (
    21  	"crypto/cipher"
    22  	"github.com/aacfactory/errors"
    23  )
    24  
    25  func ECBEncrypt(block cipher.Block, plain []byte, padding int) (encrypted []byte, err error) {
    26  	blockSize := block.BlockSize()
    27  	plain = Padding(padding, plain, block.BlockSize())
    28  	plainLen := len(plain)
    29  	encrypted = make([]byte, plainLen)
    30  	if plainLen%blockSize != 0 {
    31  		err = errors.Warning("ebc: input not full blocks")
    32  		return
    33  	}
    34  	p := encrypted[:]
    35  	for len(plain) > 0 {
    36  		block.Encrypt(p, plain[:blockSize])
    37  		plain = plain[blockSize:]
    38  		p = p[blockSize:]
    39  	}
    40  	return
    41  }
    42  
    43  func ECBDecrypt(block cipher.Block, encrypted []byte, padding int) (plain []byte, err error) {
    44  	encryptedLen := len(encrypted)
    45  	pad := make([]byte, encryptedLen)
    46  	blockSize := block.BlockSize()
    47  	if encryptedLen%blockSize != 0 {
    48  		err = errors.Warning("ebc: input not full blocks").WithCause(err)
    49  		return
    50  	}
    51  	p := pad[:]
    52  	for len(encrypted) > 0 {
    53  		block.Decrypt(p, encrypted[:blockSize])
    54  		encrypted = encrypted[blockSize:]
    55  		p = p[blockSize:]
    56  	}
    57  	plain, err = UnPadding(padding, pad)
    58  	if err != nil {
    59  		err = errors.Warning("ebc: unPadding failed").WithCause(err)
    60  		return
    61  	}
    62  	return
    63  }