在 golang 中向字节片添加填充的正确方法?

Proper way to add padding to byte slice in golang?

我正尝试在 go 中加密一些数据,但它几乎不正确 cipher.BlockSize

是否有 "built-in" 添加填充的方法,或者我应该使用函数手动添加它?

这是我现在的解决方案:

// encrypt() encrypts the message, but sometimes the 
// message isn't the proper length, so we add padding.
func encrypt(msg []byte, key []byte) []byte {        
  cipher, err := aes.NewCipher(key)                  
  if err != nil {                                    
    log.Fatal(err)                                   
  }                                                  

  if len(msg) < cipher.BlockSize() {                 
    var endLength = cipher.BlockSize() - len(msg)    
    ending := make([]byte, endLength, endLength)     
    msg = append(msg[:], ending[:]...)               
    cipher.Encrypt(msg, msg)                         
  } else {                                           
    var endLength = len(msg) % cipher.BlockSize()    
    ending := make([]byte, endLength, endLength)     
    msg = append(msg[:], ending[:]...)               
    cipher.Encrypt(msg, msg)                         
  }                                                  
  return msg                                         
}                                                    

正在查看 Package cipher it appears like you may have to add the padding yourself, see PKCS#7 padding

本质上是添加所需的填充字节,每个字节的值是添加的填充字节数。

请注意,您需要始终如一地添加填充,这意味着如果要加密的数据恰好是块大小的倍数,则必须添加整个填充块,因为无法从数据中知道是否是否添加了填充,试图超越它是一个常见的错误。考虑如果最后一个字节是0x00,那是填充还是数据?

这是我的解决方案

// padOrTrim returns (size) bytes from input (bb)
// Short bb gets zeros prefixed, Long bb gets left/MSB bits trimmed
func padOrTrim(bb []byte, size int) []byte {
    l := len(bb)
    if l == size {
        return bb
    }
    if l > size {
        return bb[l-size:]
    }
    tmp := make([]byte, size)
    copy(tmp[size-l:], bb)
    return tmp
}