1 --- libtorrent-0.12.2.orig/src/utils/diffie_hellman.cc Wed May 7 12:19:12 2008 |
|
2 +++ libtorrent-0.12.2/src/utils/diffie_hellman.cc Sun Jun 15 10:51:31 2008 |
|
3 @@ -47,6 +47,80 @@ |
|
4 |
|
5 namespace torrent { |
|
6 |
|
7 +static int generate_key(DH *dh) |
|
8 + { |
|
9 + int ok=0; |
|
10 + int generate_new_key=0; |
|
11 + unsigned l; |
|
12 + BN_CTX *ctx; |
|
13 + BN_MONT_CTX *mont=NULL; |
|
14 + BIGNUM *pub_key=NULL,*priv_key=NULL; |
|
15 + |
|
16 + ctx = BN_CTX_new(); |
|
17 + if (ctx == NULL) goto err; |
|
18 + |
|
19 + if (dh->priv_key == NULL) |
|
20 + { |
|
21 + priv_key=BN_new(); |
|
22 + if (priv_key == NULL) goto err; |
|
23 + generate_new_key=1; |
|
24 + } |
|
25 + else |
|
26 + priv_key=dh->priv_key; |
|
27 + |
|
28 + if (dh->pub_key == NULL) |
|
29 + { |
|
30 + pub_key=BN_new(); |
|
31 + if (pub_key == NULL) goto err; |
|
32 + } |
|
33 + else |
|
34 + pub_key=dh->pub_key; |
|
35 + |
|
36 + |
|
37 + if (dh->flags & DH_FLAG_CACHE_MONT_P) |
|
38 + { |
|
39 + mont = BN_MONT_CTX_set_locked((BN_MONT_CTX **)(&dh->method_mont_p), |
|
40 + CRYPTO_LOCK_DH, dh->p, ctx); |
|
41 + if (!mont) |
|
42 + goto err; |
|
43 + } |
|
44 + |
|
45 + if (generate_new_key) |
|
46 + { |
|
47 + l = dh->length ? dh->length : BN_num_bits(dh->p)-1; /* secret exponent length */ |
|
48 + if (!BN_rand(priv_key, l, 0, 0)) |
|
49 + if (!BN_pseudo_rand(priv_key, l, 0, 0)) goto err; |
|
50 + } |
|
51 + |
|
52 + { |
|
53 + BIGNUM local_prk; |
|
54 + BIGNUM *prk; |
|
55 + |
|
56 + if ((dh->flags & DH_FLAG_NO_EXP_CONSTTIME) == 0) |
|
57 + { |
|
58 + BN_init(&local_prk); |
|
59 + prk = &local_prk; |
|
60 + BN_with_flags(prk, priv_key, BN_FLG_EXP_CONSTTIME); |
|
61 + } |
|
62 + else |
|
63 + prk = priv_key; |
|
64 + |
|
65 + if (!dh->meth->bn_mod_exp(dh, pub_key, dh->g, prk, dh->p, ctx, mont)) goto err; |
|
66 + } |
|
67 + |
|
68 + dh->pub_key=pub_key; |
|
69 + dh->priv_key=priv_key; |
|
70 + ok=1; |
|
71 +err: |
|
72 + if (ok != 1) { |
|
73 + } |
|
74 + |
|
75 + if ((pub_key != NULL) && (dh->pub_key == NULL)) BN_free(pub_key); |
|
76 + if ((priv_key != NULL) && (dh->priv_key == NULL)) BN_free(priv_key); |
|
77 + BN_CTX_free(ctx); |
|
78 + return(ok); |
|
79 +} |
|
80 + |
|
81 DiffieHellman::DiffieHellman(const unsigned char *prime, int primeLength, |
|
82 const unsigned char *generator, int generatorLength) : |
|
83 m_secret(NULL) { |
|
84 @@ -56,7 +130,8 @@ |
|
85 m_dh->p = BN_bin2bn(prime, primeLength, NULL); |
|
86 m_dh->g = BN_bin2bn(generator, generatorLength, NULL); |
|
87 |
|
88 - DH_generate_key(m_dh); |
|
89 + if (!generate_key(m_dh)) |
|
90 + throw internal_error("Unable to generate encryption key."); |
|
91 #else |
|
92 throw internal_error("Compiled without encryption support."); |
|
93 #endif |
|