diff --git a/cryptobyte/asn1.go b/cryptobyte/asn1.go index f930f7e..b26376a 100644 --- a/cryptobyte/asn1.go +++ b/cryptobyte/asn1.go @@ -81,7 +81,7 @@ func (b *Builder) AddASN1BigInt(n *big.Int) { for i := range bytes { bytes[i] ^= 0xff } - if bytes[0]&0x80 == 0 { + if len(bytes) == 0 || bytes[0]&0x80 == 0 { c.add(0xff) } c.add(bytes...) diff --git a/cryptobyte/asn1_test.go b/cryptobyte/asn1_test.go index f6bb96d..74ffc06 100644 --- a/cryptobyte/asn1_test.go +++ b/cryptobyte/asn1_test.go @@ -335,3 +335,19 @@ func TestReadASN1BitString(t *testing.T) { } } } + +func TestAddASN1BigInt(t *testing.T) { + x := big.NewInt(-1) + var b Builder + b.AddASN1BigInt(x) + got, err := b.Bytes() + if err != nil { + t.Fatalf("unexpected error adding -1: %v", err) + } + s := String(got) + var y big.Int + ok := s.ReadASN1Integer(&y) + if !ok || x.Cmp(&y) != 0 { + t.Errorf("unexpected bytes %v, want %v", &y, x) + } +}