C Elliptic Curve 25519 Implementation

C Elliptic Curve 25519 Implementation

This is a very portable and simplistic implementation of the elliptic curve 25519 created by Daniel Bernstein (djb).

Check full code and live execution here: https://ramiroblan.co/curve25519.html

phobos:/opt/TOR/tor-c-client# ./bin_mult


Alice private:	0x5dfefb5b4be518af291b31ee28f12b5b4680db68cf11bb4fb28030282037a5d8
? Bob private:	0x789b89f5730b6a86433a954236aef04b64a8d6dba05f986d811e04db0b7730a8




Alice public:	0x27df9c68d5f61fd5d71cb1b57e102874975dd8f85539264308cf5f687eccf973
? Bob public:	0x658aceb11dd9bc84ea18a2f4ba84a9521b7b97ff0b0df51f2bad3b8fe0a718bb




Alice y value:	0x66cdc96a4a4d237479b85005e5f1cdea675231070381a740de1daf826ade0338
? Bob x value:	0x514a6cf535fe3f46722e5af1e1d1c687e6e55493fb5e4f9ff01400923f37beb8




Alice shared:	0x730015537704b444c46f0d76ebf8c6dd57f7104faa328945c94a7656378e5d4b
? Bob shared:	0x730015537704b444c46f0d76ebf8c6dd57f7104faa328945c94a7656378e5d4b

?        

Curve25519 is the elliptic curve of Montgomery form:

y^2=x^2+486662x^2+x        

Numbers are built using 32 bits unsigned int arrays which simplifies arithmetic operations and works well using two's complement:

#define P_VALUE [ 0 ... MAXELSZEROBASED - 8 ] = 0x0, 0x7FFFFFFF, 
						? ? ?0xFFFFFFFF, \
						? ? ?0xFFFFFFFF, \
						? ? ?0xFFFFFFFF, \
						? ? ?0xFFFFFFFF, \
						? ? ?0xFFFFFFFF, \
						? ? ?0xFFFFFFFF, \
						? ? ?0xFFFFFFED
#define P2_VALUE [ 0 ... MAXELSZEROBASED - 8 ] = 0x0, 0x7FFFFFFF, \
						? ? ? 0xFFFFFFFF, \
						? ? ? 0xFFFFFFFF, \
						? ? ? 0xFFFFFFFF, \
						? ? ? 0xFFFFFFFF, \
						? ? ? 0xFFFFFFFF, \
						? ? ? 0xFFFFFFFF, \
						? ? ? 0xFFFFFFEB
#define N_VALUE [ 0 ... MAXELSZEROBASED - 10 ] = 0x0, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4C, 0x0\        

Multiplication operation:

void rgb_mult_64(rgbnum r, rgbnum a, rgbnum b)
{
? ? ? ? int i, j, m, k = 0;
? ? ? ? uint64_t l, c = 0;

? ? ? ? rgb_init_to_0(r);

? ? ? ? for(i = MAXELSZEROBASED; i >= 0; --i)
? ? ? ? {
? ? ? ? ? ? ? ? for(j = MAXELSZEROBASED; j >= k; --j)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? m = j-k;
? ? ? ? ? ? ? ? ? ? ? ? l = (uint64_t)b[i] * a[j] + c + r[m];
? ? ? ? ? ? ? ? ? ? ? ? r[m] = l;
? ? ? ? ? ? ? ? ? ? ? ? c = l >> MAXBITS;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? c = 0;
? ? ? ? ? ? ? ? ++k;
? ? ? ? }
}        

Modulo operation using fixed point multiplication:

void rgb_ring(rgbnum r, rgbnum a, rgbnum b)
{
	int i;
	rgbnum aux, aux_N;


	rgb_init_to_0(r);


	if(a[0] & MSB1) rgb_to_negative(aux, a);
	else rgb_cp_64(a, aux);


	if(!rgb_is_smaller(aux, b))
	{
		rgb_mult_64(aux_N, aux, N);
		rgb_init_to_0(aux);
		for(i = 0; i < MAXELS - N_SHIFT; ++i) aux[i+N_SHIFT] = aux_N[i];


		rgb_mult_64(r, aux, b);
		rgb_sub_64(aux, a, r);

	}
	
	if(a[0] & MSB1)
	{
		rgb_sub_64(r, b, aux);
	}
	else rgb_cp_64(aux, r);

}        

要查看或添加评论,请登录

Ramiro Blanco的更多文章

社区洞察

其他会员也浏览了