Hello,

It looks like the functions asn1_encode_integer() and
sc_asn1_decode_integer() from src/libopensc/asn1.c are not correct.

For example the integer 128 is encoded 0x80 but should be encoded 0x00
0x80. 0x80 is the encoding of -128
-128 is encoded FF FF FF 80 but I don't know if that is a valid coding.

I am not expert in ASN.1 so am not sure it is a bug.
I found ASN.1 encoding examples in [1]:
##
## INTEGER (tests 13 - 21)
##

my %INTEGER = (
  pack("C*", 0x02, 0x02, 0x00, 0x80),         128,
  pack("C*", 0x02, 0x01, 0x80),               -128,
  pack("C*", 0x02, 0x02, 0xff, 0x01),         -255,
  pack("C*", 0x02, 0x01, 0x00),               0,
  pack("C*", 0x02, 0x03, 0x66, 0x77, 0x99),   0x667799,
  pack("C*", 0x02, 0x02, 0xFE, 0x37),        -457,
  pack("C*", 0x02, 0x04, 0x40, 0x00, 0x00, 0x00),            2**30,
  pack("C*", 0x02, 0x04, 0xC0, 0x00, 0x00, 0x00),            -2**30,
);


I propose the attached patch for asn1_encode_integer().
sc_asn1_decode_integer() should also be patched.

Do we have ASN.1 experts on this list?

bye

[1] http://search.cpan.org/src/GBARR/Convert-ASN1-0.21/t/00prim.t

-- 
 Dr. Ludovic Rousseau
Index: src/libopensc/asn1.c
===================================================================
--- src/libopensc/asn1.c        (révision 3386)
+++ src/libopensc/asn1.c        (copie de travail)
@@ -546,7 +546,7 @@ static int asn1_encode_integer(int in, u
        int i = sizeof(in) * 8, skip = 1;
        u8 *p, b;
 
-       *obj = p = (u8 *) malloc(sizeof(in));
+       *obj = p = (u8 *) malloc(sizeof(in)+1);
        if (*obj == NULL)
                return SC_ERROR_OUT_OF_MEMORY;
        do {
@@ -554,7 +554,12 @@ static int asn1_encode_integer(int in, u
                b = in >> i;
                if (b == 0 && skip)
                        continue;
-               skip = 0;
+               if (skip) {
+                       skip = 0;
+                       /* prepend 00 if MSb is 1 and integer positive */
+                       if ((b & 0x80) != 0 && in > 0)
+                               *p++ = 0;
+               }
                *p++ = b;
        } while (i > 0);
        *objsize = p - *obj;
_______________________________________________
opensc-devel mailing list
opensc-devel@lists.opensc-project.org
http://www.opensc-project.org/mailman/listinfo/opensc-devel

Reply via email to