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条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