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

报告相同问题?

悬赏问题

  • ¥15 如何解决蓝牙通话音频突发失真问题
  • ¥15 安装opengauss数据库报错
  • ¥15 【急】在线问答CNC雕刻机的电子电路与编程
  • ¥60 在mc68335芯片上移植ucos ii 的成功工程文件
  • ¥15 笔记本外接显示器正常,但是笔记本屏幕黑屏
  • ¥15 Python pandas
  • ¥15 蓝牙硬件,可以用哪几种方法控制手机点击和滑动
  • ¥15 生物医学数据分析。基础课程就v经常唱课程舅成牛逼
  • ¥15 云环境云开发云函数对接微信商户中的分账功能
  • ¥15 空间转录组CRAD遇到问题