dongmo2324 2016-09-01 20:43
浏览 421
已采纳

在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                                         
}                                                    
  • 写回答

2条回答 默认 最新

  • douou1891 2016-09-01 20:58
    关注

    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?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?