More method functions for elliptic curves,
[openssl.git] / crypto / ec / ec.c
1 /*
2  *
3  *      ec.c
4  *
5  *      Elliptic Curve Arithmetic Functions
6  *
7  *      Copyright (C) Lenka Fibikova 2000
8  *
9  *
10  */
11
12
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <assert.h>
16
17 #include "ec2.h"
18
19
20
21 EC *EC_new()
22 {
23         EC *ret;
24
25         ret=(EC *)malloc(sizeof(EC));
26         if (ret == NULL) return NULL;
27         ret->A = BN_new();
28         ret->B = BN_new();
29         ret->p = BN_new();
30         ret->is_in_mont = 0;
31
32         if (ret->A == NULL || ret->B == NULL || ret->p == NULL)
33         {
34                 if (ret->A != NULL) BN_free(ret->A);
35                 if (ret->B != NULL) BN_free(ret->B);
36                 if (ret->p != NULL) BN_free(ret->p);
37                 free(ret);
38                 return(NULL);
39         }
40         return(ret);
41 }
42
43
44 void EC_clear_free(EC *E)
45 {
46         if (E == NULL) return;
47
48         if (E->A != NULL) BN_clear_free(E->A);
49         if (E->B != NULL) BN_clear_free(E->B);
50         if (E->p != NULL) BN_clear_free(E->p);
51         E->is_in_mont = 0;
52         free(E);
53 }
54
55
56 #ifdef MONTGOMERY
57 int EC_to_montgomery(EC *E, BN_MONTGOMERY *mont, BN_CTX *ctx)
58 {
59         assert(E != NULL);
60         assert(E->A != NULL && E->B != NULL && E->p != NULL);
61
62         assert(mont != NULL);
63         assert(mont->p != NULL);
64
65         assert(ctx != NULL);
66
67         if (E->is_in_mont) return 1;
68
69         if (!BN_lshift(E->A, E->A, mont->R_num_bits)) return 0;
70         if (!BN_mod(E->A, E->A, mont->p, ctx)) return 0;
71
72         if (!BN_lshift(E->B, E->B, mont->R_num_bits)) return 0;
73         if (!BN_mod(E->B, E->B, mont->p, ctx)) return 0;
74
75         E->is_in_mont = 1;
76         return 1;
77
78 }
79
80
81 int EC_from_montgomery(EC *E, BN_MONTGOMERY *mont, BN_CTX *ctx)
82 {
83         assert(E != NULL);
84         assert(E->A != NULL && E->B != NULL && E->p != NULL);
85
86         assert(mont != NULL);
87         assert(mont->p != NULL);
88
89         assert(ctx != NULL);
90
91         if (!E->is_in_mont) return 1;
92
93         if (!BN_mont_red(E->A, mont)) return 0;
94         if (!BN_mont_red(E->B, mont)) return 0;
95
96         E->is_in_mont = 0;
97         return 1;
98 }
99 #endif /* MONTGOMERY */