| 1 | package x509tools |
| 2 | |
| 3 | import ( |
| 4 | "math/big" |
| 5 | "testing" |
| 6 | |
| 7 | "github.com/stretchr/testify/assert" |
| 8 | "github.com/stretchr/testify/require" |
| 9 | ) |
| 10 | |
| 11 | func TestUnpack(t *testing.T) { |
| 12 | packed := []byte{1, 0, 2, 0} |
| 13 | sig, err := UnpackEcdsaSignature(packed) |
| 14 | require.NoError(t, err) |
| 15 | assert.Equal(t, int64(256), sig.R.Int64()) |
| 16 | assert.Equal(t, int64(512), sig.S.Int64()) |
| 17 | invalid := []byte{1, 2, 3} |
| 18 | _, err = UnpackEcdsaSignature(invalid) |
| 19 | require.Error(t, err) |
| 20 | } |
| 21 | |
| 22 | func TestUnmarshal(t *testing.T) { |
| 23 | packed := []byte{0x30, 0x8, 0x2, 0x2, 0x2, 0x0, 0x2, 0x2, 0x0, 0xff} |
| 24 | sig, err := UnmarshalEcdsaSignature(packed) |
| 25 | require.NoError(t, err) |
| 26 | assert.Equal(t, int64(512), sig.R.Int64()) |
| 27 | assert.Equal(t, int64(255), sig.S.Int64()) |
| 28 | invalid := []byte{1, 2, 3} |
| 29 | _, err = UnmarshalEcdsaSignature(invalid) |
| 30 | require.Error(t, err) |
| 31 | } |
| 32 | |
| 33 | func TestMarshal(t *testing.T) { |
| 34 | sig := EcdsaSignature{ |
| 35 | R: big.NewInt(512), |
| 36 | S: big.NewInt(255), |
| 37 | } |
| 38 | assert.Equal(t, []byte{0x30, 0x8, 0x2, 0x2, 0x2, 0x0, 0x2, 0x2, 0x0, 0xff}, sig.Marshal()) |
| 39 | |
| 40 | // test both ways around to ensure it's padded correctly |
| 41 | assert.Equal(t, []byte{2, 0, 0, 255}, sig.Pack()) |
| 42 | sig.R, sig.S = sig.S, sig.R |
| 43 | assert.Equal(t, []byte{0, 255, 2, 0}, sig.Pack()) |
| 44 | } |