forked from ceceradio/GranadosRT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RSA.cs
326 lines (276 loc) · 8.32 KB
/
RSA.cs
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
315
316
317
318
319
320
321
322
323
324
325
326
/* ---------------------------------------------------------------------------
*
* Copyright (c) Routrek Networks, Inc. All Rights Reserved..
*
* This file is a part of the Granados SSH Client Library that is subject to
* the license included in the distributed package.
* You may not use this file except in compliance with the license.
*
* ---------------------------------------------------------------------------
* I implemented this algorithm with reference to following products and books though the algorithm is known publicly.
* * MindTerm ( AppGate Network Security )
* * Applied Cryptography ( Bruce Schneier )
*/
using System;
using System.Diagnostics;
//using System.Security.Cryptography;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using System.Runtime.InteropServices.WindowsRuntime;
using GranadosRT.Routrek.SSHC;
namespace GranadosRT.Routrek.PKI
{
internal class RSAKeyPair : KeyPair, ISigner, IVerifier {
private RSAPublicKey _publickey;
private BigInteger _d;
private BigInteger _u;
private BigInteger _p;
private BigInteger _q;
internal RSAKeyPair(BigInteger modulus, BigInteger e, BigInteger d, BigInteger p, BigInteger q)
{
_publickey = new RSAPublicKey(e, modulus);
_d = d;
_p = p;
_q = q;
_u = p.modInverse(q);
}
internal RSAKeyPair(BigInteger e, BigInteger d, BigInteger n, BigInteger u, BigInteger p, BigInteger q)
{
_publickey = new RSAPublicKey(e, n);
_d = d;
_u = u;
_p = p;
_q = q;
}
public BigInteger D {
get {
return _d;
}
}
public BigInteger U {
get {
return _u;
}
}
public BigInteger P {
get {
return _p;
}
}
public BigInteger Q {
get {
return _q;
}
}
public PublicKeyAlgorithm Algorithm
{
get {
return PublicKeyAlgorithm.RSA;
}
}
public byte[] Sign([ReadOnlyArray()] byte[] data) {
BigInteger pe = PrimeExponent(_d, _p);
BigInteger qe = PrimeExponent(_d, _q);
BigInteger result = SignCore(new BigInteger(data), pe, qe);
return result.getBytes();
}
public void Verify([ReadOnlyArray()] byte[] data, [WriteOnlyArray()] byte[] expected) {
_publickey.Verify(data, expected);
}
public byte[] SignWithSHA1([ReadOnlyArray()] byte[] data) {
byte[] hash = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1).HashData(data.AsBuffer()).ToArray();
byte[] buf = new byte[hash.Length + PKIUtil.SHA1_ASN_ID.Length];
Array.Copy(PKIUtil.SHA1_ASN_ID, 0, buf, 0, PKIUtil.SHA1_ASN_ID.Length);
Array.Copy(hash, 0, buf, PKIUtil.SHA1_ASN_ID.Length, hash.Length);
BigInteger x = new BigInteger(buf);
//Debug.WriteLine(x.ToHexString());
int padLen = (_publickey._n.bitCount() + 7) / 8;
x = RSAUtil.PKCS1PadType1(x, padLen);
byte[] result = Sign(x.getBytes());
return result;
}
private BigInteger SignCore(BigInteger input, BigInteger pe, BigInteger qe) {
BigInteger p2 = (input % _p).modPow(pe, _p);
BigInteger q2 = (input % _q).modPow(qe, _q);
if(p2==q2)
return p2;
BigInteger k = (q2-p2) % _q;
if(k.IsNegative) k += _q; //in .NET, k is negative when _q is negative
k = (k * _u) % _q;
BigInteger result = k * _p + p2;
return result;
}
public PublicKey PublicKey
{
get {
return _publickey;
}
}
private static BigInteger PrimeExponent(BigInteger privateExponent, BigInteger prime) {
BigInteger pe = prime - new BigInteger(1);
return privateExponent % pe;
}
/*
public RSAParameters ToRSAParameters() {
RSAParameters p = new RSAParameters();
p.D = _d.getBytes();
p.Exponent = _publickey.Exponent.getBytes();
p.Modulus = _publickey.Modulus.getBytes();
p.P = _p.getBytes();
p.Q = _q.getBytes();
BigInteger pe = PrimeExponent(_d, _p);
BigInteger qe = PrimeExponent(_d, _q);
p.DP = pe.getBytes();
p.DQ = qe.getBytes();
p.InverseQ = _u.getBytes();
return p;
}
*/
public static RSAKeyPair GenerateNew(int bits, Random rnd) {
BigInteger one = new BigInteger(1);
BigInteger p = null;
BigInteger q = null;
BigInteger t = null;
BigInteger p_1 = null;
BigInteger q_1 = null;
BigInteger phi = null;
BigInteger G = null;
BigInteger F = null;
BigInteger e = null;
BigInteger d = null;
BigInteger u = null;
BigInteger n = null;
bool finished = false;
while(!finished) {
p = BigInteger.genPseudoPrime(bits / 2, 64, rnd);
q = BigInteger.genPseudoPrime(bits - (bits / 2), 64, rnd);
if(p == 0) {
continue;
} else if(q < p) {
t = q;
q = p;
p = t;
}
t = p.gcd(q);
if(t != one) {
continue;
}
p_1 = p - one;
q_1 = q - one;
phi = p_1 * q_1;
G = p_1.gcd(q_1);
F = phi / G;
e = one << 5;
e = e - one;
do {
e = e + (one + one);
t = e.gcd(phi);
} while(t!=one);
// !!! d = e.modInverse(F);
d = e.modInverse(phi);
n = p * q;
u = p.modInverse(q);
finished = true;
}
return new RSAKeyPair(e,d,n,u,p,q);
}
}
internal class RSAPublicKey : PublicKey, IVerifier {
internal BigInteger _e;
internal BigInteger _n;
public RSAPublicKey(BigInteger exp, BigInteger mod) {
_e = exp;
_n = mod;
}
public PublicKeyAlgorithm Algorithm
{
get {
return PublicKeyAlgorithm.RSA;
}
}
public BigInteger Exponent {
get {
return _e;
}
}
public BigInteger Modulus {
get {
return _n;
}
}
public void Verify(byte[] data, byte[] expected) {
if(VerifyBI(data)!=new BigInteger(expected))
throw new Exception("Failed to verify");
}
private BigInteger VerifyBI(byte[] data) {
return new BigInteger(data).modPow(_e, _n);
}
public void VerifyWithSHA1(byte[] data, byte[] expected) {
BigInteger result = VerifyBI(data);
byte[] finaldata = RSAUtil.StripPKCS1Pad(result,1).getBytes();
if(finaldata.Length != PKIUtil.SHA1_ASN_ID.Length+expected.Length)
throw new Exception("result is too short");
else {
byte[] r = new byte[finaldata.Length];
Array.Copy(PKIUtil.SHA1_ASN_ID, 0, r, 0, PKIUtil.SHA1_ASN_ID.Length);
Array.Copy(expected, 0, r, PKIUtil.SHA1_ASN_ID.Length, expected.Length);
if(SSHUtil.memcmp(r, finaldata)!=0)
throw new Exception("failed to verify");
}
}
public void WriteTo(IKeyWriter writer) {
writer.Write(_e);
writer.Write(_n);
}
}
internal class RSAUtil {
public static BigInteger PKCS1PadType2(BigInteger input, int pad_len, Random rand) {
int input_byte_length = (input.bitCount()+7)/8;
//System.out.println(String.valueOf(pad_len) + ":" + input_byte_length);
byte[] pad = new byte[pad_len - input_byte_length - 3];
for(int i = 0; i < pad.Length; i++) {
byte[] b = new byte[1];
rand.NextBytes(b);
while(b[0] == 0) rand.NextBytes(b); //0‚Å‚Í‚¾‚ß‚¾
pad[i] = b[0];
}
BigInteger pad_int = new BigInteger(pad);
pad_int = pad_int << ((input_byte_length + 1) * 8);
BigInteger result = new BigInteger(2);
result = result << ((pad_len - 2) * 8);
result = result | pad_int;
result = result | input;
return result;
}
public static BigInteger PKCS1PadType1(BigInteger input, int pad_len) {
int input_byte_length = (input.bitCount()+7)/8;
//System.out.println(String.valueOf(pad_len) + ":" + input_byte_length);
byte[] pad = new byte[pad_len - input_byte_length - 3];
for(int i = 0; i < pad.Length; i++) {
pad[i] = (byte)0xff;
}
BigInteger pad_int = new BigInteger(pad);
pad_int = pad_int << ((input_byte_length + 1) * 8);
BigInteger result = new BigInteger(1);
result = result << ((pad_len - 2) * 8);
result = result | pad_int;
result = result | input;
return result;
}
public static BigInteger StripPKCS1Pad(BigInteger input, int type) {
byte[] strip = input.getBytes();
int i;
if(strip[0] != type) throw new Exception(String.Format("Invalid PKCS1 padding {0}", type));
for(i = 1; i < strip.Length; i++) {
if(strip[i] == 0) break;
if(type == 0x01 && strip[i] != (byte)0xff)
throw new Exception("Invalid PKCS1 padding, corrupt data");
}
if(i == strip.Length)
throw new Exception("Invalid PKCS1 padding, corrupt data");
byte[] val = new byte[strip.Length - i];
Array.Copy(strip, i, val, 0, val.Length);
return new BigInteger(val);
}
}
}