encodeinttest.c (1643B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 #include <stdio.h> 6 7 #include "secasn1.h" 8 9 struct TestCase { 10 long value; 11 unsigned char data[5]; 12 unsigned int len; 13 }; 14 15 static struct TestCase testCase[] = { 16 /* XXX NSS doesn't generate the shortest encoding for negative values. */ 17 #if 0 18 { -128, { 0x80 }, 1 }, 19 { -129, { 0xFF, 0x7F }, 2 }, 20 #endif 21 22 { 0, { 0x00 }, 1 }, 23 { 127, { 0x7F }, 1 }, 24 { 128, { 0x00, 0x80 }, 2 }, 25 { 256, { 0x01, 0x00 }, 2 }, 26 { 32768, { 0x00, 0x80, 0x00 }, 3 } 27 }; 28 29 int 30 main() 31 { 32 PRBool failed = PR_FALSE; 33 unsigned int i; 34 unsigned int j; 35 36 for (i = 0; i < sizeof(testCase) / sizeof(testCase[0]); i++) { 37 SECItem encoded; 38 if (SEC_ASN1EncodeInteger(NULL, &encoded, testCase[i].value) == NULL) { 39 fprintf(stderr, "SEC_ASN1EncodeInteger failed\n"); 40 failed = PR_TRUE; 41 continue; 42 } 43 if (encoded.len != testCase[i].len || 44 memcmp(encoded.data, testCase[i].data, encoded.len) != 0) { 45 fprintf(stderr, "Encoding of %ld is incorrect:", 46 testCase[i].value); 47 for (j = 0; j < encoded.len; j++) { 48 fprintf(stderr, " 0x%02X", (unsigned int)encoded.data[j]); 49 } 50 fputs("\n", stderr); 51 failed = PR_TRUE; 52 } 53 PORT_Free(encoded.data); 54 } 55 56 if (failed) { 57 fprintf(stderr, "FAIL\n"); 58 return 1; 59 } 60 printf("PASS\n"); 61 return 0; 62 }