Merge pull request #84 from apache/oct-fixes
make comp CT and check octet max len in toHex
diff --git a/include/amcl.h.in b/include/amcl.h.in
index f588c0a..ea9175c 100644
--- a/include/amcl.h.in
+++ b/include/amcl.h.in
@@ -232,6 +232,7 @@
extern void OCT_clear(octet *O);
/** @brief Compare two octets
*
+ Terminates early if O.len != P.len
@param O first Octet to be compared
@param P second Octet to be compared
@return 1 if equal, else 0
@@ -239,6 +240,7 @@
extern int OCT_comp(octet *O,octet *P);
/** @brief Compare first n bytes of two octets
*
+ Terminates early if O.len > n or P.len > n
@param O first Octet to be compared
@param P second Octet to be compared
@param n number of bytes to compare
@@ -362,6 +364,7 @@
extern void OCT_fromHex(octet *dst,char *src);
/** @brief Convert an Octet to printable hex number
*
+ Truncates if there is no room
@param dst hex value
@param src Octet to be converted
*/
diff --git a/src/oct.c b/src/oct.c
index e768dca..4362a98 100644
--- a/src/oct.c
+++ b/src/oct.c
@@ -73,28 +73,42 @@
int OCT_comp(octet *x,octet *y)
{
int i;
+ byte res = 0;
- if (x->len>y->len) return 0;
- if (x->len<y->len) return 0;
+ if (x->len != y->len) return 0;
for (i=0; i<x->len; i++)
{
- if (x->val[i]!=y->val[i]) return 0;
+ res |= (x->val[i] ^ y->val[i]);
}
- return 1;
+
+ // Condense result to one bit
+ res = ~res;
+ res &= res >> 4;
+ res &= res >> 2;
+ res &= res >> 1;
+
+ return (int)res;
}
/* check are first n bytes the same (in constant time) */
int OCT_ncomp(octet *x,octet *y,int n)
{
- int i,res=0;
+ int i;
+ byte res = 0;
if (n>y->len || n>x->len) return 0;
for (i=0; i<n; i++)
{
- res|=(int)(x->val[i]^y->val[i]);
+ res |= (x->val[i] ^ y->val[i]);
}
- if (res==0) return 1;
- return 0;
+
+ // Condense result to one bit
+ res = ~res;
+ res &= res >> 4;
+ res &= res >> 2;
+ res &= res >> 1;
+
+ return (int)res;
}
/* Shift octet to the left by n bytes. Leftmost bytes disappear */
@@ -268,6 +282,8 @@
{
int i,j,k,pads,len=(int)strlen(b);
int c,ch[4],ptr[3];
+ OCT_clear(w);
+
j=k=0;
while (j<len && k<w->max)
{
@@ -382,9 +398,10 @@
{
int i=0;
int j=0;
+ int len = (int)strlen(src);
OCT_clear(dst);
- while(src[j]!=0)
+ while(j < len && i < dst->max)
{
dst->val[i++] = char2int(src[j])*16 + char2int(src[j+1]);
j += 2;
diff --git a/test/test_octet_consistency.c b/test/test_octet_consistency.c
index 19ad0d4..7c02742 100644
--- a/test/test_octet_consistency.c
+++ b/test/test_octet_consistency.c
@@ -59,7 +59,7 @@
{
if(!OCT_ncomp(&V,&W,i))
{
- printf("ERROR comparing two equal octet, OCTET\n");
+ printf("ERROR comparing %d bytes out of two equal octet, OCTET\n", i);
exit(EXIT_FAILURE);
}
}
@@ -69,6 +69,11 @@
printf("ERROR comparing two different octet, OCTET\n");
exit(EXIT_FAILURE);
}
+ if(OCT_ncomp(&V,&W,len))
+ {
+ printf("ERROR comparing %d bytes out of two different octet, OCTET\n", len);
+ exit(EXIT_FAILURE);
+ }
}
OCT_rand(&W,&rng,0);
OCT_copy(&V,&W);