Skip to content

Commit

Permalink
Remove redundant check length check
Browse files Browse the repository at this point in the history
Add tests to cover all length check cases
  • Loading branch information
Cravtos committed May 23, 2024
1 parent b9b61df commit b7da01d
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 13 deletions.
15 changes: 6 additions & 9 deletions ber.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,12 @@ func lengthLength(i int) (numBytes int) {
// added to 0x80. The length is encoded in big endian encoding follow after
//
// Examples:
// length | byte 1 | bytes n
// 0 | 0x00 | -
// 120 | 0x78 | -
// 200 | 0x81 | 0xC8
// 500 | 0x82 | 0x01 0xF4
//
// length | byte 1 | bytes n
// 0 | 0x00 | -
// 120 | 0x78 | -
// 200 | 0x81 | 0xC8
// 500 | 0x82 | 0x01 0xF4
func encodeLength(out *bytes.Buffer, length int) (err error) {
if length >= 128 {
l := lengthLength(length)
Expand All @@ -134,9 +134,6 @@ func encodeLength(out *bytes.Buffer, length int) (err error) {

func readObject(ber []byte, offset int) (asn1Object, int, error) {
berLen := len(ber)
if offset >= berLen {
return nil, 0, errors.New("ber2der: offset is after end of ber data")
}
tagStart := offset
b := ber[offset]
offset++
Expand Down Expand Up @@ -259,7 +256,7 @@ func readObject(ber []byte, offset int) (asn1Object, int, error) {
}

func isIndefiniteTermination(ber []byte, offset int) (bool, error) {
if len(ber) - offset < 2 {
if len(ber)-offset < 2 {
return false, errors.New("ber2der: Invalid BER format")
}

Expand Down
10 changes: 6 additions & 4 deletions ber_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,16 @@ func TestBer2Der_Negatives(t *testing.T) {
Input []byte
ErrorContains string
}{
{[]byte{0x30, 0x85}, "end of ber data reached"},
{[]byte{0x1f, 0x0}, "end of ber data reached"},
{[]byte{0x30, 0x85, 0x1}, "tag length too long"},
{[]byte{0x30, 0x84, 0x80, 0x0, 0x0, 0x0}, "length is negative"},
{[]byte{0x30, 0x82, 0x0, 0x1}, "length has leading zero"},
{[]byte{0x30, 0x81, 0x01}, "end of ber data reached"},
{[]byte{0x30, 0x80, 0x1, 0x2, 0x1, 0x2}, "Invalid BER format"},
{[]byte{0x30, 0x80, 0x1, 0x2}, "end of ber data reached"},
{[]byte{0x30, 0x03, 0x01, 0x02}, "length is more than available data"},
{[]byte{0x30, 0x80, 0x1, 0x2, 0x1}, "BER tag length is more than available data"},
{[]byte{0x1f, 0x80}, "end of ber data reached"},
{[]byte{0x30, 0x80}, "end of ber data reached"},
{[]byte{0x30}, "end of ber data reached"},
{[]byte("0 0 0 0 0 0 0 0\x020\x020\x020\x020\x020\x020\x020\x020\x020\x020\x020\x020\x020\x020\x02\x1f0"), "end of ber data reached"},
}

for _, fixture := range fixtures {
Expand Down

0 comments on commit b7da01d

Please sign in to comment.