1// Copyright 2017 The Go Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5package encoding 6 7import ( 8 "bytes" 9 "io" 10 "testing" 11) 12 13var mpiTests = []struct { 14 encoded []byte 15 bytes []byte 16 reencoded []byte 17 bitLength uint16 18 err error 19}{ 20 { 21 encoded: []byte{0x0, 0x0}, 22 bytes: []byte{}, 23 bitLength: 0, 24 }, 25 { 26 encoded: []byte{0x0, 0x1, 0x1}, 27 bytes: []byte{0x1}, 28 bitLength: 1, 29 }, 30 { 31 encoded: []byte{0x0, 0x9, 0x1, 0xff}, 32 bytes: []byte{0x1, 0xff}, 33 bitLength: 9, 34 }, 35 { 36 encoded: append([]byte{0x1, 0x0, 0xff}, make([]byte, 0x1f)...), 37 bytes: append([]byte{0xff}, make([]byte, 0x1f)...), 38 bitLength: 0x100, 39 }, 40 // https://bugs.gnupg.org/gnupg/issue1853 41 { 42 encoded: []byte{0x0, 0x10, 0x0, 0x1}, 43 bytes: []byte{0x0, 0x1}, 44 reencoded: []byte{0x0, 0x1, 0x1}, 45 bitLength: 0x10, 46 }, 47 // EOF error, 48 { 49 encoded: []byte{}, 50 err: io.ErrUnexpectedEOF, 51 }, 52 { 53 encoded: []byte{0x1, 0x0, 0x0}, 54 err: io.ErrUnexpectedEOF, 55 }, 56} 57 58func TestMPI(t *testing.T) { 59 for i, test := range mpiTests { 60 mpi := new(MPI) 61 if _, err := mpi.ReadFrom(bytes.NewBuffer(test.encoded)); err != nil { 62 if !sameError(err, test.err) { 63 t.Errorf("#%d: ReadFrom error got:%q", i, err) 64 } 65 continue 66 } 67 if b := mpi.Bytes(); !bytes.Equal(b, test.bytes) { 68 t.Errorf("#%d: bad creation got:%x want:%x", i, b, test.bytes) 69 } 70 if bl := mpi.BitLength(); bl != test.bitLength { 71 t.Errorf("#%d: bad BitLength got:%d want:%d", i, bl, test.bitLength) 72 } 73 74 reencoded := test.encoded 75 if test.reencoded != nil { 76 reencoded = test.reencoded 77 } 78 79 if b := mpi.EncodedBytes(); !bytes.Equal(b, test.encoded) { 80 t.Errorf("#%d: bad encoding got:%x want:%x", i, b, test.encoded) 81 } 82 if b := NewMPI(mpi.Bytes()).EncodedBytes(); !bytes.Equal(b, reencoded) { 83 t.Errorf("#%d: bad encoding got:%x want:%x", i, b, reencoded) 84 } 85 } 86} 87