我一直在努力将ECDH实现到我的iOS项目中,并且在我的代码中有一个小的逻辑错误用于点乘法。从使用NIST列表示例测试(“Link”)我知道我的double方法和我的add方法正常工作(使用各种曲线测试)但不知何故我无法让实际的乘法算法工作。 这是乘法代码:
- (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];
}
这里点加法&点倍增加。
- (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];
}
我真的不知道在开始时如何处理Q点,也许这就是错误。
但无论如何,非常感谢你。 :)
安东