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

报告相同问题?

悬赏问题

  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面