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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Utilities;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Operators;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Security.Certificates;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.X509.Extension;
namespace Org.BouncyCastle.X509
{
/**
* The following extensions are listed in RFC 2459 as relevant to CRLs
*
* Authority Key Identifier
* Issuer Alternative Name
* CRL Number
* Delta CRL Indicator (critical)
* Issuing Distribution Point (critical)
*/
public class X509Crl
: X509ExtensionBase
// TODO Add interface Crl?
{
private class CachedEncoding
{
private readonly byte[] encoding;
private readonly CrlException exception;
internal CachedEncoding(byte[] encoding, CrlException exception)
{
this.encoding = encoding;
this.exception = exception;
}
internal byte[] Encoding
{
get { return encoding; }
}
internal byte[] GetEncoded()
{
if (null != exception)
throw exception;
if (null == encoding)
throw new CrlException();
return encoding;
}
}
private readonly CertificateList c;
private readonly string sigAlgName;
private readonly byte[] sigAlgParams;
private readonly bool isIndirect;
private readonly object cacheLock = new object();
private CachedEncoding cachedEncoding;
private volatile bool hashValueSet;
private volatile int hashValue;
public X509Crl(byte[] encoding)
: this(CertificateList.GetInstance(encoding))
{
}
public X509Crl(CertificateList c)
{
this.c = c;
try
{
this.sigAlgName = X509SignatureUtilities.GetSignatureName(c.SignatureAlgorithm);
Asn1Encodable parameters = c.SignatureAlgorithm.Parameters;
this.sigAlgParams = (null == parameters) ? null : parameters.GetEncoded(Asn1Encodable.Der);
this.isIndirect = IsIndirectCrl;
}
catch (Exception e)
{
throw new CrlException("CRL contents invalid: " + e);
}
}
public virtual CertificateList CertificateList
{
get { return c; }
}
protected override X509Extensions GetX509Extensions()
{
return c.Version >= 2
? c.TbsCertList.Extensions
: null;
}
public virtual void Verify(
AsymmetricKeyParameter publicKey)
{
Verify(new Asn1VerifierFactoryProvider(publicKey));
}
/// <summary>
/// Verify the CRL's signature using a verifier created using the passed in verifier provider.
/// </summary>
/// <param name="verifierProvider">An appropriate provider for verifying the CRL's signature.</param>
/// <returns>True if the signature is valid.</returns>
/// <exception cref="Exception">If verifier provider is not appropriate or the CRL algorithm is invalid.</exception>
public virtual void Verify(
IVerifierFactoryProvider verifierProvider)
{
CheckSignature(verifierProvider.CreateVerifierFactory(c.SignatureAlgorithm));
}
protected virtual void CheckSignature(
IVerifierFactory verifier)
{
// TODO Compare IsAlgIDEqual in X509Certificate.CheckSignature
if (!c.SignatureAlgorithm.Equals(c.TbsCertList.Signature))
throw new CrlException("Signature algorithm on CertificateList does not match TbsCertList.");
Asn1Encodable parameters = c.SignatureAlgorithm.Parameters;
IStreamCalculator<IVerifier> streamCalculator = verifier.CreateCalculator();
byte[] b = this.GetTbsCertList();
streamCalculator.Stream.Write(b, 0, b.Length);
Platform.Dispose(streamCalculator.Stream);
if (!streamCalculator.GetResult().IsVerified(this.GetSignature()))
throw new InvalidKeyException("CRL does not verify with supplied public key.");
}
public virtual int Version
{
get { return c.Version; }
}
public virtual X509Name IssuerDN
{
get { return c.Issuer; }
}
public virtual DateTime ThisUpdate
{
get { return c.ThisUpdate.ToDateTime(); }
}
public virtual DateTime? NextUpdate => c.NextUpdate?.ToDateTime();
private ISet<X509CrlEntry> LoadCrlEntries()
{
var entrySet = new HashSet<X509CrlEntry>();
var revoked = c.GetRevokedCertificateEnumeration();
X509Name previousCertificateIssuer = IssuerDN;
foreach (CrlEntry entry in revoked)
{
X509CrlEntry crlEntry = new X509CrlEntry(entry, isIndirect, previousCertificateIssuer);
entrySet.Add(crlEntry);
previousCertificateIssuer = crlEntry.GetCertificateIssuer();
}
return entrySet;
}
public virtual X509CrlEntry GetRevokedCertificate(
BigInteger serialNumber)
{
var certs = c.GetRevokedCertificateEnumeration();
X509Name previousCertificateIssuer = IssuerDN;
foreach (CrlEntry entry in certs)
{
X509CrlEntry crlEntry = new X509CrlEntry(entry, isIndirect, previousCertificateIssuer);
if (serialNumber.Equals(entry.UserCertificate.Value))
{
return crlEntry;
}
previousCertificateIssuer = crlEntry.GetCertificateIssuer();
}
return null;
}
public virtual ISet<X509CrlEntry> GetRevokedCertificates()
{
var entrySet = LoadCrlEntries();
if (entrySet.Count > 0)
return entrySet;
return null;
}
public virtual byte[] GetTbsCertList()
{
try
{
return c.TbsCertList.GetDerEncoded();
}
catch (Exception e)
{
throw new CrlException(e.ToString());
}
}
public virtual byte[] GetSignature()
{
return c.GetSignatureOctets();
}
public virtual string SigAlgName
{
get { return sigAlgName; }
}
public virtual string SigAlgOid
{
get { return c.SignatureAlgorithm.Algorithm.Id; }
}
public virtual byte[] GetSigAlgParams()
{
return Arrays.Clone(sigAlgParams);
}
/// <summary>
/// Return the DER encoding of this CRL.
/// </summary>
/// <returns>A byte array containing the DER encoding of this CRL.</returns>
/// <exception cref="CrlException">If there is an error encoding the CRL.</exception>
public virtual byte[] GetEncoded()
{
return Arrays.Clone(GetCachedEncoding().GetEncoded());
}
public override bool Equals(object other)
{
if (this == other)
return true;
X509Crl that = other as X509Crl;
if (null == that)
return false;
if (this.hashValueSet && that.hashValueSet)
{
if (this.hashValue != that.hashValue)
return false;
}
else if (null == this.cachedEncoding || null == that.cachedEncoding)
{
DerBitString signature = c.Signature;
if (null != signature && !signature.Equals(that.c.Signature))
return false;
}
byte[] thisEncoding = this.GetCachedEncoding().Encoding;
byte[] thatEncoding = that.GetCachedEncoding().Encoding;
return null != thisEncoding
&& null != thatEncoding
&& Arrays.AreEqual(thisEncoding, thatEncoding);
}
public override int GetHashCode()
{
if (!hashValueSet)
{
byte[] thisEncoding = this.GetCachedEncoding().Encoding;
hashValue = Arrays.GetHashCode(thisEncoding);
hashValueSet = true;
}
return hashValue;
}
/**
* Returns a string representation of this CRL.
*
* @return a string representation of this CRL.
*/
public override string ToString()
{
StringBuilder buf = new StringBuilder();
buf.Append(" Version: ").Append(this.Version).AppendLine();
buf.Append(" IssuerDN: ").Append(this.IssuerDN).AppendLine();
buf.Append(" This update: ").Append(this.ThisUpdate).AppendLine();
buf.Append(" Next update: ").Append(this.NextUpdate).AppendLine();
buf.Append(" Signature Algorithm: ").Append(this.SigAlgName).AppendLine();
byte[] sig = this.GetSignature();
buf.Append(" Signature: ");
buf.Append(Hex.ToHexString(sig, 0, 20)).AppendLine();
for (int i = 20; i < sig.Length; i += 20)
{
int count = System.Math.Min(20, sig.Length - i);
buf.Append(" ");
buf.Append(Hex.ToHexString(sig, i, count)).AppendLine();
}
X509Extensions extensions = c.TbsCertList.Extensions;
if (extensions != null)
{
var e = extensions.ExtensionOids.GetEnumerator();
if (e.MoveNext())
{
buf.Append(" Extensions: ").AppendLine();
}
do
{
DerObjectIdentifier oid = e.Current;
X509Extension ext = extensions.GetExtension(oid);
if (ext.Value != null)
{
Asn1Object asn1Value = X509ExtensionUtilities.FromExtensionValue(ext.Value);
buf.Append(" critical(").Append(ext.IsCritical).Append(") ");
try
{
if (oid.Equals(X509Extensions.CrlNumber))
{
buf.Append(new CrlNumber(DerInteger.GetInstance(asn1Value).PositiveValue)).AppendLine();
}
else if (oid.Equals(X509Extensions.DeltaCrlIndicator))
{
buf.Append(
"Base CRL: "
+ new CrlNumber(DerInteger.GetInstance(
asn1Value).PositiveValue))
.AppendLine();
}
else if (oid.Equals(X509Extensions.IssuingDistributionPoint))
{
buf.Append(IssuingDistributionPoint.GetInstance((Asn1Sequence) asn1Value)).AppendLine();
}
else if (oid.Equals(X509Extensions.CrlDistributionPoints))
{
buf.Append(CrlDistPoint.GetInstance((Asn1Sequence) asn1Value)).AppendLine();
}
else if (oid.Equals(X509Extensions.FreshestCrl))
{
buf.Append(CrlDistPoint.GetInstance((Asn1Sequence) asn1Value)).AppendLine();
}
else
{
buf.Append(oid.Id);
buf.Append(" value = ").Append(
Asn1Dump.DumpAsString(asn1Value))
.AppendLine();
}
}
catch (Exception)
{
buf.Append(oid.Id);
buf.Append(" value = ").Append("*****").AppendLine();
}
}
else
{
buf.AppendLine();
}
}
while (e.MoveNext());
}
var certSet = GetRevokedCertificates();
if (certSet != null)
{
foreach (X509CrlEntry entry in certSet)
{
buf.Append(entry);
buf.AppendLine();
}
}
return buf.ToString();
}
/**
* Checks whether the given certificate is on this CRL.
*
* @param cert the certificate to check for.
* @return true if the given certificate is on this CRL,
* false otherwise.
*/
// public bool IsRevoked(
// Certificate cert)
// {
// if (!cert.getType().Equals("X.509"))
// {
// throw new RuntimeException("X.509 CRL used with non X.509 Cert");
// }
public virtual bool IsRevoked(
X509Certificate cert)
{
CrlEntry[] certs = c.GetRevokedCertificates();
if (certs != null)
{
BigInteger serial = cert.SerialNumber;
for (int i = 0; i < certs.Length; i++)
{
if (certs[i].UserCertificate.HasValue(serial))
return true;
}
}
return false;
}
protected virtual bool IsIndirectCrl
{
get
{
Asn1OctetString idp = GetExtensionValue(X509Extensions.IssuingDistributionPoint);
bool isIndirect = false;
try
{
if (idp != null)
{
isIndirect = IssuingDistributionPoint.GetInstance(
X509ExtensionUtilities.FromExtensionValue(idp)).IsIndirectCrl;
}
}
catch (Exception e)
{
// TODO
// throw new ExtCrlException("Exception reading IssuingDistributionPoint", e);
throw new CrlException("Exception reading IssuingDistributionPoint" + e);
}
return isIndirect;
}
}
private CachedEncoding GetCachedEncoding()
{
lock (cacheLock)
{
if (null != cachedEncoding)
return cachedEncoding;
}
byte[] encoding = null;
CrlException exception = null;
try
{
encoding = c.GetEncoded(Asn1Encodable.Der);
}
catch (IOException e)
{
exception = new CrlException("Failed to DER-encode CRL", e);
}
CachedEncoding temp = new CachedEncoding(encoding, exception);
lock (cacheLock)
{
if (null == cachedEncoding)
{
cachedEncoding = temp;
}
return cachedEncoding;
}
}
}
}
|