From e71fe27c302d36e6355d9da12f3d9ec51540825a Mon Sep 17 00:00:00 2001 From: Peter Dettman Date: Fri, 27 Jan 2023 01:58:23 +0700 Subject: Misc. cleanup after bc-fips-csharp updates --- crypto/src/asn1/cms/SignedData.cs | 4 +- .../asn1/cryptopro/ECGOST3410ParamSetParameters.cs | 4 +- .../asn1/cryptopro/GOST3410ParamSetParameters.cs | 9 +- crypto/src/asn1/esf/SignerLocation.cs | 16 +- crypto/src/asn1/isismtt/x509/Admissions.cs | 10 +- crypto/src/asn1/ocsp/CertID.cs | 30 +-- crypto/src/asn1/pkcs/CertBag.cs | 4 +- crypto/src/asn1/pkcs/ContentInfo.cs | 7 +- crypto/src/asn1/pkcs/EncryptedPrivateKeyInfo.cs | 20 +- crypto/src/asn1/pkcs/PBEParameter.cs | 23 +- crypto/src/asn1/pkcs/SignerInfo.cs | 24 +- crypto/src/asn1/x509/AuthorityInformationAccess.cs | 6 +- crypto/src/asn1/x509/ExtendedKeyUsage.cs | 4 +- crypto/src/asn1/x509/NameConstraints.cs | 10 +- crypto/src/asn1/x509/SubjectDirectoryAttributes.cs | 34 +-- crypto/src/asn1/x509/SubjectPublicKeyInfo.cs | 1 - crypto/src/asn1/x509/V2TBSCertListGenerator.cs | 2 - crypto/src/asn1/x509/X509ExtensionsGenerator.cs | 2 - crypto/src/cms/CMSSignedDataParser.cs | 1 - .../cms/DefaultSignedAttributeTableGenerator.cs | 39 ++- crypto/src/cms/OriginatorInformation.cs | 2 +- crypto/src/cms/RecipientInformationStore.cs | 2 +- crypto/src/cms/SignerInfoGenerator.cs | 15 +- crypto/src/crypto/CryptoServicesRegistrar.cs | 2 +- crypto/src/crypto/digests/LongDigest.cs | 2 +- crypto/src/crypto/digests/MD5Digest.cs | 141 +++++------ crypto/src/crypto/encodings/OaepEncoding.cs | 19 +- crypto/src/crypto/generators/ECKeyPairGenerator.cs | 68 ++---- crypto/src/crypto/modes/GCMBlockCipher.cs | 41 +--- crypto/src/crypto/modes/gcm/GcmUtilities.cs | 6 +- crypto/src/crypto/signers/Ed25519phSigner.cs | 4 +- crypto/src/crypto/signers/Ed448phSigner.cs | 4 +- crypto/src/crypto/signers/IsoTrailers.cs | 5 +- crypto/src/crypto/signers/PssSigner.cs | 21 +- crypto/src/math/ec/ECPoint.cs | 6 +- crypto/src/math/ec/abc/Tnaf.cs | 4 +- crypto/src/openpgp/PgpUtilities.cs | 268 ++++++++++----------- crypto/src/pkix/PkixCertPath.cs | 31 +-- crypto/src/pkix/PkixCertPathChecker.cs | 2 - crypto/src/pkix/PkixCertPathValidator.cs | 4 +- crypto/src/pkix/PkixCertPathValidatorUtilities.cs | 27 +-- crypto/src/pkix/PkixCrlUtilities.cs | 54 ++--- crypto/src/pkix/Rfc3281CertPathUtilities.cs | 19 +- crypto/src/util/collections/CollectionUtilities.cs | 13 + crypto/src/x509/X509AttrCertParser.cs | 4 - crypto/src/x509/store/X509AttrCertStoreSelector.cs | 24 +- 46 files changed, 438 insertions(+), 600 deletions(-) diff --git a/crypto/src/asn1/cms/SignedData.cs b/crypto/src/asn1/cms/SignedData.cs index 789f8bd72..6b07e5128 100644 --- a/crypto/src/asn1/cms/SignedData.cs +++ b/crypto/src/asn1/cms/SignedData.cs @@ -24,8 +24,8 @@ namespace Org.BouncyCastle.Asn1.Cms public static SignedData GetInstance(object obj) { - if (obj is SignedData) - return (SignedData)obj; + if (obj is SignedData signedData) + return signedData; if (obj == null) return null; return new SignedData(Asn1Sequence.GetInstance(obj)); diff --git a/crypto/src/asn1/cryptopro/ECGOST3410ParamSetParameters.cs b/crypto/src/asn1/cryptopro/ECGOST3410ParamSetParameters.cs index 87df3c4a9..2c494c526 100644 --- a/crypto/src/asn1/cryptopro/ECGOST3410ParamSetParameters.cs +++ b/crypto/src/asn1/cryptopro/ECGOST3410ParamSetParameters.cs @@ -18,9 +18,7 @@ namespace Org.BouncyCastle.Asn1.CryptoPro public static ECGost3410ParamSetParameters GetInstance(object obj) { if (obj == null || obj is ECGost3410ParamSetParameters) - { - return (ECGost3410ParamSetParameters) obj; - } + return (ECGost3410ParamSetParameters)obj; if (obj is Asn1Sequence seq) return new ECGost3410ParamSetParameters(seq); diff --git a/crypto/src/asn1/cryptopro/GOST3410ParamSetParameters.cs b/crypto/src/asn1/cryptopro/GOST3410ParamSetParameters.cs index c82e4248a..ae0cd4f83 100644 --- a/crypto/src/asn1/cryptopro/GOST3410ParamSetParameters.cs +++ b/crypto/src/asn1/cryptopro/GOST3410ParamSetParameters.cs @@ -27,11 +27,7 @@ namespace Org.BouncyCastle.Asn1.CryptoPro throw new ArgumentException("Invalid GOST3410Parameter: " + Platform.GetTypeName(obj)); } - public Gost3410ParamSetParameters( - int keySize, - BigInteger p, - BigInteger q, - BigInteger a) + public Gost3410ParamSetParameters(int keySize, BigInteger p, BigInteger q, BigInteger a) { this.keySize = keySize; this.p = new DerInteger(p); @@ -39,8 +35,7 @@ namespace Org.BouncyCastle.Asn1.CryptoPro this.a = new DerInteger(a); } - private Gost3410ParamSetParameters( - Asn1Sequence seq) + private Gost3410ParamSetParameters(Asn1Sequence seq) { if (seq.Count != 4) throw new ArgumentException("Wrong number of elements in sequence", "seq"); diff --git a/crypto/src/asn1/esf/SignerLocation.cs b/crypto/src/asn1/esf/SignerLocation.cs index 0e87812be..106a32c59 100644 --- a/crypto/src/asn1/esf/SignerLocation.cs +++ b/crypto/src/asn1/esf/SignerLocation.cs @@ -19,9 +19,9 @@ namespace Org.BouncyCastle.Asn1.Esf public class SignerLocation : Asn1Encodable { - private DirectoryString countryName; - private DirectoryString localityName; - private Asn1Sequence postalAddress; + private readonly DirectoryString countryName; + private readonly DirectoryString localityName; + private readonly Asn1Sequence postalAddress; public SignerLocation(Asn1Sequence seq) { @@ -99,13 +99,7 @@ namespace Org.BouncyCastle.Asn1.Esf if (postalAddress == null) return null; - DirectoryString[] dirStrings = new DirectoryString[postalAddress.Count]; - for (int i = 0; i != dirStrings.Length; i++) - { - dirStrings[i] = DirectoryString.GetInstance(postalAddress[i]); - } - - return dirStrings; + return postalAddress.MapElements(element => DirectoryString.GetInstance(element.ToAsn1Object())); } public Asn1Sequence PostalAddress @@ -132,7 +126,7 @@ namespace Org.BouncyCastle.Asn1.Esf */ public override Asn1Object ToAsn1Object() { - Asn1EncodableVector v = new Asn1EncodableVector(); + Asn1EncodableVector v = new Asn1EncodableVector(3); v.AddOptionalTagged(true, 0, countryName); v.AddOptionalTagged(true, 1, localityName); v.AddOptionalTagged(true, 2, postalAddress); diff --git a/crypto/src/asn1/isismtt/x509/Admissions.cs b/crypto/src/asn1/isismtt/x509/Admissions.cs index 42ebceb1c..1ade6093f 100644 --- a/crypto/src/asn1/isismtt/x509/Admissions.cs +++ b/crypto/src/asn1/isismtt/x509/Admissions.cs @@ -70,13 +70,13 @@ namespace Org.BouncyCastle.Asn1.IsisMtt.X509 switch (tagged1.TagNo) { case 0: - admissionAuthority = GeneralName.GetInstance((Asn1TaggedObject)o, true); + admissionAuthority = GeneralName.GetInstance(tagged1, true); break; case 1: - namingAuthority = NamingAuthority.GetInstance((Asn1TaggedObject)o, true); + namingAuthority = NamingAuthority.GetInstance(tagged1, true); break; default: - throw new ArgumentException("Bad tag number: " + ((Asn1TaggedObject)o).TagNo); + throw new ArgumentException("Bad tag number: " + tagged1.TagNo); } e.MoveNext(); o = e.Current; @@ -86,10 +86,10 @@ namespace Org.BouncyCastle.Asn1.IsisMtt.X509 switch (tagged2.TagNo) { case 1: - namingAuthority = NamingAuthority.GetInstance((Asn1TaggedObject)o, true); + namingAuthority = NamingAuthority.GetInstance(tagged2, true); break; default: - throw new ArgumentException("Bad tag number: " + ((Asn1TaggedObject)o).TagNo); + throw new ArgumentException("Bad tag number: " + tagged2.TagNo); } e.MoveNext(); o = e.Current; diff --git a/crypto/src/asn1/ocsp/CertID.cs b/crypto/src/asn1/ocsp/CertID.cs index 523f6b87c..12a111ec9 100644 --- a/crypto/src/asn1/ocsp/CertID.cs +++ b/crypto/src/asn1/ocsp/CertID.cs @@ -1,12 +1,10 @@ using System; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; -using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Ocsp { - public class CertID + public class CertID : Asn1Encodable { private readonly AlgorithmIdentifier hashAlgorithm; @@ -14,27 +12,18 @@ namespace Org.BouncyCastle.Asn1.Ocsp private readonly Asn1OctetString issuerKeyHash; private readonly DerInteger serialNumber; - public static CertID GetInstance( - Asn1TaggedObject obj, - bool explicitly) + public static CertID GetInstance(Asn1TaggedObject obj, bool explicitly) { return GetInstance(Asn1Sequence.GetInstance(obj, explicitly)); } - public static CertID GetInstance( - object obj) + public static CertID GetInstance(object obj) { - if (obj == null || obj is CertID) - { - return (CertID)obj; - } - - if (obj is Asn1Sequence) - { - return new CertID((Asn1Sequence)obj); - } - - throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); + if (obj == null) + return null; + if (obj is CertID certID) + return certID; + return new CertID(Asn1Sequence.GetInstance(obj)); } public CertID( @@ -49,8 +38,7 @@ namespace Org.BouncyCastle.Asn1.Ocsp this.serialNumber = serialNumber; } - private CertID( - Asn1Sequence seq) + private CertID(Asn1Sequence seq) { if (seq.Count != 4) throw new ArgumentException("Wrong number of elements in sequence", "seq"); diff --git a/crypto/src/asn1/pkcs/CertBag.cs b/crypto/src/asn1/pkcs/CertBag.cs index b32b10ae0..81868fef6 100644 --- a/crypto/src/asn1/pkcs/CertBag.cs +++ b/crypto/src/asn1/pkcs/CertBag.cs @@ -7,8 +7,8 @@ namespace Org.BouncyCastle.Asn1.Pkcs { public static CertBag GetInstance(object obj) { - if (obj is CertBag) - return (CertBag)obj; + if (obj is CertBag certBag) + return certBag; if (obj == null) return null; return new CertBag(Asn1Sequence.GetInstance(obj)); diff --git a/crypto/src/asn1/pkcs/ContentInfo.cs b/crypto/src/asn1/pkcs/ContentInfo.cs index d19b4659c..05d9a2033 100644 --- a/crypto/src/asn1/pkcs/ContentInfo.cs +++ b/crypto/src/asn1/pkcs/ContentInfo.cs @@ -1,5 +1,3 @@ -using System; - namespace Org.BouncyCastle.Asn1.Pkcs { public class ContentInfo @@ -12,9 +10,8 @@ namespace Org.BouncyCastle.Asn1.Pkcs { if (obj == null) return null; - ContentInfo existing = obj as ContentInfo; - if (existing != null) - return existing; + if (obj is ContentInfo contentInfo) + return contentInfo; return new ContentInfo(Asn1Sequence.GetInstance(obj)); } diff --git a/crypto/src/asn1/pkcs/EncryptedPrivateKeyInfo.cs b/crypto/src/asn1/pkcs/EncryptedPrivateKeyInfo.cs index 5ca612f27..bf0e1aaeb 100644 --- a/crypto/src/asn1/pkcs/EncryptedPrivateKeyInfo.cs +++ b/crypto/src/asn1/pkcs/EncryptedPrivateKeyInfo.cs @@ -1,7 +1,6 @@ using System; using Org.BouncyCastle.Asn1.X509; -using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Pkcs { @@ -28,19 +27,14 @@ namespace Org.BouncyCastle.Asn1.Pkcs this.data = new DerOctetString(encoding); } - public static EncryptedPrivateKeyInfo GetInstance( - object obj) + public static EncryptedPrivateKeyInfo GetInstance(object obj) { - if (obj is EncryptedPrivateKeyInfo) - { - return (EncryptedPrivateKeyInfo) obj; - } - - if (obj is Asn1Sequence seq) - return new EncryptedPrivateKeyInfo(seq); - - throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); - } + if (obj == null) + return null; + if (obj is EncryptedPrivateKeyInfo encryptedPrivateKeyInfo) + return encryptedPrivateKeyInfo; + return new EncryptedPrivateKeyInfo(Asn1Sequence.GetInstance(obj)); + } public AlgorithmIdentifier EncryptionAlgorithm { diff --git a/crypto/src/asn1/pkcs/PBEParameter.cs b/crypto/src/asn1/pkcs/PBEParameter.cs index e8e7c5a82..31d9ad1f3 100644 --- a/crypto/src/asn1/pkcs/PBEParameter.cs +++ b/crypto/src/asn1/pkcs/PBEParameter.cs @@ -1,7 +1,6 @@ using System; using Org.BouncyCastle.Math; -using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Pkcs { @@ -11,20 +10,14 @@ namespace Org.BouncyCastle.Asn1.Pkcs private readonly Asn1OctetString salt; private readonly DerInteger iterationCount; - public static PbeParameter GetInstance(object obj) - { - if (obj is PbeParameter || obj == null) - { - return (PbeParameter) obj; - } - - if (obj is Asn1Sequence) - { - return new PbeParameter((Asn1Sequence) obj); - } - - throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); - } + public static PbeParameter GetInstance(object obj) + { + if (obj == null) + return null; + if (obj is PbeParameter pbeParameter) + return pbeParameter; + return new PbeParameter(Asn1Sequence.GetInstance(obj)); + } private PbeParameter(Asn1Sequence seq) { diff --git a/crypto/src/asn1/pkcs/SignerInfo.cs b/crypto/src/asn1/pkcs/SignerInfo.cs index 7abd8e5c6..777251e84 100644 --- a/crypto/src/asn1/pkcs/SignerInfo.cs +++ b/crypto/src/asn1/pkcs/SignerInfo.cs @@ -1,7 +1,4 @@ -using System; - using Org.BouncyCastle.Asn1.X509; -using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Pkcs { @@ -19,21 +16,14 @@ namespace Org.BouncyCastle.Asn1.Pkcs private Asn1OctetString encryptedDigest; private Asn1Set unauthenticatedAttributes; - public static SignerInfo GetInstance( - object obj) + public static SignerInfo GetInstance(object obj) { - if (obj is SignerInfo) - { - return (SignerInfo) obj; - } - - if (obj is Asn1Sequence) - { - return new SignerInfo((Asn1Sequence) obj); - } - - throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); - } + if (obj == null) + return null; + if (obj is SignerInfo signerInfo) + return signerInfo; + return new SignerInfo(Asn1Sequence.GetInstance(obj)); + } public SignerInfo( DerInteger version, diff --git a/crypto/src/asn1/x509/AuthorityInformationAccess.cs b/crypto/src/asn1/x509/AuthorityInformationAccess.cs index 382513674..c601322c5 100644 --- a/crypto/src/asn1/x509/AuthorityInformationAccess.cs +++ b/crypto/src/asn1/x509/AuthorityInformationAccess.cs @@ -1,8 +1,6 @@ using System; using System.Text; -using Org.BouncyCastle.Utilities; - namespace Org.BouncyCastle.Asn1.X509 { /** @@ -31,10 +29,10 @@ namespace Org.BouncyCastle.Asn1.X509 public static AuthorityInformationAccess GetInstance(object obj) { - if (obj is AuthorityInformationAccess) - return (AuthorityInformationAccess)obj; if (obj == null) return null; + if (obj is AuthorityInformationAccess authorityInformationAccess) + return authorityInformationAccess; return new AuthorityInformationAccess(Asn1Sequence.GetInstance(obj)); } diff --git a/crypto/src/asn1/x509/ExtendedKeyUsage.cs b/crypto/src/asn1/x509/ExtendedKeyUsage.cs index f812c308d..08962ab72 100644 --- a/crypto/src/asn1/x509/ExtendedKeyUsage.cs +++ b/crypto/src/asn1/x509/ExtendedKeyUsage.cs @@ -67,10 +67,8 @@ namespace Org.BouncyCastle.Asn1.X509 { Asn1EncodableVector v = new Asn1EncodableVector(); - foreach (object usage in usages) + foreach (var oid in usages) { - DerObjectIdentifier oid = DerObjectIdentifier.GetInstance(usage); - v.Add(oid); m_usageTable.Add(oid); } diff --git a/crypto/src/asn1/x509/NameConstraints.cs b/crypto/src/asn1/x509/NameConstraints.cs index 9fe4fdd01..590b14aa0 100644 --- a/crypto/src/asn1/x509/NameConstraints.cs +++ b/crypto/src/asn1/x509/NameConstraints.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using Org.BouncyCastle.Utilities; @@ -68,12 +69,7 @@ namespace Org.BouncyCastle.Asn1.X509 private DerSequence CreateSequence(IList subtrees) { - GeneralSubtree[] gsts = new GeneralSubtree[subtrees.Count]; - for (int i = 0; i < subtrees.Count; ++i) - { - gsts[i] = subtrees[i]; - } - return new DerSequence(gsts); + return new DerSequence(subtrees.ToArray()); } public Asn1Sequence PermittedSubtrees @@ -92,7 +88,7 @@ namespace Org.BouncyCastle.Asn1.X509 */ public override Asn1Object ToAsn1Object() { - Asn1EncodableVector v = new Asn1EncodableVector(); + Asn1EncodableVector v = new Asn1EncodableVector(2); v.AddOptionalTagged(false, 0, permitted); v.AddOptionalTagged(false, 1, excluded); return new DerSequence(v); diff --git a/crypto/src/asn1/x509/SubjectDirectoryAttributes.cs b/crypto/src/asn1/x509/SubjectDirectoryAttributes.cs index 6ebd35e21..c8f24ecd5 100644 --- a/crypto/src/asn1/x509/SubjectDirectoryAttributes.cs +++ b/crypto/src/asn1/x509/SubjectDirectoryAttributes.cs @@ -1,7 +1,5 @@ -using System; using System.Collections.Generic; -using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; namespace Org.BouncyCastle.Asn1.X509 @@ -28,23 +26,16 @@ namespace Org.BouncyCastle.Asn1.X509 public class SubjectDirectoryAttributes : Asn1Encodable { - private readonly IList m_attributes; + private readonly List m_attributes; - public static SubjectDirectoryAttributes GetInstance( - object obj) - { - if (obj == null || obj is SubjectDirectoryAttributes) - { - return (SubjectDirectoryAttributes) obj; - } - - if (obj is Asn1Sequence) - { - return new SubjectDirectoryAttributes((Asn1Sequence) obj); - } - - throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); - } + public static SubjectDirectoryAttributes GetInstance(object obj) + { + if (obj == null) + return null; + if (obj is SubjectDirectoryAttributes subjectDirectoryAttributes) + return subjectDirectoryAttributes; + return new SubjectDirectoryAttributes(Asn1Sequence.GetInstance(obj)); + } /** * Constructor from Asn1Sequence. @@ -114,12 +105,7 @@ namespace Org.BouncyCastle.Asn1.X509 */ public override Asn1Object ToAsn1Object() { - AttributeX509[] v = new AttributeX509[m_attributes.Count]; - for (int i = 0; i < m_attributes.Count; ++i) - { - v[i] = m_attributes[i]; - } - return new DerSequence(v); + return new DerSequence(m_attributes.ToArray()); } /** diff --git a/crypto/src/asn1/x509/SubjectPublicKeyInfo.cs b/crypto/src/asn1/x509/SubjectPublicKeyInfo.cs index 52f977e91..4875152eb 100644 --- a/crypto/src/asn1/x509/SubjectPublicKeyInfo.cs +++ b/crypto/src/asn1/x509/SubjectPublicKeyInfo.cs @@ -1,5 +1,4 @@ using System; -using System.IO; namespace Org.BouncyCastle.Asn1.X509 { diff --git a/crypto/src/asn1/x509/V2TBSCertListGenerator.cs b/crypto/src/asn1/x509/V2TBSCertListGenerator.cs index aa1a0b95d..bf016c22d 100644 --- a/crypto/src/asn1/x509/V2TBSCertListGenerator.cs +++ b/crypto/src/asn1/x509/V2TBSCertListGenerator.cs @@ -2,8 +2,6 @@ using System; using System.Collections.Generic; using System.IO; -using Org.BouncyCastle.Utilities; - namespace Org.BouncyCastle.Asn1.X509 { /** diff --git a/crypto/src/asn1/x509/X509ExtensionsGenerator.cs b/crypto/src/asn1/x509/X509ExtensionsGenerator.cs index 53d18ecff..7ea6084af 100644 --- a/crypto/src/asn1/x509/X509ExtensionsGenerator.cs +++ b/crypto/src/asn1/x509/X509ExtensionsGenerator.cs @@ -90,8 +90,6 @@ namespace Org.BouncyCastle.Asn1.X509 } } - - /// Return true if there are no extension present in this generator. /// True if empty, false otherwise public bool IsEmpty diff --git a/crypto/src/cms/CMSSignedDataParser.cs b/crypto/src/cms/CMSSignedDataParser.cs index 83f87718f..8b02770d6 100644 --- a/crypto/src/cms/CMSSignedDataParser.cs +++ b/crypto/src/cms/CMSSignedDataParser.cs @@ -8,7 +8,6 @@ using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.IO; using Org.BouncyCastle.Security; -using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; using Org.BouncyCastle.Utilities.IO; using Org.BouncyCastle.X509; diff --git a/crypto/src/cms/DefaultSignedAttributeTableGenerator.cs b/crypto/src/cms/DefaultSignedAttributeTableGenerator.cs index d8b668c4e..dea4de0a3 100644 --- a/crypto/src/cms/DefaultSignedAttributeTableGenerator.cs +++ b/crypto/src/cms/DefaultSignedAttributeTableGenerator.cs @@ -60,23 +60,22 @@ namespace Org.BouncyCastle.Cms private void DoCreateStandardAttributeTable(IDictionary parameters, IDictionary std) { - // contentType will be absent if we're trying to generate a counter signature. - - if (parameters.ContainsKey(CmsAttributeTableParameter.ContentType)) + if (!std.ContainsKey(CmsAttributes.ContentType)) { - if (!std.ContainsKey(CmsAttributes.ContentType)) + // contentType will be absent if we're trying to generate a counter signature. + if (parameters.TryGetValue(CmsAttributeTableParameter.ContentType, out var contentType)) { - DerObjectIdentifier contentType = (DerObjectIdentifier) - parameters[CmsAttributeTableParameter.ContentType]; - Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(CmsAttributes.ContentType, - new DerSet(contentType)); + Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute( + CmsAttributes.ContentType, + new DerSet((DerObjectIdentifier)contentType)); std[attr.AttrType] = attr; } } if (!std.ContainsKey(CmsAttributes.SigningTime)) { - Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(CmsAttributes.SigningTime, + Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute( + CmsAttributes.SigningTime, new DerSet(new Time(DateTime.UtcNow))); std[attr.AttrType] = attr; } @@ -84,17 +83,35 @@ namespace Org.BouncyCastle.Cms if (!std.ContainsKey(CmsAttributes.MessageDigest)) { byte[] messageDigest = (byte[])parameters[CmsAttributeTableParameter.Digest]; - Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(CmsAttributes.MessageDigest, + + Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute( + CmsAttributes.MessageDigest, new DerSet(new DerOctetString(messageDigest))); std[attr.AttrType] = attr; } + + // TODO CmsAlgorithmProtect support (see bc-fips-csharp) + //if (!std.ContainsKey(CmsAttributes.CmsAlgorithmProtect)) + //{ + // var digestAlgorithmIdentifier = (Asn1.X509.AlgorithmIdentifier) + // parameters[CmsAttributeTableParameter.DigestAlgorithmIdentifier]; + // var signatureAlgorithmIdentifier = (Asn1.X509.AlgorithmIdentifier) + // parameters[CmsAttributeTableParameter.SignatureAlgorithmIdentifier]; + // var cmsAlgorithmProtection = new CmsAlgorithmProtection( + // digestAlgorithmIdentifier, CmsAlgorithmProtection.Signature, signatureAlgorithmIdentifier); + + // Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute( + // CmsAttributes.CmsAlgorithmProtect, + // new DerSet(cmsAlgorithmProtection)); + // std[attr.AttrType] = attr; + //} } /** * @param parameters source parameters * @return the populated attribute table */ - public virtual AttributeTable GetAttributes(IDictionary parameters) + public virtual AttributeTable GetAttributes(IDictionary parameters) { var table = CreateStandardAttributeTable(parameters); return new AttributeTable(table); diff --git a/crypto/src/cms/OriginatorInformation.cs b/crypto/src/cms/OriginatorInformation.cs index 7186fafc3..6307cbc1f 100644 --- a/crypto/src/cms/OriginatorInformation.cs +++ b/crypto/src/cms/OriginatorInformation.cs @@ -10,7 +10,7 @@ namespace Org.BouncyCastle.Cms { private readonly OriginatorInfo originatorInfo; - internal OriginatorInformation(OriginatorInfo originatorInfo) + public OriginatorInformation(OriginatorInfo originatorInfo) { this.originatorInfo = originatorInfo; } diff --git a/crypto/src/cms/RecipientInformationStore.cs b/crypto/src/cms/RecipientInformationStore.cs index 06d093805..281b51c79 100644 --- a/crypto/src/cms/RecipientInformationStore.cs +++ b/crypto/src/cms/RecipientInformationStore.cs @@ -25,7 +25,7 @@ namespace Org.BouncyCastle.Cms list.Add(recipientInformation); } - this.m_all = new List(recipientInfos); + m_all = new List(recipientInfos); } public RecipientInformation this[RecipientID selector] diff --git a/crypto/src/cms/SignerInfoGenerator.cs b/crypto/src/cms/SignerInfoGenerator.cs index 786749cb5..2fa185885 100644 --- a/crypto/src/cms/SignerInfoGenerator.cs +++ b/crypto/src/cms/SignerInfoGenerator.cs @@ -1,5 +1,3 @@ -using System; - using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Cms; using Org.BouncyCastle.Asn1.X509; @@ -23,7 +21,8 @@ namespace Org.BouncyCastle.Cms internal CmsAttributeTableGenerator unsignedGen; private bool isDirectSignature; - internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureFactory signerFactory): this(sigId, signerFactory, false) + internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureFactory signerFactory) + : this(sigId, signerFactory, false) { } @@ -45,7 +44,8 @@ namespace Org.BouncyCastle.Cms } } - internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureFactory contentSigner, CmsAttributeTableGenerator signedGen, CmsAttributeTableGenerator unsignedGen) + internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureFactory contentSigner, + CmsAttributeTableGenerator signedGen, CmsAttributeTableGenerator unsignedGen) { this.sigId = sigId; this.contentSigner = contentSigner; @@ -54,7 +54,7 @@ namespace Org.BouncyCastle.Cms this.isDirectSignature = false; } - internal void setAssociatedCertificate(X509Certificate certificate) + internal void SetAssociatedCertificate(X509Certificate certificate) { this.certificate = certificate; } @@ -130,11 +130,12 @@ namespace Org.BouncyCastle.Cms */ public SignerInfoGenerator Build(ISignatureFactory contentSigner, X509Certificate certificate) { - SignerIdentifier sigId = new SignerIdentifier(new IssuerAndSerialNumber(certificate.IssuerDN, new DerInteger(certificate.SerialNumber))); + SignerIdentifier sigId = new SignerIdentifier(new IssuerAndSerialNumber(certificate.IssuerDN, + new DerInteger(certificate.SerialNumber))); SignerInfoGenerator sigInfoGen = CreateGenerator(contentSigner, sigId); - sigInfoGen.setAssociatedCertificate(certificate); + sigInfoGen.SetAssociatedCertificate(certificate); return sigInfoGen; } diff --git a/crypto/src/crypto/CryptoServicesRegistrar.cs b/crypto/src/crypto/CryptoServicesRegistrar.cs index 33bf47386..a2784108e 100644 --- a/crypto/src/crypto/CryptoServicesRegistrar.cs +++ b/crypto/src/crypto/CryptoServicesRegistrar.cs @@ -11,7 +11,7 @@ namespace Org.BouncyCastle.Crypto public static SecureRandom GetSecureRandom(SecureRandom secureRandom) { - return secureRandom ?? new SecureRandom(); + return secureRandom ?? GetSecureRandom(); } } } diff --git a/crypto/src/crypto/digests/LongDigest.cs b/crypto/src/crypto/digests/LongDigest.cs index 6a2f94ece..df48c4889 100644 --- a/crypto/src/crypto/digests/LongDigest.cs +++ b/crypto/src/crypto/digests/LongDigest.cs @@ -12,7 +12,7 @@ namespace Org.BouncyCastle.Crypto.Digests public abstract class LongDigest : IDigest, IMemoable { - private int MyByteLength = 128; + private const int MyByteLength = 128; private byte[] xBuf; private int xBufOff; diff --git a/crypto/src/crypto/digests/MD5Digest.cs b/crypto/src/crypto/digests/MD5Digest.cs index 062d7bb46..3a0967bc3 100644 --- a/crypto/src/crypto/digests/MD5Digest.cs +++ b/crypto/src/crypto/digests/MD5Digest.cs @@ -181,16 +181,6 @@ namespace Org.BouncyCastle.Crypto.Digests private static readonly int S43 = 15; private static readonly int S44 = 21; - /* - * rotate int x left n bits. - */ - private static uint RotateLeft( - uint x, - int n) - { - return (x << n) | (x >> (32 - n)); - } - /* * F, G, H and I are the basic MD5 functions. */ @@ -236,82 +226,82 @@ namespace Org.BouncyCastle.Crypto.Digests // // Round 1 - F cycle, 16 times. // - a = RotateLeft((a + F(b, c, d) + X[0] + 0xd76aa478), S11) + b; - d = RotateLeft((d + F(a, b, c) + X[1] + 0xe8c7b756), S12) + a; - c = RotateLeft((c + F(d, a, b) + X[2] + 0x242070db), S13) + d; - b = RotateLeft((b + F(c, d, a) + X[3] + 0xc1bdceee), S14) + c; - a = RotateLeft((a + F(b, c, d) + X[4] + 0xf57c0faf), S11) + b; - d = RotateLeft((d + F(a, b, c) + X[5] + 0x4787c62a), S12) + a; - c = RotateLeft((c + F(d, a, b) + X[6] + 0xa8304613), S13) + d; - b = RotateLeft((b + F(c, d, a) + X[7] + 0xfd469501), S14) + c; - a = RotateLeft((a + F(b, c, d) + X[8] + 0x698098d8), S11) + b; - d = RotateLeft((d + F(a, b, c) + X[9] + 0x8b44f7af), S12) + a; - c = RotateLeft((c + F(d, a, b) + X[10] + 0xffff5bb1), S13) + d; - b = RotateLeft((b + F(c, d, a) + X[11] + 0x895cd7be), S14) + c; - a = RotateLeft((a + F(b, c, d) + X[12] + 0x6b901122), S11) + b; - d = RotateLeft((d + F(a, b, c) + X[13] + 0xfd987193), S12) + a; - c = RotateLeft((c + F(d, a, b) + X[14] + 0xa679438e), S13) + d; - b = RotateLeft((b + F(c, d, a) + X[15] + 0x49b40821), S14) + c; + a = Integers.RotateLeft((a + F(b, c, d) + X[0] + 0xd76aa478), S11) + b; + d = Integers.RotateLeft((d + F(a, b, c) + X[1] + 0xe8c7b756), S12) + a; + c = Integers.RotateLeft((c + F(d, a, b) + X[2] + 0x242070db), S13) + d; + b = Integers.RotateLeft((b + F(c, d, a) + X[3] + 0xc1bdceee), S14) + c; + a = Integers.RotateLeft((a + F(b, c, d) + X[4] + 0xf57c0faf), S11) + b; + d = Integers.RotateLeft((d + F(a, b, c) + X[5] + 0x4787c62a), S12) + a; + c = Integers.RotateLeft((c + F(d, a, b) + X[6] + 0xa8304613), S13) + d; + b = Integers.RotateLeft((b + F(c, d, a) + X[7] + 0xfd469501), S14) + c; + a = Integers.RotateLeft((a + F(b, c, d) + X[8] + 0x698098d8), S11) + b; + d = Integers.RotateLeft((d + F(a, b, c) + X[9] + 0x8b44f7af), S12) + a; + c = Integers.RotateLeft((c + F(d, a, b) + X[10] + 0xffff5bb1), S13) + d; + b = Integers.RotateLeft((b + F(c, d, a) + X[11] + 0x895cd7be), S14) + c; + a = Integers.RotateLeft((a + F(b, c, d) + X[12] + 0x6b901122), S11) + b; + d = Integers.RotateLeft((d + F(a, b, c) + X[13] + 0xfd987193), S12) + a; + c = Integers.RotateLeft((c + F(d, a, b) + X[14] + 0xa679438e), S13) + d; + b = Integers.RotateLeft((b + F(c, d, a) + X[15] + 0x49b40821), S14) + c; // // Round 2 - G cycle, 16 times. // - a = RotateLeft((a + G(b, c, d) + X[1] + 0xf61e2562), S21) + b; - d = RotateLeft((d + G(a, b, c) + X[6] + 0xc040b340), S22) + a; - c = RotateLeft((c + G(d, a, b) + X[11] + 0x265e5a51), S23) + d; - b = RotateLeft((b + G(c, d, a) + X[0] + 0xe9b6c7aa), S24) + c; - a = RotateLeft((a + G(b, c, d) + X[5] + 0xd62f105d), S21) + b; - d = RotateLeft((d + G(a, b, c) + X[10] + 0x02441453), S22) + a; - c = RotateLeft((c + G(d, a, b) + X[15] + 0xd8a1e681), S23) + d; - b = RotateLeft((b + G(c, d, a) + X[4] + 0xe7d3fbc8), S24) + c; - a = RotateLeft((a + G(b, c, d) + X[9] + 0x21e1cde6), S21) + b; - d = RotateLeft((d + G(a, b, c) + X[14] + 0xc33707d6), S22) + a; - c = RotateLeft((c + G(d, a, b) + X[3] + 0xf4d50d87), S23) + d; - b = RotateLeft((b + G(c, d, a) + X[8] + 0x455a14ed), S24) + c; - a = RotateLeft((a + G(b, c, d) + X[13] + 0xa9e3e905), S21) + b; - d = RotateLeft((d + G(a, b, c) + X[2] + 0xfcefa3f8), S22) + a; - c = RotateLeft((c + G(d, a, b) + X[7] + 0x676f02d9), S23) + d; - b = RotateLeft((b + G(c, d, a) + X[12] + 0x8d2a4c8a), S24) + c; + a = Integers.RotateLeft((a + G(b, c, d) + X[1] + 0xf61e2562), S21) + b; + d = Integers.RotateLeft((d + G(a, b, c) + X[6] + 0xc040b340), S22) + a; + c = Integers.RotateLeft((c + G(d, a, b) + X[11] + 0x265e5a51), S23) + d; + b = Integers.RotateLeft((b + G(c, d, a) + X[0] + 0xe9b6c7aa), S24) + c; + a = Integers.RotateLeft((a + G(b, c, d) + X[5] + 0xd62f105d), S21) + b; + d = Integers.RotateLeft((d + G(a, b, c) + X[10] + 0x02441453), S22) + a; + c = Integers.RotateLeft((c + G(d, a, b) + X[15] + 0xd8a1e681), S23) + d; + b = Integers.RotateLeft((b + G(c, d, a) + X[4] + 0xe7d3fbc8), S24) + c; + a = Integers.RotateLeft((a + G(b, c, d) + X[9] + 0x21e1cde6), S21) + b; + d = Integers.RotateLeft((d + G(a, b, c) + X[14] + 0xc33707d6), S22) + a; + c = Integers.RotateLeft((c + G(d, a, b) + X[3] + 0xf4d50d87), S23) + d; + b = Integers.RotateLeft((b + G(c, d, a) + X[8] + 0x455a14ed), S24) + c; + a = Integers.RotateLeft((a + G(b, c, d) + X[13] + 0xa9e3e905), S21) + b; + d = Integers.RotateLeft((d + G(a, b, c) + X[2] + 0xfcefa3f8), S22) + a; + c = Integers.RotateLeft((c + G(d, a, b) + X[7] + 0x676f02d9), S23) + d; + b = Integers.RotateLeft((b + G(c, d, a) + X[12] + 0x8d2a4c8a), S24) + c; // // Round 3 - H cycle, 16 times. // - a = RotateLeft((a + H(b, c, d) + X[5] + 0xfffa3942), S31) + b; - d = RotateLeft((d + H(a, b, c) + X[8] + 0x8771f681), S32) + a; - c = RotateLeft((c + H(d, a, b) + X[11] + 0x6d9d6122), S33) + d; - b = RotateLeft((b + H(c, d, a) + X[14] + 0xfde5380c), S34) + c; - a = RotateLeft((a + H(b, c, d) + X[1] + 0xa4beea44), S31) + b; - d = RotateLeft((d + H(a, b, c) + X[4] + 0x4bdecfa9), S32) + a; - c = RotateLeft((c + H(d, a, b) + X[7] + 0xf6bb4b60), S33) + d; - b = RotateLeft((b + H(c, d, a) + X[10] + 0xbebfbc70), S34) + c; - a = RotateLeft((a + H(b, c, d) + X[13] + 0x289b7ec6), S31) + b; - d = RotateLeft((d + H(a, b, c) + X[0] + 0xeaa127fa), S32) + a; - c = RotateLeft((c + H(d, a, b) + X[3] + 0xd4ef3085), S33) + d; - b = RotateLeft((b + H(c, d, a) + X[6] + 0x04881d05), S34) + c; - a = RotateLeft((a + H(b, c, d) + X[9] + 0xd9d4d039), S31) + b; - d = RotateLeft((d + H(a, b, c) + X[12] + 0xe6db99e5), S32) + a; - c = RotateLeft((c + H(d, a, b) + X[15] + 0x1fa27cf8), S33) + d; - b = RotateLeft((b + H(c, d, a) + X[2] + 0xc4ac5665), S34) + c; + a = Integers.RotateLeft((a + H(b, c, d) + X[5] + 0xfffa3942), S31) + b; + d = Integers.RotateLeft((d + H(a, b, c) + X[8] + 0x8771f681), S32) + a; + c = Integers.RotateLeft((c + H(d, a, b) + X[11] + 0x6d9d6122), S33) + d; + b = Integers.RotateLeft((b + H(c, d, a) + X[14] + 0xfde5380c), S34) + c; + a = Integers.RotateLeft((a + H(b, c, d) + X[1] + 0xa4beea44), S31) + b; + d = Integers.RotateLeft((d + H(a, b, c) + X[4] + 0x4bdecfa9), S32) + a; + c = Integers.RotateLeft((c + H(d, a, b) + X[7] + 0xf6bb4b60), S33) + d; + b = Integers.RotateLeft((b + H(c, d, a) + X[10] + 0xbebfbc70), S34) + c; + a = Integers.RotateLeft((a + H(b, c, d) + X[13] + 0x289b7ec6), S31) + b; + d = Integers.RotateLeft((d + H(a, b, c) + X[0] + 0xeaa127fa), S32) + a; + c = Integers.RotateLeft((c + H(d, a, b) + X[3] + 0xd4ef3085), S33) + d; + b = Integers.RotateLeft((b + H(c, d, a) + X[6] + 0x04881d05), S34) + c; + a = Integers.RotateLeft((a + H(b, c, d) + X[9] + 0xd9d4d039), S31) + b; + d = Integers.RotateLeft((d + H(a, b, c) + X[12] + 0xe6db99e5), S32) + a; + c = Integers.RotateLeft((c + H(d, a, b) + X[15] + 0x1fa27cf8), S33) + d; + b = Integers.RotateLeft((b + H(c, d, a) + X[2] + 0xc4ac5665), S34) + c; // // Round 4 - K cycle, 16 times. // - a = RotateLeft((a + K(b, c, d) + X[0] + 0xf4292244), S41) + b; - d = RotateLeft((d + K(a, b, c) + X[7] + 0x432aff97), S42) + a; - c = RotateLeft((c + K(d, a, b) + X[14] + 0xab9423a7), S43) + d; - b = RotateLeft((b + K(c, d, a) + X[5] + 0xfc93a039), S44) + c; - a = RotateLeft((a + K(b, c, d) + X[12] + 0x655b59c3), S41) + b; - d = RotateLeft((d + K(a, b, c) + X[3] + 0x8f0ccc92), S42) + a; - c = RotateLeft((c + K(d, a, b) + X[10] + 0xffeff47d), S43) + d; - b = RotateLeft((b + K(c, d, a) + X[1] + 0x85845dd1), S44) + c; - a = RotateLeft((a + K(b, c, d) + X[8] + 0x6fa87e4f), S41) + b; - d = RotateLeft((d + K(a, b, c) + X[15] + 0xfe2ce6e0), S42) + a; - c = RotateLeft((c + K(d, a, b) + X[6] + 0xa3014314), S43) + d; - b = RotateLeft((b + K(c, d, a) + X[13] + 0x4e0811a1), S44) + c; - a = RotateLeft((a + K(b, c, d) + X[4] + 0xf7537e82), S41) + b; - d = RotateLeft((d + K(a, b, c) + X[11] + 0xbd3af235), S42) + a; - c = RotateLeft((c + K(d, a, b) + X[2] + 0x2ad7d2bb), S43) + d; - b = RotateLeft((b + K(c, d, a) + X[9] + 0xeb86d391), S44) + c; + a = Integers.RotateLeft((a + K(b, c, d) + X[0] + 0xf4292244), S41) + b; + d = Integers.RotateLeft((d + K(a, b, c) + X[7] + 0x432aff97), S42) + a; + c = Integers.RotateLeft((c + K(d, a, b) + X[14] + 0xab9423a7), S43) + d; + b = Integers.RotateLeft((b + K(c, d, a) + X[5] + 0xfc93a039), S44) + c; + a = Integers.RotateLeft((a + K(b, c, d) + X[12] + 0x655b59c3), S41) + b; + d = Integers.RotateLeft((d + K(a, b, c) + X[3] + 0x8f0ccc92), S42) + a; + c = Integers.RotateLeft((c + K(d, a, b) + X[10] + 0xffeff47d), S43) + d; + b = Integers.RotateLeft((b + K(c, d, a) + X[1] + 0x85845dd1), S44) + c; + a = Integers.RotateLeft((a + K(b, c, d) + X[8] + 0x6fa87e4f), S41) + b; + d = Integers.RotateLeft((d + K(a, b, c) + X[15] + 0xfe2ce6e0), S42) + a; + c = Integers.RotateLeft((c + K(d, a, b) + X[6] + 0xa3014314), S43) + d; + b = Integers.RotateLeft((b + K(c, d, a) + X[13] + 0x4e0811a1), S44) + c; + a = Integers.RotateLeft((a + K(b, c, d) + X[4] + 0xf7537e82), S41) + b; + d = Integers.RotateLeft((d + K(a, b, c) + X[11] + 0xbd3af235), S42) + a; + c = Integers.RotateLeft((c + K(d, a, b) + X[2] + 0x2ad7d2bb), S43) + d; + b = Integers.RotateLeft((b + K(c, d, a) + X[9] + 0xeb86d391), S44) + c; H1 += a; H2 += b; @@ -332,8 +322,5 @@ namespace Org.BouncyCastle.Crypto.Digests CopyIn(d); } - } - } - diff --git a/crypto/src/crypto/encodings/OaepEncoding.cs b/crypto/src/crypto/encodings/OaepEncoding.cs index a0ae7d1e6..9ddaec779 100644 --- a/crypto/src/crypto/encodings/OaepEncoding.cs +++ b/crypto/src/crypto/encodings/OaepEncoding.cs @@ -285,24 +285,17 @@ namespace Org.BouncyCastle.Crypto.Encodings return output; } - private byte[] MaskGeneratorFunction( - byte[] Z, - int zOff, - int zLen, - int length) + private byte[] MaskGeneratorFunction(byte[] Z, int zOff, int zLen, int length) { - if (mgf1Hash is IXof) + if (mgf1Hash is IXof xof) { byte[] mask = new byte[length]; - mgf1Hash.BlockUpdate(Z, zOff, zLen); - ((IXof)mgf1Hash).OutputFinal(mask, 0, mask.Length); - + xof.BlockUpdate(Z, zOff, zLen); + xof.OutputFinal(mask, 0, length); return mask; } - else - { - return MaskGeneratorFunction1(Z, zOff, zLen, length); - } + + return MaskGeneratorFunction1(Z, zOff, zLen, length); } /** diff --git a/crypto/src/crypto/generators/ECKeyPairGenerator.cs b/crypto/src/crypto/generators/ECKeyPairGenerator.cs index 6aba6921e..9ef5cdefd 100644 --- a/crypto/src/crypto/generators/ECKeyPairGenerator.cs +++ b/crypto/src/crypto/generators/ECKeyPairGenerator.cs @@ -50,26 +50,26 @@ namespace Org.BouncyCastle.Crypto.Generators DerObjectIdentifier oid; switch (parameters.Strength) { - case 192: - oid = X9ObjectIdentifiers.Prime192v1; - break; - case 224: - oid = SecObjectIdentifiers.SecP224r1; - break; - case 239: - oid = X9ObjectIdentifiers.Prime239v1; - break; - case 256: - oid = X9ObjectIdentifiers.Prime256v1; - break; - case 384: - oid = SecObjectIdentifiers.SecP384r1; - break; - case 521: - oid = SecObjectIdentifiers.SecP521r1; - break; - default: - throw new InvalidParameterException("unknown key size."); + case 192: + oid = X9ObjectIdentifiers.Prime192v1; + break; + case 224: + oid = SecObjectIdentifiers.SecP224r1; + break; + case 239: + oid = X9ObjectIdentifiers.Prime239v1; + break; + case 256: + oid = X9ObjectIdentifiers.Prime256v1; + break; + case 384: + oid = SecObjectIdentifiers.SecP384r1; + break; + case 521: + oid = SecObjectIdentifiers.SecP521r1; + break; + default: + throw new InvalidParameterException("unknown key size."); } X9ECParameters ecps = FindECCurveByOid(oid); @@ -131,42 +131,22 @@ namespace Org.BouncyCastle.Crypto.Generators internal static X9ECParameters FindECCurveByName(string name) { - X9ECParameters ecP = CustomNamedCurves.GetByName(name); - if (ecP == null) - { - ecP = ECNamedCurveTable.GetByName(name); - } - return ecP; + return CustomNamedCurves.GetByName(name) ?? ECNamedCurveTable.GetByName(name); } internal static X9ECParametersHolder FindECCurveByNameLazy(string name) { - X9ECParametersHolder holder = CustomNamedCurves.GetByNameLazy(name); - if (holder == null) - { - holder = ECNamedCurveTable.GetByNameLazy(name); - } - return holder; + return CustomNamedCurves.GetByNameLazy(name) ?? ECNamedCurveTable.GetByNameLazy(name); } internal static X9ECParameters FindECCurveByOid(DerObjectIdentifier oid) { - X9ECParameters ecP = CustomNamedCurves.GetByOid(oid); - if (ecP == null) - { - ecP = ECNamedCurveTable.GetByOid(oid); - } - return ecP; + return CustomNamedCurves.GetByOid(oid) ?? ECNamedCurveTable.GetByOid(oid); } internal static X9ECParametersHolder FindECCurveByOidLazy(DerObjectIdentifier oid) { - X9ECParametersHolder holder = CustomNamedCurves.GetByOidLazy(oid); - if (holder == null) - { - holder = ECNamedCurveTable.GetByOidLazy(oid); - } - return holder; + return CustomNamedCurves.GetByOidLazy(oid) ?? ECNamedCurveTable.GetByOidLazy(oid); } internal static ECPublicKeyParameters GetCorrespondingPublicKey( diff --git a/crypto/src/crypto/modes/GCMBlockCipher.cs b/crypto/src/crypto/modes/GCMBlockCipher.cs index f75235cf2..aed9ef311 100644 --- a/crypto/src/crypto/modes/GCMBlockCipher.cs +++ b/crypto/src/crypto/modes/GCMBlockCipher.cs @@ -108,30 +108,24 @@ namespace Org.BouncyCastle.Crypto.Modes KeyParameter keyParam; byte[] newNonce; - if (parameters is AeadParameters) + if (parameters is AeadParameters aeadParameters) { - AeadParameters param = (AeadParameters)parameters; + newNonce = aeadParameters.GetNonce(); + initialAssociatedText = aeadParameters.GetAssociatedText(); - newNonce = param.GetNonce(); - initialAssociatedText = param.GetAssociatedText(); - - int macSizeBits = param.MacSize; + int macSizeBits = aeadParameters.MacSize; if (macSizeBits < 32 || macSizeBits > 128 || macSizeBits % 8 != 0) - { throw new ArgumentException("Invalid value for MAC size: " + macSizeBits); - } macSize = macSizeBits / 8; - keyParam = param.Key; + keyParam = aeadParameters.Key; } - else if (parameters is ParametersWithIV) + else if (parameters is ParametersWithIV withIV) { - ParametersWithIV param = (ParametersWithIV)parameters; - - newNonce = param.GetIV(); + newNonce = withIV.GetIV(); initialAssociatedText = null; macSize = 16; - keyParam = (KeyParameter)param.Parameters; + keyParam = (KeyParameter)withIV.Parameters; } else { @@ -142,22 +136,17 @@ namespace Org.BouncyCastle.Crypto.Modes this.bufBlock = new byte[bufLength]; if (newNonce == null || newNonce.Length < 1) - { throw new ArgumentException("IV must be at least 1 byte"); - } if (forEncryption) { if (nonce != null && Arrays.AreEqual(nonce, newNonce)) { if (keyParam == null) - { throw new ArgumentException("cannot reuse nonce for GCM encryption"); - } + if (lastKey != null && Arrays.AreEqual(lastKey, keyParam.GetKey())) - { throw new ArgumentException("cannot reuse nonce for GCM encryption"); - } } } @@ -223,9 +212,7 @@ namespace Org.BouncyCastle.Crypto.Modes public byte[] GetMac() { - return macBlock == null - ? new byte[macSize] - : Arrays.Clone(macBlock); + return macBlock == null ? new byte[macSize] : (byte[])macBlock.Clone(); } public int GetOutputSize(int len) @@ -233,9 +220,7 @@ namespace Org.BouncyCastle.Crypto.Modes int totalData = len + bufOff; if (forEncryption) - { return totalData + macSize; - } return totalData < macSize ? 0 : totalData - macSize; } @@ -246,9 +231,8 @@ namespace Org.BouncyCastle.Crypto.Modes if (!forEncryption) { if (totalData < macSize) - { return 0; - } + totalData -= macSize; } return totalData - totalData % BlockSize; @@ -1490,9 +1474,8 @@ namespace Org.BouncyCastle.Crypto.Modes if (!initialised) { if (forEncryption) - { throw new InvalidOperationException("GCM cipher cannot be reused for encryption"); - } + throw new InvalidOperationException("GCM cipher needs to be initialised"); } } diff --git a/crypto/src/crypto/modes/gcm/GcmUtilities.cs b/crypto/src/crypto/modes/gcm/GcmUtilities.cs index 97b34fb61..a239e9ec0 100644 --- a/crypto/src/crypto/modes/gcm/GcmUtilities.cs +++ b/crypto/src/crypto/modes/gcm/GcmUtilities.cs @@ -14,7 +14,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Modes.Gcm { - internal abstract class GcmUtilities + internal static class GcmUtilities { internal struct FieldElement { @@ -177,13 +177,13 @@ namespace Org.BouncyCastle.Crypto.Modes.Gcm ulong z1 = Interleave.Expand64To128Rev(x.n0, out ulong z0); ulong z3 = Interleave.Expand64To128Rev(x.n1, out ulong z2); - Debug.Assert(z3 << 63 == 0); + Debug.Assert(z3 << 63 == 0UL); z1 ^= z3 ^ (z3 >> 1) ^ (z3 >> 2) ^ (z3 >> 7); // z2 ^= (z3 << 63) ^ (z3 << 62) ^ (z3 << 57); z2 ^= (z3 << 62) ^ (z3 << 57); - Debug.Assert(z2 << 63 == 0); + Debug.Assert(z2 << 63 == 0UL); z0 ^= z2 ^ (z2 >> 1) ^ (z2 >> 2) ^ (z2 >> 7); // z1 ^= (z2 << 63) ^ (z2 << 62) ^ (z2 << 57); diff --git a/crypto/src/crypto/signers/Ed25519phSigner.cs b/crypto/src/crypto/signers/Ed25519phSigner.cs index 0416aa5a5..60bf3376c 100644 --- a/crypto/src/crypto/signers/Ed25519phSigner.cs +++ b/crypto/src/crypto/signers/Ed25519phSigner.cs @@ -72,7 +72,7 @@ namespace Org.BouncyCastle.Crypto.Signers byte[] msg = new byte[Ed25519.PrehashSize]; if (Ed25519.PrehashSize != prehash.DoFinal(msg, 0)) - throw new InvalidOperationException("Prehash digest failed"); + throw new InvalidOperationException("Prehash calculation failed"); byte[] signature = new byte[Ed25519PrivateKeyParameters.SignatureSize]; privateKey.Sign(Ed25519.Algorithm.Ed25519ph, context, msg, 0, Ed25519.PrehashSize, signature, 0); @@ -91,7 +91,7 @@ namespace Org.BouncyCastle.Crypto.Signers byte[] msg = new byte[Ed25519.PrehashSize]; if (Ed25519.PrehashSize != prehash.DoFinal(msg, 0)) - throw new InvalidOperationException("Prehash digest failed"); + throw new InvalidOperationException("Prehash calculation failed"); return publicKey.Verify(Ed25519.Algorithm.Ed25519ph, context, msg, 0, Ed25519.PrehashSize, signature, 0); } diff --git a/crypto/src/crypto/signers/Ed448phSigner.cs b/crypto/src/crypto/signers/Ed448phSigner.cs index 2600af45f..02d65b6fb 100644 --- a/crypto/src/crypto/signers/Ed448phSigner.cs +++ b/crypto/src/crypto/signers/Ed448phSigner.cs @@ -72,7 +72,7 @@ namespace Org.BouncyCastle.Crypto.Signers byte[] msg = new byte[Ed448.PrehashSize]; if (Ed448.PrehashSize != prehash.OutputFinal(msg, 0, Ed448.PrehashSize)) - throw new InvalidOperationException("Prehash digest failed"); + throw new InvalidOperationException("Prehash calculation failed"); byte[] signature = new byte[Ed448PrivateKeyParameters.SignatureSize]; privateKey.Sign(Ed448.Algorithm.Ed448ph, context, msg, 0, Ed448.PrehashSize, signature, 0); @@ -91,7 +91,7 @@ namespace Org.BouncyCastle.Crypto.Signers byte[] msg = new byte[Ed448.PrehashSize]; if (Ed448.PrehashSize != prehash.OutputFinal(msg, 0, Ed448.PrehashSize)) - throw new InvalidOperationException("Prehash digest failed"); + throw new InvalidOperationException("Prehash calculation failed"); return publicKey.Verify(Ed448.Algorithm.Ed448ph, context, msg, 0, Ed448.PrehashSize, signature, 0); } diff --git a/crypto/src/crypto/signers/IsoTrailers.cs b/crypto/src/crypto/signers/IsoTrailers.cs index 61006b848..83b9c192d 100644 --- a/crypto/src/crypto/signers/IsoTrailers.cs +++ b/crypto/src/crypto/signers/IsoTrailers.cs @@ -42,7 +42,10 @@ namespace Org.BouncyCastle.Crypto.Signers public static int GetTrailer(IDigest digest) { - return TrailerMap[digest.AlgorithmName]; + if (TrailerMap.TryGetValue(digest.AlgorithmName, out var trailer)) + return trailer; + + throw new InvalidOperationException("No trailer for digest"); } public static bool NoTrailerAvailable(IDigest digest) diff --git a/crypto/src/crypto/signers/PssSigner.cs b/crypto/src/crypto/signers/PssSigner.cs index 9bb2a7d37..c1613c8d1 100644 --- a/crypto/src/crypto/signers/PssSigner.cs +++ b/crypto/src/crypto/signers/PssSigner.cs @@ -343,24 +343,17 @@ namespace Org.BouncyCastle.Crypto.Signers sp[3] = (byte)((uint) i >> 0); } - private byte[] MaskGeneratorFunction( - byte[] Z, - int zOff, - int zLen, - int length) - { - if (mgfDigest is IXof) + private byte[] MaskGeneratorFunction(byte[] Z, int zOff, int zLen, int length) + { + if (mgfDigest is IXof xof) { byte[] mask = new byte[length]; - mgfDigest.BlockUpdate(Z, zOff, zLen); - ((IXof)mgfDigest).OutputFinal(mask, 0, mask.Length); - + xof.BlockUpdate(Z, zOff, zLen); + xof.OutputFinal(mask, 0, mask.Length); return mask; } - else - { - return MaskGeneratorFunction1(Z, zOff, zLen, length); - } + + return MaskGeneratorFunction1(Z, zOff, zLen, length); } /// mask generator function, as described in Pkcs1v2. diff --git a/crypto/src/math/ec/ECPoint.cs b/crypto/src/math/ec/ECPoint.cs index 1329ea0d0..4607c8cfe 100644 --- a/crypto/src/math/ec/ECPoint.cs +++ b/crypto/src/math/ec/ECPoint.cs @@ -487,11 +487,7 @@ namespace Org.BouncyCastle.Math.EC public PreCompInfo Precompute(PreCompInfo existing) { - ValidityPreCompInfo info = existing as ValidityPreCompInfo; - if (info == null) - { - info = new ValidityPreCompInfo(); - } + ValidityPreCompInfo info = existing as ValidityPreCompInfo ?? new ValidityPreCompInfo(); if (info.HasFailed()) return info; diff --git a/crypto/src/math/ec/abc/Tnaf.cs b/crypto/src/math/ec/abc/Tnaf.cs index fd073bb7b..88a4eeb96 100644 --- a/crypto/src/math/ec/abc/Tnaf.cs +++ b/crypto/src/math/ec/abc/Tnaf.cs @@ -13,7 +13,7 @@ namespace Org.BouncyCastle.Math.EC.Abc * by Jerome A. Solinas. The paper first appeared in the Proceedings of * Crypto 1997. */ - internal class Tnaf + internal static class Tnaf { private static readonly BigInteger MinusOne = BigInteger.One.Negate(); private static readonly BigInteger MinusTwo = BigInteger.Two.Negate(); @@ -552,7 +552,7 @@ namespace Org.BouncyCastle.Math.EC.Abc return new BigInteger[] { dividend0, dividend1 }; } - protected static int GetShiftsForCofactor(BigInteger h) + private static int GetShiftsForCofactor(BigInteger h) { if (h != null && h.BitLength < 4) { diff --git a/crypto/src/openpgp/PgpUtilities.cs b/crypto/src/openpgp/PgpUtilities.cs index f400d36cc..8b8f7d9c5 100644 --- a/crypto/src/openpgp/PgpUtilities.cs +++ b/crypto/src/openpgp/PgpUtilities.cs @@ -51,10 +51,6 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp return d; } - private PgpUtilities() - { - } - public static MPInteger[] DsaSigToMpi( byte[] encoding) { @@ -89,24 +85,24 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp { switch (hashAlgorithm) { - case HashAlgorithmTag.Sha1: - return "SHA1"; - case HashAlgorithmTag.MD2: - return "MD2"; - case HashAlgorithmTag.MD5: - return "MD5"; - case HashAlgorithmTag.RipeMD160: - return "RIPEMD160"; - case HashAlgorithmTag.Sha224: - return "SHA224"; - case HashAlgorithmTag.Sha256: - return "SHA256"; - case HashAlgorithmTag.Sha384: - return "SHA384"; - case HashAlgorithmTag.Sha512: - return "SHA512"; - default: - throw new PgpException("unknown hash algorithm tag in GetDigestName: " + hashAlgorithm); + case HashAlgorithmTag.Sha1: + return "SHA1"; + case HashAlgorithmTag.MD2: + return "MD2"; + case HashAlgorithmTag.MD5: + return "MD5"; + case HashAlgorithmTag.RipeMD160: + return "RIPEMD160"; + case HashAlgorithmTag.Sha224: + return "SHA224"; + case HashAlgorithmTag.Sha256: + return "SHA256"; + case HashAlgorithmTag.Sha384: + return "SHA384"; + case HashAlgorithmTag.Sha512: + return "SHA512"; + default: + throw new PgpException("unknown hash algorithm tag in GetDigestName: " + hashAlgorithm); } } @@ -140,28 +136,28 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp string encAlg; switch (keyAlgorithm) { - case PublicKeyAlgorithmTag.RsaGeneral: - case PublicKeyAlgorithmTag.RsaSign: - encAlg = "RSA"; - break; - case PublicKeyAlgorithmTag.Dsa: - encAlg = "DSA"; - break; - case PublicKeyAlgorithmTag.ECDH: - encAlg = "ECDH"; - break; - case PublicKeyAlgorithmTag.ECDsa: - encAlg = "ECDSA"; - break; - case PublicKeyAlgorithmTag.EdDsa: - encAlg = "EdDSA"; - break; - case PublicKeyAlgorithmTag.ElGamalEncrypt: // in some malformed cases. - case PublicKeyAlgorithmTag.ElGamalGeneral: - encAlg = "ElGamal"; - break; - default: - throw new PgpException("unknown algorithm tag in signature:" + keyAlgorithm); + case PublicKeyAlgorithmTag.RsaGeneral: + case PublicKeyAlgorithmTag.RsaSign: + encAlg = "RSA"; + break; + case PublicKeyAlgorithmTag.Dsa: + encAlg = "DSA"; + break; + case PublicKeyAlgorithmTag.ECDH: + encAlg = "ECDH"; + break; + case PublicKeyAlgorithmTag.ECDsa: + encAlg = "ECDSA"; + break; + case PublicKeyAlgorithmTag.EdDsa: + encAlg = "EdDSA"; + break; + case PublicKeyAlgorithmTag.ElGamalEncrypt: // in some malformed cases. + case PublicKeyAlgorithmTag.ElGamalGeneral: + encAlg = "ElGamal"; + break; + default: + throw new PgpException("unknown algorithm tag in signature:" + keyAlgorithm); } return GetDigestName(hashAlgorithm) + "with" + encAlg; @@ -172,36 +168,36 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp { switch (algorithm) { - case SymmetricKeyAlgorithmTag.Null: - return null; - case SymmetricKeyAlgorithmTag.TripleDes: - return "DESEDE"; - case SymmetricKeyAlgorithmTag.Idea: - return "IDEA"; - case SymmetricKeyAlgorithmTag.Cast5: - return "CAST5"; - case SymmetricKeyAlgorithmTag.Blowfish: - return "Blowfish"; - case SymmetricKeyAlgorithmTag.Safer: - return "SAFER"; - case SymmetricKeyAlgorithmTag.Des: - return "DES"; - case SymmetricKeyAlgorithmTag.Aes128: - return "AES"; - case SymmetricKeyAlgorithmTag.Aes192: - return "AES"; - case SymmetricKeyAlgorithmTag.Aes256: - return "AES"; - case SymmetricKeyAlgorithmTag.Twofish: - return "Twofish"; - case SymmetricKeyAlgorithmTag.Camellia128: - return "Camellia"; - case SymmetricKeyAlgorithmTag.Camellia192: - return "Camellia"; - case SymmetricKeyAlgorithmTag.Camellia256: - return "Camellia"; - default: - throw new PgpException("unknown symmetric algorithm: " + algorithm); + case SymmetricKeyAlgorithmTag.Null: + return null; + case SymmetricKeyAlgorithmTag.TripleDes: + return "DESEDE"; + case SymmetricKeyAlgorithmTag.Idea: + return "IDEA"; + case SymmetricKeyAlgorithmTag.Cast5: + return "CAST5"; + case SymmetricKeyAlgorithmTag.Blowfish: + return "Blowfish"; + case SymmetricKeyAlgorithmTag.Safer: + return "SAFER"; + case SymmetricKeyAlgorithmTag.Des: + return "DES"; + case SymmetricKeyAlgorithmTag.Aes128: + return "AES"; + case SymmetricKeyAlgorithmTag.Aes192: + return "AES"; + case SymmetricKeyAlgorithmTag.Aes256: + return "AES"; + case SymmetricKeyAlgorithmTag.Twofish: + return "Twofish"; + case SymmetricKeyAlgorithmTag.Camellia128: + return "Camellia"; + case SymmetricKeyAlgorithmTag.Camellia192: + return "Camellia"; + case SymmetricKeyAlgorithmTag.Camellia256: + return "Camellia"; + default: + throw new PgpException("unknown symmetric algorithm: " + algorithm); } } @@ -210,29 +206,29 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp int keySize; switch (algorithm) { - case SymmetricKeyAlgorithmTag.Des: - keySize = 64; - break; - case SymmetricKeyAlgorithmTag.Idea: - case SymmetricKeyAlgorithmTag.Cast5: - case SymmetricKeyAlgorithmTag.Blowfish: - case SymmetricKeyAlgorithmTag.Safer: - case SymmetricKeyAlgorithmTag.Aes128: - case SymmetricKeyAlgorithmTag.Camellia128: - keySize = 128; - break; - case SymmetricKeyAlgorithmTag.TripleDes: - case SymmetricKeyAlgorithmTag.Aes192: - case SymmetricKeyAlgorithmTag.Camellia192: - keySize = 192; - break; - case SymmetricKeyAlgorithmTag.Aes256: - case SymmetricKeyAlgorithmTag.Twofish: - case SymmetricKeyAlgorithmTag.Camellia256: - keySize = 256; - break; - default: - throw new PgpException("unknown symmetric algorithm: " + algorithm); + case SymmetricKeyAlgorithmTag.Des: + keySize = 64; + break; + case SymmetricKeyAlgorithmTag.Idea: + case SymmetricKeyAlgorithmTag.Cast5: + case SymmetricKeyAlgorithmTag.Blowfish: + case SymmetricKeyAlgorithmTag.Safer: + case SymmetricKeyAlgorithmTag.Aes128: + case SymmetricKeyAlgorithmTag.Camellia128: + keySize = 128; + break; + case SymmetricKeyAlgorithmTag.TripleDes: + case SymmetricKeyAlgorithmTag.Aes192: + case SymmetricKeyAlgorithmTag.Camellia192: + keySize = 192; + break; + case SymmetricKeyAlgorithmTag.Aes256: + case SymmetricKeyAlgorithmTag.Twofish: + case SymmetricKeyAlgorithmTag.Camellia256: + keySize = 256; + break; + default: + throw new PgpException("unknown symmetric algorithm: " + algorithm); } return keySize; @@ -323,47 +319,47 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp switch (s2k.Type) { - case S2k.Simple: - digest.BlockUpdate(pBytes, 0, pBytes.Length); - break; - case S2k.Salted: - digest.BlockUpdate(iv, 0, iv.Length); - digest.BlockUpdate(pBytes, 0, pBytes.Length); - break; - case S2k.SaltedAndIterated: - long count = s2k.IterationCount; - digest.BlockUpdate(iv, 0, iv.Length); - digest.BlockUpdate(pBytes, 0, pBytes.Length); - - count -= iv.Length + pBytes.Length; - - while (count > 0) + case S2k.Simple: + digest.BlockUpdate(pBytes, 0, pBytes.Length); + break; + case S2k.Salted: + digest.BlockUpdate(iv, 0, iv.Length); + digest.BlockUpdate(pBytes, 0, pBytes.Length); + break; + case S2k.SaltedAndIterated: + long count = s2k.IterationCount; + digest.BlockUpdate(iv, 0, iv.Length); + digest.BlockUpdate(pBytes, 0, pBytes.Length); + + count -= iv.Length + pBytes.Length; + + while (count > 0) + { + if (count < iv.Length) + { + digest.BlockUpdate(iv, 0, (int)count); + break; + } + else + { + digest.BlockUpdate(iv, 0, iv.Length); + count -= iv.Length; + } + + if (count < pBytes.Length) + { + digest.BlockUpdate(pBytes, 0, (int)count); + count = 0; + } + else { - if (count < iv.Length) - { - digest.BlockUpdate(iv, 0, (int)count); - break; - } - else - { - digest.BlockUpdate(iv, 0, iv.Length); - count -= iv.Length; - } - - if (count < pBytes.Length) - { - digest.BlockUpdate(pBytes, 0, (int)count); - count = 0; - } - else - { - digest.BlockUpdate(pBytes, 0, pBytes.Length); - count -= pBytes.Length; - } + digest.BlockUpdate(pBytes, 0, pBytes.Length); + count -= pBytes.Length; } - break; - default: - throw new PgpException("unknown S2k type: " + s2k.Type); + } + break; + default: + throw new PgpException("unknown S2k type: " + s2k.Type); } } else diff --git a/crypto/src/pkix/PkixCertPath.cs b/crypto/src/pkix/PkixCertPath.cs index 7f04b1b63..a2ea3074d 100644 --- a/crypto/src/pkix/PkixCertPath.cs +++ b/crypto/src/pkix/PkixCertPath.cs @@ -3,13 +3,13 @@ using System.Collections.Generic; using System.IO; using Org.BouncyCastle.Asn1; -using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Asn1.Pkcs; -using Org.BouncyCastle.X509; +using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.OpenSsl; using Org.BouncyCastle.Security.Certificates; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; +using Org.BouncyCastle.X509; namespace Org.BouncyCastle.Pkix { @@ -78,7 +78,7 @@ namespace Org.BouncyCastle.Pkix public class PkixCertPath // : CertPath { - internal static readonly List m_encodings = new List{ "PkiPath", "PEM", "PKCS7" }; + private static readonly List EncodingNames = new List{ "PkiPath", "PEM", "PKCS7" }; private readonly IList m_certificates; @@ -186,31 +186,24 @@ namespace Org.BouncyCastle.Pkix **/ public PkixCertPath(Stream inStream, string encoding) { - //string upper = Platform.ToUpperInvariant(encoding); - IList certs; try { if (Platform.EqualsIgnoreCase("PkiPath", encoding)) { Asn1InputStream derInStream = new Asn1InputStream(inStream); - Asn1Object derObject = derInStream.ReadObject(); - if (!(derObject is Asn1Sequence)) - { - throw new CertificateException( + if (!(derInStream.ReadObject() is Asn1Sequence asn1Sequence)) + { + throw new CertificateException( "input stream does not contain a ASN1 SEQUENCE while reading PkiPath encoded data to load CertPath"); } - certs = new List(); + var certArray = asn1Sequence.MapElements( + element => new X509Certificate(X509CertificateStructure.GetInstance(element.ToAsn1Object()))); - foreach (Asn1Encodable ae in (Asn1Sequence)derObject) - { - byte[] derBytes = ae.GetEncoded(Asn1Encodable.Der); - Stream certInStream = new MemoryStream(derBytes, false); + Array.Reverse(certArray); - // TODO Is inserting at the front important (list will be sorted later anyway)? - certs.Insert(0, new X509CertificateParser().ReadCertificate(certInStream)); - } + certs = new List(certArray); } else if (Platform.EqualsIgnoreCase("PEM", encoding) || Platform.EqualsIgnoreCase("PKCS7", encoding)) @@ -242,7 +235,7 @@ namespace Org.BouncyCastle.Pkix **/ public virtual IEnumerable Encodings { - get { return CollectionUtilities.Proxy(m_encodings); } + get { return CollectionUtilities.Proxy(EncodingNames); } } /** @@ -304,7 +297,7 @@ namespace Org.BouncyCastle.Pkix **/ public virtual byte[] GetEncoded() { - return GetEncoded(m_encodings[0]); + return GetEncoded(EncodingNames[0]); } /** diff --git a/crypto/src/pkix/PkixCertPathChecker.cs b/crypto/src/pkix/PkixCertPathChecker.cs index 08b7e3d41..856053d11 100644 --- a/crypto/src/pkix/PkixCertPathChecker.cs +++ b/crypto/src/pkix/PkixCertPathChecker.cs @@ -32,7 +32,6 @@ namespace Org.BouncyCastle.Pkix * checking must be supported */ public abstract void Init(bool forward); - //throws CertPathValidatorException; /** * Indicates if forward checking is supported. Forward checking refers to @@ -82,7 +81,6 @@ namespace Org.BouncyCastle.Pkix * if the specified certificate does not pass the check */ public abstract void Check(X509Certificate cert, ISet unresolvedCritExts); - //throws CertPathValidatorException; /** * Returns a clone of this object. Calls the Object.clone() diff --git a/crypto/src/pkix/PkixCertPathValidator.cs b/crypto/src/pkix/PkixCertPathValidator.cs index 6fe3fd903..0c585f520 100644 --- a/crypto/src/pkix/PkixCertPathValidator.cs +++ b/crypto/src/pkix/PkixCertPathValidator.cs @@ -212,7 +212,7 @@ namespace Org.BouncyCastle.Pkix // var targetConstraints = paramsPkix.GetTargetConstraintsCert(); - if (targetConstraints != null && !targetConstraints.Match((X509Certificate)certs[0])) + if (targetConstraints != null && !targetConstraints.Match(certs[0])) { throw new PkixCertPathValidatorException( "Target certificate in certification path does not match targetConstraints.", null, 0); @@ -222,7 +222,7 @@ namespace Org.BouncyCastle.Pkix // initialize CertPathChecker's // var certPathCheckers = paramsPkix.GetCertPathCheckers(); - foreach (PkixCertPathChecker certPathChecker in certPathCheckers) + foreach (var certPathChecker in certPathCheckers) { certPathChecker.Init(false); } diff --git a/crypto/src/pkix/PkixCertPathValidatorUtilities.cs b/crypto/src/pkix/PkixCertPathValidatorUtilities.cs index e8105c485..efbf855ff 100644 --- a/crypto/src/pkix/PkixCertPathValidatorUtilities.cs +++ b/crypto/src/pkix/PkixCertPathValidatorUtilities.cs @@ -677,7 +677,7 @@ namespace Org.BouncyCastle.Pkix DistributionPoint dp, ICollection issuerPrincipals, X509CrlStoreSelector selector, - PkixParameters pkixParams) + PkixParameters pkixParameters) { var issuers = new List(); // indirect CRL @@ -778,7 +778,7 @@ namespace Org.BouncyCastle.Pkix * or no CRLs are found. */ internal static ISet GetCompleteCrls(DistributionPoint dp, object certObj, DateTime currentDate, - PkixParameters paramsPKIX) + PkixParameters pkixParameters) { var certObjIssuer = GetIssuerPrincipal(certObj); @@ -788,7 +788,7 @@ namespace Org.BouncyCastle.Pkix var issuers = new HashSet(); issuers.Add(certObjIssuer); - GetCrlIssuersFromDistributionPoint(dp, issuers, crlselect, paramsPKIX); + GetCrlIssuersFromDistributionPoint(dp, issuers, crlselect, pkixParameters); } catch (Exception e) { @@ -808,7 +808,7 @@ namespace Org.BouncyCastle.Pkix crlselect.CompleteCrlEnabled = true; - ISet crls = CrlUtilities.FindCrls(crlselect, paramsPKIX, currentDate); + ISet crls = CrlUtilities.FindCrls(crlselect, pkixParameters, currentDate); if (crls.Count < 1) throw new Exception("No CRLs found for issuer \"" + certObjIssuer + "\""); @@ -825,10 +825,8 @@ namespace Org.BouncyCastle.Pkix * @throws Exception if an exception occurs while picking the delta * CRLs. */ - internal static ISet GetDeltaCrls( - DateTime currentDate, - PkixParameters paramsPKIX, - X509Crl completeCRL) + internal static ISet GetDeltaCrls(DateTime currentDate, PkixParameters pkixParameters, + X509Crl completeCRL) { X509CrlStoreSelector deltaSelect = new X509CrlStoreSelector(); @@ -890,7 +888,7 @@ namespace Org.BouncyCastle.Pkix deltaSelect.MaxBaseCrlNumber = completeCRLNumber; // find delta CRLs - ISet temp = CrlUtilities.FindCrls(deltaSelect, paramsPKIX, currentDate); + ISet temp = CrlUtilities.FindCrls(deltaSelect, pkixParameters, currentDate); var result = new HashSet(); @@ -975,8 +973,8 @@ namespace Org.BouncyCastle.Pkix return false; } - internal static void ProcessCertD1ii(int index, IList[] policyNodes, - DerObjectIdentifier _poid, ISet _pq) + internal static void ProcessCertD1ii(int index, IList[] policyNodes, DerObjectIdentifier _poid, + ISet _pq) { foreach (var _node in policyNodes[index - 1]) { @@ -1007,9 +1005,8 @@ namespace Org.BouncyCastle.Pkix * @exception Exception * if an error occurs. */ - internal static HashSet FindIssuerCerts( - X509Certificate cert, - PkixBuilderParameters pkixParams) + internal static HashSet FindIssuerCerts(X509Certificate cert, + PkixBuilderParameters pkixBuilderParameters) { X509CertStoreSelector certSelector = new X509CertStoreSelector(); try @@ -1025,7 +1022,7 @@ namespace Org.BouncyCastle.Pkix var certs = new HashSet(); try { - CollectionUtilities.CollectMatches(certs, certSelector, pkixParams.GetStoresCert()); + CollectionUtilities.CollectMatches(certs, certSelector, pkixBuilderParameters.GetStoresCert()); } catch (Exception e) { diff --git a/crypto/src/pkix/PkixCrlUtilities.cs b/crypto/src/pkix/PkixCrlUtilities.cs index facbf56c2..3451b8ac0 100644 --- a/crypto/src/pkix/PkixCrlUtilities.cs +++ b/crypto/src/pkix/PkixCrlUtilities.cs @@ -9,22 +9,27 @@ namespace Org.BouncyCastle.Pkix { public class PkixCrlUtilities { - public virtual ISet FindCrls(X509CrlStoreSelector crlSelector, PkixParameters paramsPkix, + // TODO bc-fips-csharp implements this for ISelector, using optional ICheckingCertificate + public virtual ISet FindCrls(X509CrlStoreSelector crlSelector, PkixParameters paramsPkix) + { + // get complete CRL(s) + try + { + return FindCrls(crlSelector, paramsPkix.GetStoresCrl()); + } + catch (Exception e) + { + throw new Exception("Exception obtaining complete CRLs.", e); + } + } + + // TODO bc-fips-csharp implements this for ISelector, using optional ICheckingCertificate + public virtual ISet FindCrls(X509CrlStoreSelector crlSelector, PkixParameters paramsPkix, DateTime currentDate) { - HashSet initialSet; - - // get complete CRL(s) - try - { - initialSet = FindCrls(crlSelector, paramsPkix.GetStoresCrl()); - } - catch (Exception e) - { - throw new Exception("Exception obtaining complete CRLs.", e); - } + var initialSet = FindCrls(crlSelector, paramsPkix); - var finalSet = new HashSet(); + var finalSet = new HashSet(); DateTime validityDate = currentDate; if (paramsPkix.Date != null) @@ -32,15 +37,15 @@ namespace Org.BouncyCastle.Pkix validityDate = paramsPkix.Date.Value; } - // based on RFC 5280 6.3.3 - foreach (X509Crl crl in initialSet) + X509Certificate cert = crlSelector.CertificateChecking; + + // based on RFC 5280 6.3.3 + foreach (X509Crl crl in initialSet) { DateTime? nextUpdate = crl.NextUpdate; if (null == nextUpdate || nextUpdate.Value.CompareTo(validityDate) > 0) { - X509Certificate cert = crlSelector.CertificateChecking; - if (null == cert || crl.ThisUpdate.CompareTo(cert.NotAfter) < 0) { finalSet.Add(crl); @@ -51,19 +56,6 @@ namespace Org.BouncyCastle.Pkix return finalSet; } - public virtual ISet FindCrls(X509CrlStoreSelector crlSelector, PkixParameters paramsPkix) - { - // get complete CRL(s) - try - { - return FindCrls(crlSelector, paramsPkix.GetStoresCrl()); - } - catch (Exception e) - { - throw new Exception("Exception obtaining complete CRLs.", e); - } - } - /// /// crl checking /// Return a Collection of all CRLs found in the X509Store's that are @@ -76,7 +68,7 @@ namespace Org.BouncyCastle.Pkix /// a Collection of all found {@link X509CRL X509CRL} objects. May be /// empty but never null. /// - private HashSet FindCrls(ISelector crlSelector, IList> crlStores) + private HashSet FindCrls(ISelector crlSelector, IEnumerable> crlStores) { var crls = new HashSet(); diff --git a/crypto/src/pkix/Rfc3281CertPathUtilities.cs b/crypto/src/pkix/Rfc3281CertPathUtilities.cs index 4d12ad0c0..b0746bc83 100644 --- a/crypto/src/pkix/Rfc3281CertPathUtilities.cs +++ b/crypto/src/pkix/Rfc3281CertPathUtilities.cs @@ -253,26 +253,21 @@ namespace Org.BouncyCastle.Pkix } } - internal static void ProcessAttrCert4( - X509Certificate acIssuerCert, - PkixParameters pkixParams) + internal static void ProcessAttrCert4(X509Certificate acIssuerCert, PkixParameters pkixParams) { - var set = pkixParams.GetTrustedACIssuers(); - bool trusted = false; - foreach (TrustAnchor anchor in set) + foreach (var anchor in pkixParams.GetTrustedACIssuers()) { var symbols = X509Name.RFC2253Symbols; + if (acIssuerCert.SubjectDN.ToString(false, symbols).Equals(anchor.CAName) || acIssuerCert.Equals(anchor.TrustedCert)) { - trusted = true; + // Trusted + return; } } - if (!trusted) - { - throw new PkixCertPathValidatorException( - "Attribute certificate issuer is not directly trusted."); - } + + throw new PkixCertPathValidatorException("Attribute certificate issuer is not directly trusted."); } internal static void ProcessAttrCert3( diff --git a/crypto/src/util/collections/CollectionUtilities.cs b/crypto/src/util/collections/CollectionUtilities.cs index 26b3f2a1d..a1fb0e949 100644 --- a/crypto/src/util/collections/CollectionUtilities.cs +++ b/crypto/src/util/collections/CollectionUtilities.cs @@ -31,6 +31,19 @@ namespace Org.BouncyCastle.Utilities.Collections return new StoreImpl(contents); } + public static T GetFirstOrNull(IEnumerable e) + where T : class + { + if (e != null) + { + foreach (var t in e) + { + return t; + } + } + return null; + } + public static T GetValueOrKey(IDictionary d, T k) { return d.TryGetValue(k, out var v) ? v : k; diff --git a/crypto/src/x509/X509AttrCertParser.cs b/crypto/src/x509/X509AttrCertParser.cs index f1dc09543..0019a48eb 100644 --- a/crypto/src/x509/X509AttrCertParser.cs +++ b/crypto/src/x509/X509AttrCertParser.cs @@ -114,9 +114,7 @@ namespace Org.BouncyCastle.X509 if (sData != null) { if (sDataObjectCount != sData.Count) - { return GetCertificate(); - } sData = null; sDataObjectCount = 0; @@ -139,9 +137,7 @@ namespace Org.BouncyCastle.X509 } if (tag != 0x30) // assume ascii PEM encoded. - { return ReadPemCertificate(inStream); - } return ReadDerCertificate(new Asn1InputStream(inStream)); } diff --git a/crypto/src/x509/store/X509AttrCertStoreSelector.cs b/crypto/src/x509/store/X509AttrCertStoreSelector.cs index e68208c74..6b3c854f1 100644 --- a/crypto/src/x509/store/X509AttrCertStoreSelector.cs +++ b/crypto/src/x509/store/X509AttrCertStoreSelector.cs @@ -72,8 +72,7 @@ namespace Org.BouncyCastle.X509.Store if (targetNames.Count > 0 || targetGroups.Count > 0) { - Asn1OctetString targetInfoExt = attrCert.GetExtensionValue( - X509Extensions.TargetInformation); + Asn1OctetString targetInfoExt = attrCert.GetExtensionValue(X509Extensions.TargetInformation); if (targetInfoExt != null) { @@ -109,10 +108,9 @@ namespace Org.BouncyCastle.X509.Store } } } + if (!found) - { return false; - } } if (targetGroups.Count > 0) @@ -136,9 +134,7 @@ namespace Org.BouncyCastle.X509.Store } if (!found) - { return false; - } } } } @@ -204,8 +200,7 @@ namespace Org.BouncyCastle.X509.Store * * @param name The name as a GeneralName (not null) */ - public void AddTargetName( - GeneralName name) + public void AddTargetName(GeneralName name) { targetNames.Add(name); } @@ -338,18 +333,7 @@ namespace Org.BouncyCastle.X509.Store { foreach (object o in names) { - if (o is GeneralName gn) - { - result.Add(gn); - } - else if (o is byte[] bs) - { - result.Add(GeneralName.GetInstance(Asn1Object.FromByteArray(bs))); - } - else - { - throw new InvalidOperationException(); - } + result.Add(GeneralName.GetInstance(o)); } } -- cgit 1.4.1