hermancain
hermancain

Reputation: 1622

Proper way to add padding to byte slice in golang?

I'm trying to encrypt some data in go but it's hardly ever the correct cipher.BlockSize.

Is there a "built-in" way to add padding or should I be using a function to add it manually?

This is my solution now:

// 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                                         
}                                                    

Upvotes: 2

Views: 8362

Answers (2)

Plato
Plato

Reputation: 11052

here's my solution

// 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
}

Upvotes: 0

zaph
zaph

Reputation: 112857

Looking at Package cipher it appears like you may have to add the padding yourself, see PKCS#7 padding.

Essentially add the required padding bytes with the value of each byte the number of padding byte added.

Note that you need to add padding consistently and that means that if the data to be encrypted is an exact multiple of the block size an entire block of padding must be added since there is no way to know from the data if padding has been added or not, it is a common mistake to try to out-smart this. Consider if the last byte is 0x00, is that padding or data?

Upvotes: 1

Related Questions