Jameo
Jameo

Reputation: 4607

Golang hex encoding

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.

Upvotes: 0

Views: 3998

Answers (2)

nemo
nemo

Reputation: 57649

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)

Upvotes: 7

user634175
user634175

Reputation:

func pad(input []byte, pad_count int) []byte {
    out := make([]byte, len(input) + int(pad_count))
    copy(out, input)
    for i := 0; i < pad_count; i++ {
        out[len(input) + i] = byte(pad_count)
    }
    return out
}

Upvotes: 0

Related Questions