doulan0297 2014-05-27 14:39
浏览 388
已采纳

Golang十六进制编码

I'm attempting to recreate a PKCS #5 Padding algorithm I've found written in python.

The main line I'm struggling to recreate is this

return data + (chr(pad_count) * pad_count).encode('utf-8')

which essentially repeats pad_count (an integer, between 1 and 16), as a char, between 1 and 16 times. I'm having trouble getting a similar result in Go.

For example, pad_count of 11 will return the string

\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b

The closeset I've come is this:

b := make([]byte, 2)
binary.LittleEndian.PutUint16(b, uint16(padCount))
fmt.Println("Pad: ", padCount, "Hex: ", hex.EncodeToString(b))

which will return:

Pad: 11 Hex: 0b00

This is pretty close, and obviously I could take a substring, and add the \x myself, but is there a better way to go about this? Also if I substring, I feel there is no guarantee that would work for all the combinations.

  • 写回答

2条回答 默认 最新

  • doulu2011 2014-05-27 15:09
    关注

    As James Henstridge already mentioned the formatting you want (\x0b...) is not something that's required but rather python's representation of non-printable characters. See for yourself:

    >>> chr(3)
    '\x03'
    

    What you have to do is defined in RFC2898:

    [...] where the padding string PS consists of 8-(||M|| mod 8) octets each with value 8-(||M|| mod 8). The padding string PS will satisfy one of the following statements:

        PS = 01, if ||M|| mod 8 = 7 ;
        PS = 02 02, if ||M|| mod 8 = 6 ;
        ...
        PS = 08 08 08 08 08 08 08 08, if ||M|| mod 8 = 0.
    

    This means that you do not need uint16 but uint8 (since an octet has only 8 bits) and you also do not need to format your bytes the way python does. So the only thing you have to do is to use bytes.Repeat:

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

报告相同问题?

悬赏问题

  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备