dongmo2324 2016-09-01 12: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 12: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部