summaryrefslogtreecommitdiff
path: root/rw.cpp
blob: ab79358cba695d76b1d3b99bb8b5baf3e4cf793b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
// rw.cpp - originally written and placed in the public domain by Wei Dai

#include "pch.h"

#include "rw.h"
#include "asn.h"
#include "integer.h"
#include "nbtheory.h"
#include "modarith.h"
#include "asn.h"

#ifndef CRYPTOPP_IMPORTS

#if defined(_OPENMP)
# define CRYPTOPP_RW_USE_OMP 1
#else
# define CRYPTOPP_RW_USE_OMP 0
#endif

NAMESPACE_BEGIN(CryptoPP)

void RWFunction::BERDecode(BufferedTransformation &bt)
{
	BERSequenceDecoder seq(bt);
	m_n.BERDecode(seq);
	seq.MessageEnd();
}

void RWFunction::DEREncode(BufferedTransformation &bt) const
{
	DERSequenceEncoder seq(bt);
	m_n.DEREncode(seq);
	seq.MessageEnd();
}

Integer RWFunction::ApplyFunction(const Integer &in) const
{
	DoQuickSanityCheck();

	Integer out = in.Squared()%m_n;
	const word r = 12;
	// this code was written to handle both r = 6 and r = 12,
	// but now only r = 12 is used in P1363
	const word r2 = r/2;
	const word r3a = (16 + 5 - r) % 16;	// n%16 could be 5 or 13
	const word r3b = (16 + 13 - r) % 16;
	const word r4 = (8 + 5 - r/2) % 8;	// n%8 == 5
	switch (out % 16)
	{
	case r:
		break;
	case r2:
	case r2+8:
		out <<= 1;
		break;
	case r3a:
	case r3b:
		out.Negate();
		out += m_n;
		break;
	case r4:
	case r4+8:
		out.Negate();
		out += m_n;
		out <<= 1;
		break;
	default:
		out = Integer::Zero();
	}
	return out;
}

bool RWFunction::Validate(RandomNumberGenerator &rng, unsigned int level) const
{
	CRYPTOPP_UNUSED(rng), CRYPTOPP_UNUSED(level);
	bool pass = true;
	pass = pass && m_n > Integer::One() && m_n%8 == 5;
	CRYPTOPP_ASSERT(pass);
	return pass;
}

bool RWFunction::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
{
	return GetValueHelper(this, name, valueType, pValue).Assignable()
		CRYPTOPP_GET_FUNCTION_ENTRY(Modulus)
		;
}

void RWFunction::AssignFrom(const NameValuePairs &source)
{
	AssignFromHelper(this, source)
		CRYPTOPP_SET_FUNCTION_ENTRY(Modulus)
		;
}

// *****************************************************************************
// private key operations:

// generate a random private key
void InvertibleRWFunction::GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg)
{
	int modulusSize = 2048;
	alg.GetIntValue("ModulusSize", modulusSize) || alg.GetIntValue("KeySize", modulusSize);

	if (modulusSize < 16)
		throw InvalidArgument("InvertibleRWFunction: specified modulus length is too small");

	AlgorithmParameters primeParam = MakeParametersForTwoPrimesOfEqualSize(modulusSize);
	m_p.GenerateRandom(rng, CombinedNameValuePairs(primeParam, MakeParameters("EquivalentTo", 3)("Mod", 8)));
	m_q.GenerateRandom(rng, CombinedNameValuePairs(primeParam, MakeParameters("EquivalentTo", 7)("Mod", 8)));

	m_n = m_p * m_q;
	m_u = m_q.InverseMod(m_p);

	Precompute();
}

void InvertibleRWFunction::Initialize(const Integer &n, const Integer &p, const Integer &q, const Integer &u)
{
	m_n = n; m_p = p; m_q = q; m_u = u;

	Precompute();
}

void InvertibleRWFunction::PrecomputeTweakedRoots() const
{
	ModularArithmetic modp(m_p), modq(m_q);

	// GCC warning bug, https://stackoverflow.com/q/12842306/608639
#ifdef _OPENMP
	#pragma omp parallel sections if(CRYPTOPP_RW_USE_OMP)
	{
		#pragma omp section
			m_pre_2_9p = modp.Exponentiate(2, (9 * m_p - 11)/8);
		#pragma omp section
			m_pre_2_3q = modq.Exponentiate(2, (3 * m_q - 5)/8);
		#pragma omp section
			m_pre_q_p = modp.Exponentiate(m_q, m_p - 2);
	}
#else
	m_pre_2_9p = modp.Exponentiate(2, (9 * m_p - 11)/8);
	m_pre_2_3q = modq.Exponentiate(2, (3 * m_q - 5)/8);
	m_pre_q_p = modp.Exponentiate(m_q, m_p - 2);
#endif

	m_precompute = true;
}

void InvertibleRWFunction::LoadPrecomputation(BufferedTransformation &bt)
{
	BERSequenceDecoder seq(bt);
	m_pre_2_9p.BERDecode(seq);
	m_pre_2_3q.BERDecode(seq);
	m_pre_q_p.BERDecode(seq);
	seq.MessageEnd();

	m_precompute = true;
}

void InvertibleRWFunction::SavePrecomputation(BufferedTransformation &bt) const
{
	if(!m_precompute)
		Precompute();

	DERSequenceEncoder seq(bt);
	m_pre_2_9p.DEREncode(seq);
	m_pre_2_3q.DEREncode(seq);
	m_pre_q_p.DEREncode(seq);
	seq.MessageEnd();
}

