I've been working on implementing ECDH into my iOS project and have a small logic bug in my code for the point multiplication. From testing with the NIST List examples ("Link") I know that my double method and my add method is working correctly (tested with a various of curves) but somehow I can't get the actually multiplication algorithm to work. Here is the multiplication code:
- (NSArray *)multiplyPX:(BigInteger *)P_X PY:(BigInteger *)P_Y andD:(BigInteger *)D
{
BigInteger *ZERO = [[BigInteger alloc] initWithInt32:0];
BigInteger *curveA = [[BigInteger alloc] initWithString:@"ffffffff00000001000000000000000000000000fffffffffffffffffffffffc" radix:16];
//Getting the binary representation of the D value
NSString *dBinary = [D toRadix:2];
//Creating new Point Q = 0;
BigInteger *Qx = ZERO;
BigInteger *Qy = ZERO;
//For every binary digit in D do "point doubling" & if dBinary[i] == 1 do "point addition"
for (int i = [dBinary length]-1; i >= 0; i++) {
//Check that you don't divide by 0
if (![Qy isEqual:ZERO]) {
//Point Doubling
NSArray *arr = [self pointDoublingWithXp:Qx andYp:Qy andA:curveA];
Qx = [arr objectAtIndex:0];
Qy = [arr objectAtIndex:1];
}
//If dBinary[i] == 1
if ([dBinary characterAtIndex:i] == 49) {
//Point Addition
NSArray *arr = [self pointAdditionWithXp:P_X andYp:P_Y andXq:Qx andYq:Qy];
Qx = [arr objectAtIndex:0];
Qy = [arr objectAtIndex:1];
}
}
return [[NSArray alloc] initWithObjects:Qx, Qy, nil];
}
And here the point addition & point doubling.
- (NSArray *)pointAdditionWithXp:(BigInteger *)xp andYp:(BigInteger *)yp andXq:(BigInteger *)xq andYq:(BigInteger *)yq
{
BigInteger *ONE = [[BigInteger alloc] initWithInt32:1];
BigInteger *TWO = [[BigInteger alloc] initWithInt32:2];
BigInteger *slope = [[yq sub:yp] multiply:[[xq sub:xp] inverseModulo:p] modulo:p];
BigInteger *xout = [[[[slope exp:TWO modulo:p] sub:xq] sub:xp] multiply:ONE modulo:p];
BigInteger *yout = [[yp negate] multiply:ONE modulo:p];
yout = [yout add:[slope multiply:[xp sub:xout] modulo:p]];
return [[NSArray alloc] initWithObjects:xout, yout, nil];
}
- (NSArray *)pointDoublingWithXp:(BigInteger *)xp andYp:(BigInteger *)yp andA:(BigInteger *)a
{
BigInteger *ONE = [[BigInteger alloc] initWithInt32:1];
BigInteger *TWO = [[BigInteger alloc] initWithInt32:2];
BigInteger *THREE = [[BigInteger alloc] initWithInt32:3];
BigInteger *slope = [[[[xp multiply:xp] multiply:THREE] add:a] multiply:[[yp multiply:TWO] inverseModulo:p]];
BigInteger *xout = [[[slope multiply:slope] sub:[xp multiply:TWO]] multiply:ONE modulo:p];
BigInteger *yout = [[[yp negate] add:[slope multiply:[xp sub:xout]]] multiply:ONE modulo:p];
return [[NSArray alloc] initWithObjects:xout, yout, nil];
}
I don't really know what to do with the point Q at the beginning, maybe that's the bug.
But anyways, thank you very much. :)
Anton