void InvertibleRWFunction::BERDecode(BufferedTransformation &bt)
{
	BERSequenceDecoder seq(bt);
	m_n.BERDecode(seq);
	m_p.BERDecode(seq);
	m_q.BERDecode(seq);
	m_u.BERDecode(seq);
	seq.MessageEnd();

	m_precompute = false;
}

void InvertibleRWFunction::DEREncode(BufferedTransformation &bt) const
{
	DERSequenceEncoder seq(bt);
	m_n.DEREncode(seq);
	m_p.DEREncode(seq);
	m_q.DEREncode(seq);
	m_u.DEREncode(seq);
	seq.MessageEnd();
}

// DJB's "RSA signatures and Rabin-Williams signatures..." (http://cr.yp.to/sigs/rwsota-20080131.pdf).
Integer InvertibleRWFunction::CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const
{
	DoQuickSanityCheck();

	if(!m_precompute)
		Precompute();

	ModularArithmetic modn(m_n), modp(m_p), modq(m_q);
	Integer r, rInv;

	do
	{
		// Do this in a loop for people using small numbers for testing
		r.Randomize(rng, Integer::One(), m_n - Integer::One());
		// Fix for CVE-2015-2141. Thanks to Evgeny Sidorov for reporting.
		// Squaring to satisfy Jacobi requirements suggested by Jean-Pierre Munch.
		r = modn.Square(r);
		rInv = modn.MultiplicativeInverse(r);
	} while (rInv.IsZero());

	Integer re = modn.Square(r);
	re = modn.Multiply(re, x);    // blind

	const Integer &h = re, &p = m_p, &q = m_q;
	Integer e, f;

	const Integer U = modq.Exponentiate(h, (q+1)/8);
	if(((modq.Exponentiate(U, 4) - h) % q).IsZero())
		e = Integer::One();
	else
		e = -1;

	const Integer eh = e*h, V = modp.Exponentiate(eh, (p-3)/8);
	if(((modp.Multiply(modp.Exponentiate(V, 4), modp.Exponentiate(eh, 2)) - eh) % p).IsZero())
		f = Integer::One();
	else
		f = 2;

#ifdef _OPENMP
	Integer W, X;
	#pragma omp parallel sections if(CRYPTOPP_RW_USE_OMP)
	{
		#pragma omp section
		{
			W = (f.IsUnit() ? U : modq.Multiply(m_pre_2_3q, U));
		}
		#pragma omp section
		{
			const Integer t = modp.Multiply(modp.Exponentiate(V, 3), eh);
			X = (f.IsUnit() ? t : modp.Multiply(m_pre_2_9p, t));
		}
	}
#else
	const Integer W = (f.IsUnit() ? U : modq.Multiply(m_pre_2_3q, U));
	const Integer t = modp.Multiply(modp.Exponentiate(V, 3), eh);
	const Integer X = (f.IsUnit() ? t : modp.Multiply(m_pre_2_9p, t));
#endif

	const Integer Y = W + q * modp.Multiply(m_pre_q_p, (X - W));

	// Signature
	Integer s = modn.Multiply(modn.Square(Y), rInv);
	CRYPTOPP_ASSERT((e * f * s.Squared()) % m_n == x);

	// IEEE P1363, Section 8.2.8 IFSP-RW, p.44
	s = STDMIN(s, m_n - s);
	if (ApplyFunction(s) != x)                      // check
		throw Exception(Exception::OTHER_ERROR, "InvertibleRWFunction: computational error during private key operation");

	return s;
}

bool InvertibleRWFunction::Validate(RandomNumberGenerator &rng, unsigned int level) const
{
	bool pass = RWFunction::Validate(rng, level);
	CRYPTOPP_ASSERT(pass);
	pass = pass && m_p > Integer::One() && m_p%8 == 3 && m_p < m_n;
	CRYPTOPP_ASSERT(pass);
	pass = pass && m_q > Integer::One() && m_q%8 == 7 && m_q < m_n;
	CRYPTOPP_ASSERT(pass);
	pass = pass && m_u.IsPositive() && m_u < m_p;
	CRYPTOPP_ASSERT(pass);
	if (level >= 1)
	{
		pass = pass && m_p * m_q == m_n;
		CRYPTOPP_ASSERT(pass);
		pass = pass && m_u * m_q % m_p == 1;
		CRYPTOPP_ASSERT(pass);
	}
	if (level >= 2)
	{
		pass = pass && VerifyPrime(rng, m_p, level-2) && VerifyPrime(rng, m_q, level-2);
		CRYPTOPP_ASSERT(pass);
	}
	return pass;
}

bool InvertibleRWFunction::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
{
	return GetValueHelper<RWFunction>(this, name, valueType, pValue).Assignable()
		CRYPTOPP_GET_FUNCTION_ENTRY(Prime1)
		CRYPTOPP_GET_FUNCTION_ENTRY(Prime2)
		CRYPTOPP_GET_FUNCTION_ENTRY(MultiplicativeInverseOfPrime2ModPrime1)
		;
}

void InvertibleRWFunction::AssignFrom(const NameValuePairs &source)
{
	AssignFromHelper<RWFunction>(this, source)
		CRYPTOPP_SET_FUNCTION_ENTRY(Prime1)
		CRYPTOPP_SET_FUNCTION_ENTRY(Prime2)
		CRYPTOPP_SET_FUNCTION_ENTRY(MultiplicativeInverseOfPrime2ModPrime1)
		;

	m_precompute = false;
}

NAMESPACE_END

#endif