summary refs log tree commit diff
path: root/crypto/src
diff options
context:
space:
mode:
Diffstat (limited to 'crypto/src')
-rw-r--r--crypto/src/AssemblyInfo.cs83
-rw-r--r--crypto/src/asn1/Asn1Object.cs13
-rw-r--r--crypto/src/asn1/Asn1OctetString.cs2
-rw-r--r--crypto/src/asn1/Asn1Sequence.cs4
-rw-r--r--crypto/src/asn1/Asn1Set.cs33
-rw-r--r--crypto/src/asn1/Asn1TaggedObject.cs2
-rw-r--r--crypto/src/asn1/BERBitString.cs43
-rw-r--r--crypto/src/asn1/BEROctetStringGenerator.cs18
-rw-r--r--crypto/src/asn1/BerTaggedObject.cs2
-rw-r--r--crypto/src/asn1/DerApplicationSpecific.cs2
-rw-r--r--crypto/src/asn1/DerBMPString.cs4
-rw-r--r--crypto/src/asn1/DerBitString.cs263
-rw-r--r--crypto/src/asn1/DerBoolean.cs4
-rw-r--r--crypto/src/asn1/DerEnumerated.cs2
-rw-r--r--crypto/src/asn1/DerGeneralString.cs2
-rw-r--r--crypto/src/asn1/DerGeneralizedTime.cs14
-rw-r--r--crypto/src/asn1/DerIA5String.cs2
-rw-r--r--crypto/src/asn1/DerInteger.cs2
-rw-r--r--crypto/src/asn1/DerNumericString.cs2
-rw-r--r--crypto/src/asn1/DerObjectIdentifier.cs4
-rw-r--r--crypto/src/asn1/DerOutputStream.cs19
-rw-r--r--crypto/src/asn1/DerPrintableString.cs2
-rw-r--r--crypto/src/asn1/DerSequence.cs7
-rw-r--r--crypto/src/asn1/DerSet.cs7
-rw-r--r--crypto/src/asn1/DerT61String.cs2
-rw-r--r--crypto/src/asn1/DerUTCTime.cs6
-rw-r--r--crypto/src/asn1/DerUTF8String.cs4
-rw-r--r--crypto/src/asn1/DerUniversalString.cs2
-rw-r--r--crypto/src/asn1/DerVisibleString.cs2
-rw-r--r--crypto/src/asn1/anssi/ANSSINamedCurves.cs4
-rw-r--r--crypto/src/asn1/cmp/CAKeyUpdAnnContent.cs4
-rw-r--r--crypto/src/asn1/cmp/CertConfirmContent.cs4
-rw-r--r--crypto/src/asn1/cmp/CertOrEncCert.cs3
-rw-r--r--crypto/src/asn1/cmp/CertRepMessage.cs4
-rw-r--r--crypto/src/asn1/cmp/CertResponse.cs7
-rw-r--r--crypto/src/asn1/cmp/CertStatus.cs3
-rw-r--r--crypto/src/asn1/cmp/CertifiedKeyPair.cs3
-rw-r--r--crypto/src/asn1/cmp/Challenge.cs3
-rw-r--r--crypto/src/asn1/cmp/CmpCertificate.cs3
-rw-r--r--crypto/src/asn1/cmp/CrlAnnContent.cs3
-rw-r--r--crypto/src/asn1/cmp/ErrorMsgContent.cs7
-rw-r--r--crypto/src/asn1/cmp/GenMsgContent.cs4
-rw-r--r--crypto/src/asn1/cmp/GenRepContent.cs4
-rw-r--r--crypto/src/asn1/cmp/InfoTypeAndValue.cs4
-rw-r--r--crypto/src/asn1/cmp/KeyRecRepContent.cs4
-rw-r--r--crypto/src/asn1/cmp/OobCertHash.cs3
-rw-r--r--crypto/src/asn1/cmp/PKIBody.cs3
-rw-r--r--crypto/src/asn1/cmp/PKIConfirmContent.cs4
-rw-r--r--crypto/src/asn1/cmp/PKIFailureInfo.cs121
-rw-r--r--crypto/src/asn1/cmp/PKIFreeText.cs4
-rw-r--r--crypto/src/asn1/cmp/PKIHeader.cs3
-rw-r--r--crypto/src/asn1/cmp/PKIMessages.cs4
-rw-r--r--crypto/src/asn1/cmp/PKIStatus.cs3
-rw-r--r--crypto/src/asn1/cmp/PKIStatusInfo.cs3
-rw-r--r--crypto/src/asn1/cmp/PbmParameter.cs3
-rw-r--r--crypto/src/asn1/cmp/PollRepContent.cs4
-rw-r--r--crypto/src/asn1/cmp/PollReqContent.cs4
-rw-r--r--crypto/src/asn1/cmp/PopoDecKeyChallContent.cs4
-rw-r--r--crypto/src/asn1/cmp/PopoDecKeyRespContent.cs4
-rw-r--r--crypto/src/asn1/cmp/ProtectedPart.cs4
-rw-r--r--crypto/src/asn1/cmp/RevAnnContent.cs3
-rw-r--r--crypto/src/asn1/cmp/RevDetails.cs3
-rw-r--r--crypto/src/asn1/cmp/RevRepContent.cs3
-rw-r--r--crypto/src/asn1/cmp/RevReqContent.cs4
-rw-r--r--crypto/src/asn1/cms/Attribute.cs4
-rw-r--r--crypto/src/asn1/cms/AuthEnvelopedData.cs4
-rw-r--r--crypto/src/asn1/cms/AuthenticatedData.cs3
-rw-r--r--crypto/src/asn1/cms/CompressedData.cs4
-rw-r--r--crypto/src/asn1/cms/ContentInfo.cs4
-rw-r--r--crypto/src/asn1/cms/EncryptedContentInfo.cs4
-rw-r--r--crypto/src/asn1/cms/EncryptedData.cs4
-rw-r--r--crypto/src/asn1/cms/Evidence.cs4
-rw-r--r--crypto/src/asn1/cms/KEKIdentifier.cs4
-rw-r--r--crypto/src/asn1/cms/KEKRecipientInfo.cs4
-rw-r--r--crypto/src/asn1/cms/KeyAgreeRecipientIdentifier.cs4
-rw-r--r--crypto/src/asn1/cms/KeyAgreeRecipientInfo.cs4
-rw-r--r--crypto/src/asn1/cms/KeyTransRecipientInfo.cs4
-rw-r--r--crypto/src/asn1/cms/OriginatorIdentifierOrKey.cs4
-rw-r--r--crypto/src/asn1/cms/OriginatorInfo.cs4
-rw-r--r--crypto/src/asn1/cms/OriginatorPublicKey.cs27
-rw-r--r--crypto/src/asn1/cms/OtherKeyAttribute.cs4
-rw-r--r--crypto/src/asn1/cms/PasswordRecipientInfo.cs4
-rw-r--r--crypto/src/asn1/cms/RecipientEncryptedKey.cs4
-rw-r--r--crypto/src/asn1/cms/RecipientIdentifier.cs4
-rw-r--r--crypto/src/asn1/cms/RecipientInfo.cs4
-rw-r--r--crypto/src/asn1/cms/RecipientKeyIdentifier.cs4
-rw-r--r--crypto/src/asn1/cms/SignedData.cs4
-rw-r--r--crypto/src/asn1/cms/SignedDataParser.cs4
-rw-r--r--crypto/src/asn1/cms/SignerIdentifier.cs4
-rw-r--r--crypto/src/asn1/cms/SignerInfo.cs4
-rw-r--r--crypto/src/asn1/cms/Time.cs4
-rw-r--r--crypto/src/asn1/cms/ecc/MQVuserKeyingMaterial.cs4
-rw-r--r--crypto/src/asn1/crmf/AttributeTypeAndValue.cs4
-rw-r--r--crypto/src/asn1/crmf/CertId.cs3
-rw-r--r--crypto/src/asn1/crmf/CertReqMessages.cs4
-rw-r--r--crypto/src/asn1/crmf/CertReqMsg.cs3
-rw-r--r--crypto/src/asn1/crmf/Controls.cs4
-rw-r--r--crypto/src/asn1/crmf/PKIArchiveOptions.cs4
-rw-r--r--crypto/src/asn1/crmf/PKIPublicationInfo.cs4
-rw-r--r--crypto/src/asn1/crmf/PKMacValue.cs3
-rw-r--r--crypto/src/asn1/crmf/PopoSigningKey.cs3
-rw-r--r--crypto/src/asn1/crmf/PopoSigningKeyInput.cs3
-rw-r--r--crypto/src/asn1/crmf/ProofOfPossession.cs4
-rw-r--r--crypto/src/asn1/crmf/SinglePubInfo.cs3
-rw-r--r--crypto/src/asn1/cryptopro/ECGOST3410ParamSetParameters.cs3
-rw-r--r--crypto/src/asn1/cryptopro/GOST28147Parameters.cs4
-rw-r--r--crypto/src/asn1/cryptopro/GOST3410ParamSetParameters.cs4
-rw-r--r--crypto/src/asn1/cryptopro/GOST3410PublicKeyAlgParameters.cs4
-rw-r--r--crypto/src/asn1/esf/CertificateValues.cs3
-rw-r--r--crypto/src/asn1/esf/CommitmentTypeIndication.cs4
-rw-r--r--crypto/src/asn1/esf/CommitmentTypeQualifier.cs4
-rw-r--r--crypto/src/asn1/esf/CompleteCertificateRefs.cs3
-rw-r--r--crypto/src/asn1/esf/CompleteRevocationRefs.cs3
-rw-r--r--crypto/src/asn1/esf/CrlIdentifier.cs3
-rw-r--r--crypto/src/asn1/esf/CrlListID.cs3
-rw-r--r--crypto/src/asn1/esf/CrlOcspRef.cs4
-rw-r--r--crypto/src/asn1/esf/CrlValidatedID.cs4
-rw-r--r--crypto/src/asn1/esf/OcspIdentifier.cs3
-rw-r--r--crypto/src/asn1/esf/OcspListID.cs3
-rw-r--r--crypto/src/asn1/esf/OcspResponsesID.cs4
-rw-r--r--crypto/src/asn1/esf/OtherCertID.cs3
-rw-r--r--crypto/src/asn1/esf/OtherHashAlgAndValue.cs3
-rw-r--r--crypto/src/asn1/esf/OtherRevRefs.cs4
-rw-r--r--crypto/src/asn1/esf/OtherRevVals.cs4
-rw-r--r--crypto/src/asn1/esf/OtherSigningCertificate.cs3
-rw-r--r--crypto/src/asn1/esf/SigPolicyQualifierInfo.cs4
-rw-r--r--crypto/src/asn1/esf/SignaturePolicyId.cs3
-rw-r--r--crypto/src/asn1/esf/SignaturePolicyIdentifier.cs4
-rw-r--r--crypto/src/asn1/esf/SignerAttribute.cs3
-rw-r--r--crypto/src/asn1/ess/ContentHints.cs4
-rw-r--r--crypto/src/asn1/ess/ContentIdentifier.cs4
-rw-r--r--crypto/src/asn1/ess/ESSCertID.cs3
-rw-r--r--crypto/src/asn1/ess/OtherCertID.cs6
-rw-r--r--crypto/src/asn1/ess/OtherSigningCertificate.cs3
-rw-r--r--crypto/src/asn1/ess/SigningCertificate.cs3
-rw-r--r--crypto/src/asn1/ess/SigningCertificateV2.cs3
-rw-r--r--crypto/src/asn1/isismtt/ocsp/CertHash.cs3
-rw-r--r--crypto/src/asn1/isismtt/ocsp/RequestedCertificate.cs4
-rw-r--r--crypto/src/asn1/isismtt/x509/AdditionalInformationSyntax.cs3
-rw-r--r--crypto/src/asn1/isismtt/x509/AdmissionSyntax.cs523
-rw-r--r--crypto/src/asn1/isismtt/x509/Admissions.cs5
-rw-r--r--crypto/src/asn1/isismtt/x509/DeclarationOfMajority.cs4
-rw-r--r--crypto/src/asn1/isismtt/x509/MonetaryLimit.cs3
-rw-r--r--crypto/src/asn1/isismtt/x509/NamingAuthority.cs9
-rw-r--r--crypto/src/asn1/isismtt/x509/ProcurationSyntax.cs3
-rw-r--r--crypto/src/asn1/isismtt/x509/ProfessionInfo.cs9
-rw-r--r--crypto/src/asn1/isismtt/x509/Restriction.cs3
-rw-r--r--crypto/src/asn1/misc/NetscapeCertType.cs2
-rw-r--r--crypto/src/asn1/mozilla/PublicKeyAndChallenge.cs3
-rw-r--r--crypto/src/asn1/ocsp/BasicOCSPResponse.cs10
-rw-r--r--crypto/src/asn1/ocsp/CertID.cs3
-rw-r--r--crypto/src/asn1/ocsp/CertStatus.cs4
-rw-r--r--crypto/src/asn1/ocsp/OCSPRequest.cs4
-rw-r--r--crypto/src/asn1/ocsp/OCSPResponse.cs4
-rw-r--r--crypto/src/asn1/ocsp/Request.cs3
-rw-r--r--crypto/src/asn1/ocsp/ResponseBytes.cs4
-rw-r--r--crypto/src/asn1/ocsp/ResponseData.cs4
-rw-r--r--crypto/src/asn1/ocsp/RevokedInfo.cs4
-rw-r--r--crypto/src/asn1/ocsp/ServiceLocator.cs4
-rw-r--r--crypto/src/asn1/ocsp/Signature.cs11
-rw-r--r--crypto/src/asn1/ocsp/SingleResponse.cs8
-rw-r--r--crypto/src/asn1/ocsp/TBSRequest.cs8
-rw-r--r--crypto/src/asn1/pkcs/Attribute.cs4
-rw-r--r--crypto/src/asn1/pkcs/CertificationRequest.cs7
-rw-r--r--crypto/src/asn1/pkcs/CertificationRequestInfo.cs3
-rw-r--r--crypto/src/asn1/pkcs/EncryptedData.cs3
-rw-r--r--crypto/src/asn1/pkcs/EncryptedPrivateKeyInfo.cs3
-rw-r--r--crypto/src/asn1/pkcs/EncryptionScheme.cs6
-rw-r--r--crypto/src/asn1/pkcs/IssuerAndSerialNumber.cs3
-rw-r--r--crypto/src/asn1/pkcs/MacData.cs4
-rw-r--r--crypto/src/asn1/pkcs/PBEParameter.cs4
-rw-r--r--crypto/src/asn1/pkcs/PBKDF2Params.cs4
-rw-r--r--crypto/src/asn1/pkcs/PKCS12PBEParams.cs4
-rw-r--r--crypto/src/asn1/pkcs/PrivateKeyInfo.cs4
-rw-r--r--crypto/src/asn1/pkcs/RC2CBCParameter.cs3
-rw-r--r--crypto/src/asn1/pkcs/RSAESOAEPparams.cs3
-rw-r--r--crypto/src/asn1/pkcs/RSASSAPSSparams.cs3
-rw-r--r--crypto/src/asn1/pkcs/SignerInfo.cs4
-rw-r--r--crypto/src/asn1/sec/ECPrivateKeyStructure.cs58
-rw-r--r--crypto/src/asn1/sec/SECNamedCurves.cs4
-rw-r--r--crypto/src/asn1/smime/SMIMECapabilities.cs2
-rw-r--r--crypto/src/asn1/teletrust/TeleTrusTNamedCurves.cs4
-rw-r--r--crypto/src/asn1/tsp/Accuracy.cs4
-rw-r--r--crypto/src/asn1/tsp/MessageImprint.cs3
-rw-r--r--crypto/src/asn1/tsp/TSTInfo.cs3
-rw-r--r--crypto/src/asn1/tsp/TimeStampReq.cs3
-rw-r--r--crypto/src/asn1/tsp/TimeStampResp.cs4
-rw-r--r--crypto/src/asn1/util/Dump.cs4
-rw-r--r--crypto/src/asn1/util/FilterStream.cs16
-rw-r--r--crypto/src/asn1/x500/DirectoryString.cs4
-rw-r--r--crypto/src/asn1/x509/AccessDescription.cs4
-rw-r--r--crypto/src/asn1/x509/AlgorithmIdentifier.cs64
-rw-r--r--crypto/src/asn1/x509/AttCertIssuer.cs4
-rw-r--r--crypto/src/asn1/x509/AttCertValidityPeriod.cs4
-rw-r--r--crypto/src/asn1/x509/Attribute.cs4
-rw-r--r--crypto/src/asn1/x509/AttributeCertificate.cs7
-rw-r--r--crypto/src/asn1/x509/AttributeCertificateInfo.cs4
-rw-r--r--crypto/src/asn1/x509/AuthorityKeyIdentifier.cs4
-rw-r--r--crypto/src/asn1/x509/BasicConstraints.cs4
-rw-r--r--crypto/src/asn1/x509/CRLDistPoint.cs2
-rw-r--r--crypto/src/asn1/x509/CertificateList.cs7
-rw-r--r--crypto/src/asn1/x509/CertificatePair.cs4
-rw-r--r--crypto/src/asn1/x509/DSAParameter.cs3
-rw-r--r--crypto/src/asn1/x509/DigestInfo.cs4
-rw-r--r--crypto/src/asn1/x509/DisplayText.cs4
-rw-r--r--crypto/src/asn1/x509/DistributionPoint.cs2
-rw-r--r--crypto/src/asn1/x509/DistributionPointName.cs2
-rw-r--r--crypto/src/asn1/x509/ExtendedKeyUsage.cs2
-rw-r--r--crypto/src/asn1/x509/GeneralName.cs7
-rw-r--r--crypto/src/asn1/x509/GeneralNames.cs2
-rw-r--r--crypto/src/asn1/x509/Holder.cs4
-rw-r--r--crypto/src/asn1/x509/IssuerSerial.cs4
-rw-r--r--crypto/src/asn1/x509/IssuingDistributionPoint.cs2
-rw-r--r--crypto/src/asn1/x509/KeyUsage.cs5
-rw-r--r--crypto/src/asn1/x509/NameConstraints.cs4
-rw-r--r--crypto/src/asn1/x509/ObjectDigestInfo.cs4
-rw-r--r--crypto/src/asn1/x509/PrivateKeyUsagePeriod.cs4
-rw-r--r--crypto/src/asn1/x509/RSAPublicKeyStructure.cs9
-rw-r--r--crypto/src/asn1/x509/ReasonFlags.cs7
-rw-r--r--crypto/src/asn1/x509/SubjectDirectoryAttributes.cs2
-rw-r--r--crypto/src/asn1/x509/SubjectKeyIdentifier.cs3
-rw-r--r--crypto/src/asn1/x509/SubjectPublicKeyInfo.cs2
-rw-r--r--crypto/src/asn1/x509/TBSCertList.cs3
-rw-r--r--crypto/src/asn1/x509/Target.cs4
-rw-r--r--crypto/src/asn1/x509/TargetInformation.cs4
-rw-r--r--crypto/src/asn1/x509/Targets.cs4
-rw-r--r--crypto/src/asn1/x509/Time.cs8
-rw-r--r--crypto/src/asn1/x509/X509CertificateStructure.cs5
-rw-r--r--crypto/src/asn1/x509/X509Extensions.cs2
-rw-r--r--crypto/src/asn1/x509/X509Name.cs16
-rw-r--r--crypto/src/asn1/x509/qualified/BiometricData.cs6
-rw-r--r--crypto/src/asn1/x509/qualified/Iso4217CurrencyCode.cs6
-rw-r--r--crypto/src/asn1/x509/qualified/MonetaryValue.cs4
-rw-r--r--crypto/src/asn1/x509/qualified/QCStatement.cs5
-rw-r--r--crypto/src/asn1/x509/qualified/SemanticsInformation.cs4
-rw-r--r--crypto/src/asn1/x509/qualified/TypeOfBiometricData.cs4
-rw-r--r--crypto/src/asn1/x509/sigi/NameOrPseudonym.cs5
-rw-r--r--crypto/src/asn1/x509/sigi/PersonalData.cs3
-rw-r--r--crypto/src/asn1/x9/DHDomainParameters.cs4
-rw-r--r--crypto/src/asn1/x9/DHPublicKey.cs4
-rw-r--r--crypto/src/asn1/x9/DHValidationParms.cs4
-rw-r--r--crypto/src/asn1/x9/X962NamedCurves.cs4
-rw-r--r--crypto/src/asn1/x9/X962Parameters.cs35
-rw-r--r--crypto/src/asn1/x9/X9ECParameters.cs15
-rw-r--r--crypto/src/bcpg/ArmoredInputStream.cs13
-rw-r--r--crypto/src/bcpg/ArmoredOutputStream.cs78
-rw-r--r--crypto/src/bcpg/BcpgInputStream.cs14
-rw-r--r--crypto/src/bcpg/BcpgOutputStream.cs18
-rw-r--r--crypto/src/bcpg/PublicKeyEncSessionPacket.cs2
-rw-r--r--crypto/src/cms/CMSAuthenticatedData.cs2
-rw-r--r--crypto/src/cms/CMSAuthenticatedDataGenerator.cs6
-rw-r--r--crypto/src/cms/CMSAuthenticatedDataParser.cs2
-rw-r--r--crypto/src/cms/CMSAuthenticatedDataStreamGenerator.cs33
-rw-r--r--crypto/src/cms/CMSCompressedData.cs3
-rw-r--r--crypto/src/cms/CMSCompressedDataGenerator.cs5
-rw-r--r--crypto/src/cms/CMSCompressedDataStreamGenerator.cs26
-rw-r--r--crypto/src/cms/CMSContentInfoParser.cs3
-rw-r--r--crypto/src/cms/CMSEnvelopedData.cs2
-rw-r--r--crypto/src/cms/CMSEnvelopedDataGenerator.cs4
-rw-r--r--crypto/src/cms/CMSEnvelopedDataParser.cs2
-rw-r--r--crypto/src/cms/CMSEnvelopedDataStreamGenerator.cs35
-rw-r--r--crypto/src/cms/CMSEnvelopedHelper.cs12
-rw-r--r--crypto/src/cms/CMSPBEKey.cs4
-rw-r--r--crypto/src/cms/CMSProcessableFile.cs5
-rw-r--r--crypto/src/cms/CMSProcessableInputStream.cs3
-rw-r--r--crypto/src/cms/CMSSignedData.cs2
-rw-r--r--crypto/src/cms/CMSSignedDataGenerator.cs8
-rw-r--r--crypto/src/cms/CMSSignedDataParser.cs12
-rw-r--r--crypto/src/cms/CMSSignedDataStreamGenerator.cs28
-rw-r--r--crypto/src/cms/CMSSignedHelper.cs2
-rw-r--r--crypto/src/cms/CMSTypedStream.cs3
-rw-r--r--crypto/src/cms/KEKRecipientInfoGenerator.cs13
-rw-r--r--crypto/src/cms/KEKRecipientInformation.cs2
-rw-r--r--crypto/src/cms/KeyAgreeRecipientInfoGenerator.cs2
-rw-r--r--crypto/src/cms/KeyAgreeRecipientInformation.cs2
-rw-r--r--crypto/src/cms/KeyTransRecipientInfoGenerator.cs2
-rw-r--r--crypto/src/cms/KeyTransRecipientInformation.cs2
-rw-r--r--crypto/src/cms/PasswordRecipientInfoGenerator.cs3
-rw-r--r--crypto/src/cms/RecipientInformation.cs6
-rw-r--r--crypto/src/cms/SignerInfoGenerator.cs21
-rw-r--r--crypto/src/cms/SignerInformation.cs16
-rw-r--r--crypto/src/crypto/CipherKeyGenerator.cs4
-rw-r--r--crypto/src/crypto/IEntropySource.cs29
-rw-r--r--crypto/src/crypto/IEntropySourceProvider.cs17
-rw-r--r--crypto/src/crypto/ISignatureFactory.cs (renamed from crypto/src/crypto/ISignatureCalculator.cs)2
-rw-r--r--crypto/src/crypto/IVerifierFactory.cs (renamed from crypto/src/crypto/ISignatureVerifier.cs)2
-rw-r--r--crypto/src/crypto/IVerifierFactoryProvider.cs (renamed from crypto/src/crypto/ISignatureVerifierProvider.cs)4
-rw-r--r--crypto/src/crypto/digests/GeneralDigest.cs36
-rw-r--r--crypto/src/crypto/digests/NonMemoableDigest.cs62
-rw-r--r--crypto/src/crypto/digests/SkeinEngine.cs2
-rw-r--r--crypto/src/crypto/ec/CustomNamedCurves.cs10
-rw-r--r--crypto/src/crypto/encodings/OaepEncoding.cs2
-rw-r--r--crypto/src/crypto/engines/AesEngine.cs139
-rw-r--r--crypto/src/crypto/engines/AesFastEngine.cs133
-rw-r--r--crypto/src/crypto/engines/AesLightEngine.cs143
-rw-r--r--crypto/src/crypto/engines/BlowfishEngine.cs3
-rw-r--r--crypto/src/crypto/engines/Cast5Engine.cs3
-rw-r--r--crypto/src/crypto/engines/DesEdeEngine.cs3
-rw-r--r--crypto/src/crypto/engines/DesEngine.cs3
-rw-r--r--crypto/src/crypto/engines/GOST28147Engine.cs3
-rw-r--r--crypto/src/crypto/engines/HC128Engine.cs3
-rw-r--r--crypto/src/crypto/engines/HC256Engine.cs3
-rw-r--r--crypto/src/crypto/engines/ISAACEngine.cs3
-rw-r--r--crypto/src/crypto/engines/IdeaEngine.cs3
-rw-r--r--crypto/src/crypto/engines/IesEngine.cs4
-rw-r--r--crypto/src/crypto/engines/NoekeonEngine.cs4
-rw-r--r--crypto/src/crypto/engines/RC2Engine.cs3
-rw-r--r--crypto/src/crypto/engines/RC4Engine.cs3
-rw-r--r--crypto/src/crypto/engines/RC532Engine.cs3
-rw-r--r--crypto/src/crypto/engines/RC564Engine.cs3
-rw-r--r--crypto/src/crypto/engines/RC6Engine.cs3
-rw-r--r--crypto/src/crypto/engines/RSACoreEngine.cs2
-rw-r--r--crypto/src/crypto/engines/RijndaelEngine.cs3
-rw-r--r--crypto/src/crypto/engines/SerpentEngine.cs565
-rw-r--r--crypto/src/crypto/engines/SerpentEngineBase.cs468
-rw-r--r--crypto/src/crypto/engines/SkipjackEngine.cs3
-rw-r--r--crypto/src/crypto/engines/TEAEngine.cs3
-rw-r--r--crypto/src/crypto/engines/ThreefishEngine.cs3
-rw-r--r--crypto/src/crypto/engines/TnepresEngine.cs299
-rw-r--r--crypto/src/crypto/engines/TwofishEngine.cs3
-rw-r--r--crypto/src/crypto/engines/XTEAEngine.cs3
-rw-r--r--crypto/src/crypto/generators/DHParametersHelper.cs10
-rw-r--r--crypto/src/crypto/generators/DesEdeKeyGenerator.cs8
-rw-r--r--crypto/src/crypto/generators/DesKeyGenerator.cs8
-rw-r--r--crypto/src/crypto/generators/NaccacheSternKeyPairGenerator.cs4
-rw-r--r--crypto/src/crypto/generators/RsaKeyPairGenerator.cs2
-rw-r--r--crypto/src/crypto/io/CipherStream.cs25
-rw-r--r--crypto/src/crypto/io/DigestStream.cs18
-rw-r--r--crypto/src/crypto/io/MacStream.cs26
-rw-r--r--crypto/src/crypto/io/SignerStream.cs26
-rw-r--r--crypto/src/crypto/macs/GOST28147Mac.cs3
-rw-r--r--crypto/src/crypto/macs/SkeinMac.cs3
-rw-r--r--crypto/src/crypto/modes/GCMBlockCipher.cs9
-rw-r--r--crypto/src/crypto/modes/SicBlockCipher.cs8
-rw-r--r--crypto/src/crypto/operators/Asn1Signature.cs36
-rw-r--r--crypto/src/crypto/parameters/DesEdeParameters.cs45
-rw-r--r--crypto/src/crypto/parameters/DesParameters.cs35
-rw-r--r--crypto/src/crypto/parameters/ParametersWithRandom.cs2
-rw-r--r--crypto/src/crypto/parameters/SkeinParameters.cs2
-rw-r--r--crypto/src/crypto/prng/BasicEntropySourceProvider.cs71
-rw-r--r--crypto/src/crypto/prng/CryptoApiEntropySourceProvider.cs70
-rw-r--r--crypto/src/crypto/prng/DigestRandomGenerator.cs12
-rw-r--r--crypto/src/crypto/prng/EntropyUtilities.cs30
-rw-r--r--crypto/src/crypto/prng/IDrbgProvider.cs11
-rw-r--r--crypto/src/crypto/prng/SP800SecureRandom.cs80
-rw-r--r--crypto/src/crypto/prng/SP800SecureRandomBuilder.cs208
-rw-r--r--crypto/src/crypto/prng/ThreadedSeedGenerator.cs160
-rw-r--r--crypto/src/crypto/prng/X931Rng.cs146
-rw-r--r--crypto/src/crypto/prng/X931SecureRandom.cs70
-rw-r--r--crypto/src/crypto/prng/X931SecureRandomBuilder.cs87
-rw-r--r--crypto/src/crypto/prng/drbg/CtrSP800Drbg.cs466
-rw-r--r--crypto/src/crypto/prng/drbg/DrbgUtilities.cs103
-rw-r--r--crypto/src/crypto/prng/drbg/HMacSP800Drbg.cs186
-rw-r--r--crypto/src/crypto/prng/drbg/HashSP800Drbg.cs287
-rw-r--r--crypto/src/crypto/prng/drbg/ISP80090Drbg.cs35
-rw-r--r--crypto/src/crypto/signers/ECDsaSigner.cs59
-rw-r--r--crypto/src/crypto/tls/ByteQueueStream.cs4
-rw-r--r--crypto/src/crypto/tls/CertificateUrl.cs2
-rw-r--r--crypto/src/crypto/tls/DefaultTlsAgreementCredentials.cs2
-rw-r--r--crypto/src/crypto/tls/DefaultTlsEncryptionCredentials.cs3
-rw-r--r--crypto/src/crypto/tls/DefaultTlsSignerCredentials.cs3
-rw-r--r--crypto/src/crypto/tls/DtlsReliableHandshake.cs12
-rw-r--r--crypto/src/crypto/tls/HeartbeatMessage.cs9
-rw-r--r--crypto/src/crypto/tls/RecordStream.cs6
-rw-r--r--crypto/src/crypto/tls/ServerName.cs12
-rw-r--r--crypto/src/crypto/tls/TlsProtocol.cs13
-rw-r--r--crypto/src/crypto/tls/TlsStream.cs12
-rw-r--r--crypto/src/crypto/tls/TlsUtilities.cs5
-rw-r--r--crypto/src/math/BigInteger.cs71
-rw-r--r--crypto/src/math/Primes.cs103
-rw-r--r--crypto/src/math/ec/ECCurve.cs11
-rw-r--r--crypto/src/ocsp/BasicOCSPResp.cs6
-rw-r--r--crypto/src/ocsp/BasicOCSPRespGenerator.cs14
-rw-r--r--crypto/src/ocsp/CertificateID.cs4
-rw-r--r--crypto/src/ocsp/OCSPReq.cs6
-rw-r--r--crypto/src/openpgp/PgpCompressedDataGenerator.cs34
-rw-r--r--crypto/src/openpgp/PgpEncryptedData.cs2
-rw-r--r--crypto/src/openpgp/PgpLiteralDataGenerator.cs4
-rw-r--r--crypto/src/openpgp/PgpPublicKeyRing.cs2
-rw-r--r--crypto/src/openpgp/PgpPublicKeyRingBundle.cs8
-rw-r--r--crypto/src/openpgp/PgpSecretKey.cs2
-rw-r--r--crypto/src/openpgp/PgpSecretKeyRingBundle.cs9
-rw-r--r--crypto/src/openpgp/PgpUtilities.cs6
-rw-r--r--crypto/src/openpgp/WrappedGeneratorStream.cs12
-rw-r--r--crypto/src/openssl/MiscPemGenerator.cs11
-rw-r--r--crypto/src/openssl/PEMReader.cs6
-rw-r--r--crypto/src/pkcs/Pkcs10CertificationRequest.cs36
-rw-r--r--crypto/src/pkcs/Pkcs12Store.cs26
-rw-r--r--crypto/src/pkcs/Pkcs12Utilities.cs4
-rw-r--r--crypto/src/pkcs/PrivateKeyInfoFactory.cs37
-rw-r--r--crypto/src/pkix/PkixCertPath.cs8
-rw-r--r--crypto/src/pkix/PkixCertPathBuilder.cs2
-rw-r--r--crypto/src/pkix/PkixCertPathValidator.cs4
-rw-r--r--crypto/src/pkix/PkixCertPathValidatorUtilities.cs2
-rw-r--r--crypto/src/pkix/PkixNameConstraintValidator.cs87
-rw-r--r--crypto/src/pkix/PkixParameters.cs2
-rw-r--r--crypto/src/security/CipherUtilities.cs26
-rw-r--r--crypto/src/security/GeneratorUtilities.cs17
-rw-r--r--crypto/src/security/MacUtilities.cs8
-rw-r--r--crypto/src/security/ParameterUtilities.cs4
-rw-r--r--crypto/src/security/PbeUtilities.cs44
-rw-r--r--crypto/src/security/PrivateKeyFactory.cs17
-rw-r--r--crypto/src/security/PublicKeyFactory.cs2
-rw-r--r--crypto/src/security/SecureRandom.cs58
-rw-r--r--crypto/src/security/SignerUtilities.cs6
-rw-r--r--crypto/src/tsp/TimeStampRequest.cs2
-rw-r--r--crypto/src/tsp/TimeStampResponseGenerator.cs5
-rw-r--r--crypto/src/tsp/TimeStampToken.cs4
-rw-r--r--crypto/src/tsp/TimeStampTokenInfo.cs2
-rw-r--r--crypto/src/util/Arrays.cs29
-rw-r--r--crypto/src/util/Enums.cs15
-rw-r--r--crypto/src/util/Platform.cs55
-rw-r--r--crypto/src/util/TypeExtensions.cs17
-rw-r--r--crypto/src/util/io/BaseInputStream.cs21
-rw-r--r--crypto/src/util/io/BaseOutputStream.cs21
-rw-r--r--crypto/src/util/io/FilterStream.cs14
-rw-r--r--crypto/src/util/io/TeeInputStream.cs21
-rw-r--r--crypto/src/util/io/TeeOutputStream.cs21
-rw-r--r--crypto/src/util/io/pem/PemReader.cs10
-rw-r--r--crypto/src/util/net/IPAddress.cs4
-rw-r--r--crypto/src/util/zlib/ZDeflaterOutputStream.cs22
-rw-r--r--crypto/src/util/zlib/ZInflaterInputStream.cs19
-rw-r--r--crypto/src/util/zlib/ZInputStream.cs28
-rw-r--r--crypto/src/util/zlib/ZOutputStream.cs60
-rw-r--r--crypto/src/x509/AttributeCertificateHolder.cs4
-rw-r--r--crypto/src/x509/PEMParser.cs5
-rw-r--r--crypto/src/x509/SubjectPublicKeyInfoFactory.cs5
-rw-r--r--crypto/src/x509/X509Certificate.cs20
-rw-r--r--crypto/src/x509/X509Crl.cs14
-rw-r--r--crypto/src/x509/X509SignatureUtil.cs10
-rw-r--r--crypto/src/x509/X509V1CertificateGenerator.cs21
-rw-r--r--crypto/src/x509/X509V2AttributeCertificate.cs19
-rw-r--r--crypto/src/x509/X509V2AttributeCertificateGenerator.cs22
-rw-r--r--crypto/src/x509/X509V2CRLGenerator.cs23
-rw-r--r--crypto/src/x509/X509V3CertificateGenerator.cs25
435 files changed, 6038 insertions, 2260 deletions
diff --git a/crypto/src/AssemblyInfo.cs b/crypto/src/AssemblyInfo.cs

index ce2ff713c..05f1d8f63 100644 --- a/crypto/src/AssemblyInfo.cs +++ b/crypto/src/AssemblyInfo.cs
@@ -1,9 +1,13 @@ using System; using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; //using System.Security.Permissions; +#if PORTABLE +using System.Linq; +#else +using System.Runtime.InteropServices; +#endif + // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information @@ -29,7 +33,42 @@ using System.Runtime.InteropServices; // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: -[assembly: AssemblyVersion("1.8.*")] +[assembly: AssemblyVersion("1.8.0.0")] +[assembly: AssemblyFileVersion("1.8.15326.1")] +[assembly: AssemblyInformationalVersion("1.8.0")] + +// +// In order to sign your assembly you must specify a key to use. Refer to the +// Microsoft .NET Framework documentation for more information on assembly signing. +// +// Use the attributes below to control which key is used for signing. +// +// Notes: +// (*) If no key is specified, the assembly is not signed. +// (*) KeyName refers to a key that has been installed in the Crypto Service +// Provider (CSP) on your machine. KeyFile refers to a file which contains +// a key. +// (*) If the KeyFile and the KeyName values are both specified, the +// following processing occurs: +// (1) If the KeyName can be found in the CSP, that key is used. +// (2) If the KeyName does not exist and the KeyFile does exist, the key +// in the KeyFile is installed into the CSP and used. +// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. +// When specifying the KeyFile, the location of the KeyFile should be +// relative to the project output directory which is +// %Project Directory%\obj\<configuration>. For example, if your KeyFile is +// located in the project directory, you would specify the AssemblyKeyFile +// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] +// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework +// documentation for more information on this. +// +[assembly: AssemblyDelaySign(false)] +#if STRONG_NAME +[assembly: AssemblyKeyFile(@"../BouncyCastle.snk")] +#else +[assembly: AssemblyKeyFile("")] +#endif +[assembly: AssemblyKeyName("")] [assembly: CLSCompliant(true)] #if !PORTABLE @@ -43,3 +82,41 @@ using System.Runtime.InteropServices; // see Org.BouncyCastle.Crypto.Encodings.Pkcs1Encoding.StrictLengthEnabledProperty //[assembly: EnvironmentPermission(SecurityAction.RequestOptional, Read="Org.BouncyCastle.Pkcs1.Strict")] +internal class AssemblyInfo +{ + private static string version = null; + + public static string Version + { + get + { + if (version == null) + { +#if PORTABLE +#if NEW_REFLECTION + var a = typeof(AssemblyInfo).GetTypeInfo().Assembly; + var c = a.GetCustomAttributes(typeof(AssemblyVersionAttribute)); +#else + var a = typeof(AssemblyInfo).Assembly; + var c = a.GetCustomAttributes(typeof(AssemblyVersionAttribute), false); +#endif + var v = (AssemblyVersionAttribute)c.FirstOrDefault(); + if (v != null) + { + version = v.Version; + } +#else + version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); +#endif + + // if we're still here, then don't try again + if (version == null) + { + version = string.Empty; + } + } + + return version; + } + } +} diff --git a/crypto/src/asn1/Asn1Object.cs b/crypto/src/asn1/Asn1Object.cs
index 08bd599c1..a86fdbb4a 100644 --- a/crypto/src/asn1/Asn1Object.cs +++ b/crypto/src/asn1/Asn1Object.cs
@@ -13,13 +13,18 @@ namespace Org.BouncyCastle.Asn1 public static Asn1Object FromByteArray( byte[] data) { - try + try { - return new Asn1InputStream(data).ReadObject(); + MemoryStream input = new MemoryStream(data, false); + Asn1InputStream asn1 = new Asn1InputStream(input, data.Length); + Asn1Object result = asn1.ReadObject(); + if (input.Position != input.Length) + throw new IOException("extra data found after object"); + return result; } catch (InvalidCastException) { - throw new IOException("cannot recognise object in stream"); + throw new IOException("cannot recognise object in byte array"); } } @@ -36,7 +41,7 @@ namespace Org.BouncyCastle.Asn1 } catch (InvalidCastException) { - throw new IOException("cannot recognise object in stream"); + throw new IOException("cannot recognise object in stream"); } } diff --git a/crypto/src/asn1/Asn1OctetString.cs b/crypto/src/asn1/Asn1OctetString.cs
index 9c738a8f2..73b6e51bf 100644 --- a/crypto/src/asn1/Asn1OctetString.cs +++ b/crypto/src/asn1/Asn1OctetString.cs
@@ -52,7 +52,7 @@ namespace Org.BouncyCastle.Asn1 if (obj is Asn1TaggedObject) return GetInstance(((Asn1TaggedObject)obj).GetObject()); - throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name); + throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** diff --git a/crypto/src/asn1/Asn1Sequence.cs b/crypto/src/asn1/Asn1Sequence.cs
index 5f9ea4460..849f5e308 100644 --- a/crypto/src/asn1/Asn1Sequence.cs +++ b/crypto/src/asn1/Asn1Sequence.cs
@@ -50,7 +50,7 @@ namespace Org.BouncyCastle.Asn1 } } - throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } /** @@ -103,7 +103,7 @@ namespace Org.BouncyCastle.Asn1 return (Asn1Sequence) inner; } - throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } protected internal Asn1Sequence( diff --git a/crypto/src/asn1/Asn1Set.cs b/crypto/src/asn1/Asn1Set.cs
index cf039d7fe..bf83dbdc1 100644 --- a/crypto/src/asn1/Asn1Set.cs +++ b/crypto/src/asn1/Asn1Set.cs
@@ -2,6 +2,11 @@ using System; using System.Collections; using System.IO; +#if PORTABLE +using System.Collections.Generic; +using System.Linq; +#endif + using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; @@ -50,7 +55,7 @@ namespace Org.BouncyCastle.Asn1 } } - throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } /** @@ -116,7 +121,7 @@ namespace Org.BouncyCastle.Asn1 return new DerSet(v, false); } - throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } protected internal Asn1Set( @@ -283,6 +288,18 @@ namespace Org.BouncyCastle.Asn1 if (_set.Count < 2) return; +#if PORTABLE + var sorted = _set.Cast<Asn1Encodable>() + .Select(a => new { Item = a, Key = a.GetEncoded(Asn1Encodable.Der) }) + .OrderBy(t => t.Key, new DerComparer()) + .Select(t => t.Item) + .ToList(); + + for (int i = 0; i < _set.Count; ++i) + { + _set[i] = sorted[i]; + } +#else Asn1Encodable[] items = new Asn1Encodable[_set.Count]; byte[][] keys = new byte[_set.Count][]; @@ -299,6 +316,7 @@ namespace Org.BouncyCastle.Asn1 { _set[i] = items[i]; } +#endif } protected internal void AddObject(Asn1Encodable obj) @@ -311,12 +329,21 @@ namespace Org.BouncyCastle.Asn1 return CollectionUtilities.ToString(_set); } +#if PORTABLE + private class DerComparer + : IComparer<byte[]> + { + public int Compare(byte[] x, byte[] y) + { + byte[] a = x, b = y; +#else private class DerComparer - : IComparer + : IComparer { public int Compare(object x, object y) { byte[] a = (byte[])x, b = (byte[])y; +#endif int len = System.Math.Min(a.Length, b.Length); for (int i = 0; i != len; ++i) { diff --git a/crypto/src/asn1/Asn1TaggedObject.cs b/crypto/src/asn1/Asn1TaggedObject.cs
index 2e480738a..fdf5b651a 100644 --- a/crypto/src/asn1/Asn1TaggedObject.cs +++ b/crypto/src/asn1/Asn1TaggedObject.cs
@@ -37,7 +37,7 @@ namespace Org.BouncyCastle.Asn1 return (Asn1TaggedObject) obj; } - throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } /** diff --git a/crypto/src/asn1/BERBitString.cs b/crypto/src/asn1/BERBitString.cs new file mode 100644
index 000000000..d8cd00330 --- /dev/null +++ b/crypto/src/asn1/BERBitString.cs
@@ -0,0 +1,43 @@ +using System; + +using Org.BouncyCastle.Utilities; + +namespace Org.BouncyCastle.Asn1 +{ + public class BerBitString + : DerBitString + { + public BerBitString(byte[] data, int padBits) + : base(data, padBits) + { + } + + public BerBitString(byte[] data) + : base(data) + { + } + + public BerBitString(int namedBits) + : base(namedBits) + { + } + + public BerBitString(Asn1Encodable obj) + : base(obj) + { + } + + internal override void Encode( + DerOutputStream derOut) + { + if (derOut is Asn1OutputStream || derOut is BerOutputStream) + { + derOut.WriteEncoded(Asn1Tags.BitString, (byte)mPadBits, mData); + } + else + { + base.Encode(derOut); + } + } + } +} diff --git a/crypto/src/asn1/BEROctetStringGenerator.cs b/crypto/src/asn1/BEROctetStringGenerator.cs
index 7468a6b0b..f34538f38 100644 --- a/crypto/src/asn1/BEROctetStringGenerator.cs +++ b/crypto/src/asn1/BEROctetStringGenerator.cs
@@ -102,7 +102,22 @@ namespace Org.BouncyCastle.Asn1 } } - public override void Close() +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (_off != 0) + { + DerOctetString.Encode(_derOut, _buf, 0, _off); + } + + _gen.WriteBerEnd(); + } + base.Dispose(disposing); + } +#else + public override void Close() { if (_off != 0) { @@ -112,6 +127,7 @@ namespace Org.BouncyCastle.Asn1 _gen.WriteBerEnd(); base.Close(); } +#endif } } } diff --git a/crypto/src/asn1/BerTaggedObject.cs b/crypto/src/asn1/BerTaggedObject.cs
index 228b136cb..fd0bdc285 100644 --- a/crypto/src/asn1/BerTaggedObject.cs +++ b/crypto/src/asn1/BerTaggedObject.cs
@@ -82,7 +82,7 @@ namespace Org.BouncyCastle.Asn1 } else { - throw Platform.CreateNotImplementedException(obj.GetType().Name); + throw Platform.CreateNotImplementedException(Platform.GetTypeName(obj)); } foreach (Asn1Encodable o in eObj) diff --git a/crypto/src/asn1/DerApplicationSpecific.cs b/crypto/src/asn1/DerApplicationSpecific.cs
index 394c7431e..9149930e0 100644 --- a/crypto/src/asn1/DerApplicationSpecific.cs +++ b/crypto/src/asn1/DerApplicationSpecific.cs
@@ -160,7 +160,7 @@ namespace Org.BouncyCastle.Asn1 tmp[0] |= Asn1Tags.Constructed; } - return FromByteArray(tmp);; + return FromByteArray(tmp); } internal override void Encode( diff --git a/crypto/src/asn1/DerBMPString.cs b/crypto/src/asn1/DerBMPString.cs
index 4f7e0a635..33d950ff8 100644 --- a/crypto/src/asn1/DerBMPString.cs +++ b/crypto/src/asn1/DerBMPString.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1 { /** @@ -24,7 +26,7 @@ namespace Org.BouncyCastle.Asn1 return (DerBmpString)obj; } - throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name); + throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** diff --git a/crypto/src/asn1/DerBitString.cs b/crypto/src/asn1/DerBitString.cs
index d5cb872bc..a3c2cee01 100644 --- a/crypto/src/asn1/DerBitString.cs +++ b/crypto/src/asn1/DerBitString.cs
@@ -1,6 +1,8 @@ using System; +using System.Diagnostics; using System.Text; +using Org.BouncyCastle.Math; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1 @@ -11,83 +13,10 @@ namespace Org.BouncyCastle.Asn1 private static readonly char[] table = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; - private readonly byte[] data; - private readonly int padBits; + protected readonly byte[] mData; + protected readonly int mPadBits; - /** - * return the correct number of pad bits for a bit string defined in - * a 32 bit constant - */ - static internal int GetPadBits( - int bitString) - { - int val = 0; - for (int i = 3; i >= 0; i--) - { - // - // this may look a little odd, but if it isn't done like this pre jdk1.2 - // JVM's break! - // - if (i != 0) - { - if ((bitString >> (i * 8)) != 0) - { - val = (bitString >> (i * 8)) & 0xFF; - break; - } - } - else - { - if (bitString != 0) - { - val = bitString & 0xFF; - break; - } - } - } - - if (val == 0) - { - return 7; - } - - int bits = 1; - - while (((val <<= 1) & 0xFF) != 0) - { - bits++; - } - - return 8 - bits; - } - - /** - * return the correct number of bytes for a bit string defined in - * a 32 bit constant - */ - static internal byte[] GetBytes( - int bitString) - { - int bytes = 4; - for (int i = 3; i >= 1; i--) - { - if ((bitString & (0xFF << (i * 8))) != 0) - { - break; - } - bytes--; - } - - byte[] result = new byte[bytes]; - for (int i = 0; i < bytes; i++) - { - result[i] = (byte) ((bitString >> (i * 8)) & 0xFF); - } - - return result; - } - - /** + /** * return a Bit string from the passed in object * * @exception ArgumentException if the object cannot be converted. @@ -100,7 +29,7 @@ namespace Org.BouncyCastle.Asn1 return (DerBitString) obj; } - throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name); + throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** @@ -126,15 +55,7 @@ namespace Org.BouncyCastle.Asn1 return FromAsn1Octets(((Asn1OctetString)o).GetOctets()); } - internal DerBitString( - byte data, - int padBits) - { - this.data = new byte[]{ data }; - this.padBits = padBits; - } - - /** + /** * @param data the octets making up the bit string. * @param padBits the number of extra bits at the end of the string. */ @@ -142,67 +63,152 @@ namespace Org.BouncyCastle.Asn1 byte[] data, int padBits) { - // TODO Deep copy? - this.data = data; - this.padBits = padBits; + if (data == null) + throw new ArgumentNullException("data"); + if (padBits < 0 || padBits > 7) + throw new ArgumentException("must be in the range 0 to 7", "padBits"); + if (data.Length == 0 && padBits != 0) + throw new ArgumentException("if 'data' is empty, 'padBits' must be 0"); + + this.mData = Arrays.Clone(data); + this.mPadBits = padBits; } public DerBitString( byte[] data) + : this(data, 0) { - // TODO Deep copy? - this.data = data; } - public DerBitString( + public DerBitString( + int namedBits) + { + if (namedBits == 0) + { + this.mData = new byte[0]; + this.mPadBits = 0; + return; + } + + int bits = BigInteger.BitLen(namedBits); + int bytes = (bits + 7) / 8; + + Debug.Assert(0 < bytes && bytes <= 4); + + byte[] data = new byte[bytes]; + --bytes; + + for (int i = 0; i < bytes; i++) + { + data[i] = (byte)namedBits; + namedBits >>= 8; + } + + Debug.Assert((namedBits & 0xFF) != 0); + + data[bytes] = (byte)namedBits; + + int padBits = 0; + while ((namedBits & (1 << padBits)) == 0) + { + ++padBits; + } + + Debug.Assert(padBits < 8); + + this.mData = data; + this.mPadBits = padBits; + } + + public DerBitString( Asn1Encodable obj) + : this(obj.GetDerEncoded()) { - this.data = obj.GetDerEncoded(); - //this.padBits = 0; } - public byte[] GetBytes() + /** + * Return the octets contained in this BIT STRING, checking that this BIT STRING really + * does represent an octet aligned string. Only use this method when the standard you are + * following dictates that the BIT STRING will be octet aligned. + * + * @return a copy of the octet aligned data. + */ + public virtual byte[] GetOctets() + { + if (mPadBits != 0) + throw new InvalidOperationException("attempt to get non-octet aligned data from BIT STRING"); + + return Arrays.Clone(mData); + } + + public virtual byte[] GetBytes() { - return data; + byte[] data = Arrays.Clone(mData); + + // DER requires pad bits be zero + if (mPadBits > 0) + { + data[data.Length - 1] &= (byte)(0xFF << mPadBits); + } + + return data; } - public int PadBits + public virtual int PadBits { - get { return padBits; } + get { return mPadBits; } } /** * @return the value of the bit string as an int (truncating if necessary) */ - public int IntValue + public virtual int IntValue { get { - int value = 0; - - for (int i = 0; i != data.Length && i != 4; i++) - { - value |= (data[i] & 0xff) << (8 * i); - } - - return value; + int value = 0, length = System.Math.Min(4, mData.Length); + for (int i = 0; i < length; ++i) + { + value |= (int)mData[i] << (8 * i); + } + if (mPadBits > 0 && length == mData.Length) + { + int mask = (1 << mPadBits) - 1; + value &= ~(mask << (8 * (length - 1))); + } + return value; } } - internal override void Encode( + internal override void Encode( DerOutputStream derOut) { - byte[] bytes = new byte[GetBytes().Length + 1]; - - bytes[0] = (byte) PadBits; - Array.Copy(GetBytes(), 0, bytes, 1, bytes.Length - 1); - - derOut.WriteEncoded(Asn1Tags.BitString, bytes); + if (mPadBits > 0) + { + int last = mData[mData.Length - 1]; + int mask = (1 << mPadBits) - 1; + int unusedBits = last & mask; + + if (unusedBits != 0) + { + byte[] contents = Arrays.Prepend(mData, (byte)mPadBits); + + /* + * X.690-0207 11.2.1: Each unused bit in the final octet of the encoding of a bit string value shall be set to zero. + */ + contents[contents.Length - 1] = (byte)(last ^ unusedBits); + + derOut.WriteEncoded(Asn1Tags.BitString, contents); + return; + } + } + + derOut.WriteEncoded(Asn1Tags.BitString, (byte)mPadBits, mData); } - protected override int Asn1GetHashCode() + protected override int Asn1GetHashCode() { - return padBits.GetHashCode() ^ Arrays.GetHashCode(data); + return mPadBits.GetHashCode() ^ Arrays.GetHashCode(mData); } protected override bool Asn1Equals( @@ -213,8 +219,8 @@ namespace Org.BouncyCastle.Asn1 if (other == null) return false; - return this.padBits == other.padBits - && Arrays.AreEqual(this.data, other.data); + return this.mPadBits == other.mPadBits + && Arrays.AreEqual(this.mData, other.mData); } public override string GetString() @@ -236,12 +242,23 @@ namespace Org.BouncyCastle.Asn1 internal static DerBitString FromAsn1Octets(byte[] octets) { if (octets.Length < 1) - throw new ArgumentException("truncated BIT STRING detected"); + throw new ArgumentException("truncated BIT STRING detected", "octets"); + + int padBits = octets[0]; + byte[] data = Arrays.CopyOfRange(octets, 1, octets.Length); + + if (padBits > 0 && padBits < 8 && data.Length > 0) + { + int last = data[data.Length - 1]; + int mask = (1 << padBits) - 1; + + if ((last & mask) != 0) + { + return new BerBitString(data, padBits); + } + } - int padBits = octets[0]; - byte[] data = new byte[octets.Length - 1]; - Array.Copy(octets, 1, data, 0, data.Length); - return new DerBitString(data, padBits); + return new DerBitString(data, padBits); } } } diff --git a/crypto/src/asn1/DerBoolean.cs b/crypto/src/asn1/DerBoolean.cs
index 66791d16c..709f4ddce 100644 --- a/crypto/src/asn1/DerBoolean.cs +++ b/crypto/src/asn1/DerBoolean.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1 { public class DerBoolean @@ -23,7 +25,7 @@ namespace Org.BouncyCastle.Asn1 return (DerBoolean) obj; } - throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name); + throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** diff --git a/crypto/src/asn1/DerEnumerated.cs b/crypto/src/asn1/DerEnumerated.cs
index 2638b0205..476b7fa9a 100644 --- a/crypto/src/asn1/DerEnumerated.cs +++ b/crypto/src/asn1/DerEnumerated.cs
@@ -23,7 +23,7 @@ namespace Org.BouncyCastle.Asn1 return (DerEnumerated)obj; } - throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name); + throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** diff --git a/crypto/src/asn1/DerGeneralString.cs b/crypto/src/asn1/DerGeneralString.cs
index 0e20b53bd..553b0e09c 100644 --- a/crypto/src/asn1/DerGeneralString.cs +++ b/crypto/src/asn1/DerGeneralString.cs
@@ -19,7 +19,7 @@ namespace Org.BouncyCastle.Asn1 } throw new ArgumentException("illegal object in GetInstance: " - + obj.GetType().Name); + + Platform.GetTypeName(obj)); } public static DerGeneralString GetInstance( diff --git a/crypto/src/asn1/DerGeneralizedTime.cs b/crypto/src/asn1/DerGeneralizedTime.cs
index 6700b9016..b224ebe42 100644 --- a/crypto/src/asn1/DerGeneralizedTime.cs +++ b/crypto/src/asn1/DerGeneralizedTime.cs
@@ -27,7 +27,7 @@ namespace Org.BouncyCastle.Asn1 return (DerGeneralizedTime)obj; } - throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name, "obj"); + throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } /** @@ -83,7 +83,11 @@ namespace Org.BouncyCastle.Asn1 public DerGeneralizedTime( DateTime time) { +#if PORTABLE + this.time = time.ToUniversalTime().ToString(@"yyyyMMddHHmmss\Z"); +#else this.time = time.ToString(@"yyyyMMddHHmmss\Z"); +#endif } internal DerGeneralizedTime( @@ -200,7 +204,7 @@ namespace Org.BouncyCastle.Asn1 string d = time; bool makeUniversal = false; - if (d.EndsWith("Z")) + if (Platform.EndsWith(d, "Z")) { if (HasFractionalSeconds) { @@ -219,7 +223,7 @@ namespace Org.BouncyCastle.Asn1 if (HasFractionalSeconds) { - int fCount = d.IndexOf("GMT") - 1 - d.IndexOf('.'); + int fCount = Platform.IndexOf(d, "GMT") - 1 - d.IndexOf('.'); formatStr = @"yyyyMMddHHmmss." + FString(fCount) + @"'GMT'zzz"; } else @@ -263,11 +267,11 @@ namespace Org.BouncyCastle.Asn1 * NOTE: DateTime.Kind and DateTimeStyles.AssumeUniversal not available in .NET 1.1 */ DateTimeStyles style = DateTimeStyles.None; - if (format.EndsWith("Z")) + if (Platform.EndsWith(format, "Z")) { try { - style = (DateTimeStyles)Enum.Parse(typeof(DateTimeStyles), "AssumeUniversal"); + style = (DateTimeStyles)Enums.GetEnumValue(typeof(DateTimeStyles), "AssumeUniversal"); } catch (Exception) { diff --git a/crypto/src/asn1/DerIA5String.cs b/crypto/src/asn1/DerIA5String.cs
index 9fa2cba3c..63e91582e 100644 --- a/crypto/src/asn1/DerIA5String.cs +++ b/crypto/src/asn1/DerIA5String.cs
@@ -26,7 +26,7 @@ namespace Org.BouncyCastle.Asn1 return (DerIA5String)obj; } - throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name); + throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** diff --git a/crypto/src/asn1/DerInteger.cs b/crypto/src/asn1/DerInteger.cs
index eb0614515..3610de588 100644 --- a/crypto/src/asn1/DerInteger.cs +++ b/crypto/src/asn1/DerInteger.cs
@@ -23,7 +23,7 @@ namespace Org.BouncyCastle.Asn1 return (DerInteger)obj; } - throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name); + throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** diff --git a/crypto/src/asn1/DerNumericString.cs b/crypto/src/asn1/DerNumericString.cs
index 6e2715a4d..a729f9e8e 100644 --- a/crypto/src/asn1/DerNumericString.cs +++ b/crypto/src/asn1/DerNumericString.cs
@@ -26,7 +26,7 @@ namespace Org.BouncyCastle.Asn1 return (DerNumericString)obj; } - throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name); + throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** diff --git a/crypto/src/asn1/DerObjectIdentifier.cs b/crypto/src/asn1/DerObjectIdentifier.cs
index f9f6a79d6..6ac2b7e9e 100644 --- a/crypto/src/asn1/DerObjectIdentifier.cs +++ b/crypto/src/asn1/DerObjectIdentifier.cs
@@ -26,7 +26,7 @@ namespace Org.BouncyCastle.Asn1 return (DerObjectIdentifier) obj; if (obj is byte[]) return FromOctetString((byte[])obj); - throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name, "obj"); + throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } /** @@ -83,7 +83,7 @@ namespace Org.BouncyCastle.Asn1 public virtual bool On(DerObjectIdentifier stem) { string id = Id, stemId = stem.Id; - return id.Length > stemId.Length && id[stemId.Length] == '.' && id.StartsWith(stemId); + return id.Length > stemId.Length && id[stemId.Length] == '.' && Platform.StartsWith(id, stemId); } internal DerObjectIdentifier(byte[] bytes) diff --git a/crypto/src/asn1/DerOutputStream.cs b/crypto/src/asn1/DerOutputStream.cs
index c03d9dc11..69d5d5f28 100644 --- a/crypto/src/asn1/DerOutputStream.cs +++ b/crypto/src/asn1/DerOutputStream.cs
@@ -19,7 +19,7 @@ namespace Org.BouncyCastle.Asn1 if (length > 127) { int size = 1; - uint val = (uint) length; + uint val = (uint)length; while ((val >>= 8) != 0) { @@ -43,18 +43,29 @@ namespace Org.BouncyCastle.Asn1 int tag, byte[] bytes) { - WriteByte((byte) tag); + WriteByte((byte)tag); WriteLength(bytes.Length); Write(bytes, 0, bytes.Length); } - internal void WriteEncoded( + internal void WriteEncoded( + int tag, + byte first, + byte[] bytes) + { + WriteByte((byte)tag); + WriteLength(bytes.Length + 1); + WriteByte(first); + Write(bytes, 0, bytes.Length); + } + + internal void WriteEncoded( int tag, byte[] bytes, int offset, int length) { - WriteByte((byte) tag); + WriteByte((byte)tag); WriteLength(length); Write(bytes, offset, length); } diff --git a/crypto/src/asn1/DerPrintableString.cs b/crypto/src/asn1/DerPrintableString.cs
index cd2f46b48..e1797346d 100644 --- a/crypto/src/asn1/DerPrintableString.cs +++ b/crypto/src/asn1/DerPrintableString.cs
@@ -26,7 +26,7 @@ namespace Org.BouncyCastle.Asn1 return (DerPrintableString)obj; } - throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name); + throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** diff --git a/crypto/src/asn1/DerSequence.cs b/crypto/src/asn1/DerSequence.cs
index b50a77962..a76cf2882 100644 --- a/crypto/src/asn1/DerSequence.cs +++ b/crypto/src/asn1/DerSequence.cs
@@ -1,6 +1,9 @@ +using System; using System.Collections; using System.IO; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1 { public class DerSequence @@ -75,9 +78,9 @@ namespace Org.BouncyCastle.Asn1 dOut.WriteObject(obj); } - dOut.Close(); + Platform.Dispose(dOut); - byte[] bytes = bOut.ToArray(); + byte[] bytes = bOut.ToArray(); derOut.WriteEncoded(Asn1Tags.Sequence | Asn1Tags.Constructed, bytes); } diff --git a/crypto/src/asn1/DerSet.cs b/crypto/src/asn1/DerSet.cs
index c66dde8c7..3df1a6766 100644 --- a/crypto/src/asn1/DerSet.cs +++ b/crypto/src/asn1/DerSet.cs
@@ -1,5 +1,8 @@ +using System; using System.IO; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1 { /** @@ -98,9 +101,9 @@ namespace Org.BouncyCastle.Asn1 dOut.WriteObject(obj); } - dOut.Close(); + Platform.Dispose(dOut); - byte[] bytes = bOut.ToArray(); + byte[] bytes = bOut.ToArray(); derOut.WriteEncoded(Asn1Tags.Set | Asn1Tags.Constructed, bytes); } diff --git a/crypto/src/asn1/DerT61String.cs b/crypto/src/asn1/DerT61String.cs
index 4dee6f30c..746ccfe70 100644 --- a/crypto/src/asn1/DerT61String.cs +++ b/crypto/src/asn1/DerT61String.cs
@@ -25,7 +25,7 @@ namespace Org.BouncyCastle.Asn1 return (DerT61String)obj; } - throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name); + throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** diff --git a/crypto/src/asn1/DerUTCTime.cs b/crypto/src/asn1/DerUTCTime.cs
index ab8ca792d..99af8bf6b 100644 --- a/crypto/src/asn1/DerUTCTime.cs +++ b/crypto/src/asn1/DerUTCTime.cs
@@ -27,7 +27,7 @@ namespace Org.BouncyCastle.Asn1 return (DerUtcTime)obj; } - throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name); + throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** @@ -86,7 +86,11 @@ namespace Org.BouncyCastle.Asn1 public DerUtcTime( DateTime time) { +#if PORTABLE + this.time = time.ToUniversalTime().ToString("yyMMddHHmmss", CultureInfo.InvariantCulture) + "Z"; +#else this.time = time.ToString("yyMMddHHmmss", CultureInfo.InvariantCulture) + "Z"; +#endif } internal DerUtcTime( diff --git a/crypto/src/asn1/DerUTF8String.cs b/crypto/src/asn1/DerUTF8String.cs
index 92a50e824..758a5068d 100644 --- a/crypto/src/asn1/DerUTF8String.cs +++ b/crypto/src/asn1/DerUTF8String.cs
@@ -1,6 +1,8 @@ using System; using System.Text; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1 { /** @@ -24,7 +26,7 @@ namespace Org.BouncyCastle.Asn1 return (DerUtf8String)obj; } - throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name); + throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** diff --git a/crypto/src/asn1/DerUniversalString.cs b/crypto/src/asn1/DerUniversalString.cs
index 305102f2f..284d0f8c5 100644 --- a/crypto/src/asn1/DerUniversalString.cs +++ b/crypto/src/asn1/DerUniversalString.cs
@@ -28,7 +28,7 @@ namespace Org.BouncyCastle.Asn1 return (DerUniversalString)obj; } - throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name); + throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** diff --git a/crypto/src/asn1/DerVisibleString.cs b/crypto/src/asn1/DerVisibleString.cs
index 84c9caade..e1112201a 100644 --- a/crypto/src/asn1/DerVisibleString.cs +++ b/crypto/src/asn1/DerVisibleString.cs
@@ -36,7 +36,7 @@ namespace Org.BouncyCastle.Asn1 return GetInstance(((Asn1TaggedObject)obj).GetObject()); } - throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name); + throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** diff --git a/crypto/src/asn1/anssi/ANSSINamedCurves.cs b/crypto/src/asn1/anssi/ANSSINamedCurves.cs
index c7f9545f2..d0c90ebf1 100644 --- a/crypto/src/asn1/anssi/ANSSINamedCurves.cs +++ b/crypto/src/asn1/anssi/ANSSINamedCurves.cs
@@ -60,7 +60,7 @@ namespace Org.BouncyCastle.Asn1.Anssi DerObjectIdentifier oid, X9ECParametersHolder holder) { - objIds.Add(Platform.ToLowerInvariant(name), oid); + objIds.Add(Platform.ToUpperInvariant(name), oid); names.Add(oid, name); curves.Add(oid, holder); } @@ -99,7 +99,7 @@ namespace Org.BouncyCastle.Asn1.Anssi public static DerObjectIdentifier GetOid( string name) { - return (DerObjectIdentifier)objIds[Platform.ToLowerInvariant(name)]; + return (DerObjectIdentifier)objIds[Platform.ToUpperInvariant(name)]; } /** diff --git a/crypto/src/asn1/cmp/CAKeyUpdAnnContent.cs b/crypto/src/asn1/cmp/CAKeyUpdAnnContent.cs
index 3cdb128a6..b74bac87a 100644 --- a/crypto/src/asn1/cmp/CAKeyUpdAnnContent.cs +++ b/crypto/src/asn1/cmp/CAKeyUpdAnnContent.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cmp { public class CAKeyUpdAnnContent @@ -24,7 +26,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new CAKeyUpdAnnContent((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public virtual CmpCertificate OldWithNew diff --git a/crypto/src/asn1/cmp/CertConfirmContent.cs b/crypto/src/asn1/cmp/CertConfirmContent.cs
index f4016d8d8..370a9e7d6 100644 --- a/crypto/src/asn1/cmp/CertConfirmContent.cs +++ b/crypto/src/asn1/cmp/CertConfirmContent.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cmp { public class CertConfirmContent @@ -20,7 +22,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new CertConfirmContent((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public virtual CertStatus[] ToCertStatusArray() diff --git a/crypto/src/asn1/cmp/CertOrEncCert.cs b/crypto/src/asn1/cmp/CertOrEncCert.cs
index 4c049c180..eb200e1e8 100644 --- a/crypto/src/asn1/cmp/CertOrEncCert.cs +++ b/crypto/src/asn1/cmp/CertOrEncCert.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.Crmf; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cmp { @@ -34,7 +35,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1TaggedObject) return new CertOrEncCert((Asn1TaggedObject)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public CertOrEncCert(CmpCertificate certificate) diff --git a/crypto/src/asn1/cmp/CertRepMessage.cs b/crypto/src/asn1/cmp/CertRepMessage.cs
index c22b079c8..82869784d 100644 --- a/crypto/src/asn1/cmp/CertRepMessage.cs +++ b/crypto/src/asn1/cmp/CertRepMessage.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cmp { public class CertRepMessage @@ -28,7 +30,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new CertRepMessage((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public CertRepMessage(CmpCertificate[] caPubs, CertResponse[] response) diff --git a/crypto/src/asn1/cmp/CertResponse.cs b/crypto/src/asn1/cmp/CertResponse.cs
index 246b8ce70..843fd9299 100644 --- a/crypto/src/asn1/cmp/CertResponse.cs +++ b/crypto/src/asn1/cmp/CertResponse.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cmp { public class CertResponse @@ -45,7 +47,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new CertResponse((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public CertResponse( @@ -107,8 +109,7 @@ namespace Org.BouncyCastle.Asn1.Cmp public override Asn1Object ToAsn1Object() { Asn1EncodableVector v = new Asn1EncodableVector(certReqId, status); - v.AddOptional(certifiedKeyPair); - v.AddOptional(rspInfo); + v.AddOptional(certifiedKeyPair, rspInfo); return new DerSequence(v); } } diff --git a/crypto/src/asn1/cmp/CertStatus.cs b/crypto/src/asn1/cmp/CertStatus.cs
index 52d5ac504..d437b57b2 100644 --- a/crypto/src/asn1/cmp/CertStatus.cs +++ b/crypto/src/asn1/cmp/CertStatus.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Math; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cmp { @@ -43,7 +44,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new CertStatus((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public virtual Asn1OctetString CertHash diff --git a/crypto/src/asn1/cmp/CertifiedKeyPair.cs b/crypto/src/asn1/cmp/CertifiedKeyPair.cs
index 655dde0c5..c06f00019 100644 --- a/crypto/src/asn1/cmp/CertifiedKeyPair.cs +++ b/crypto/src/asn1/cmp/CertifiedKeyPair.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.Crmf; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cmp { @@ -45,7 +46,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new CertifiedKeyPair((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public CertifiedKeyPair( diff --git a/crypto/src/asn1/cmp/Challenge.cs b/crypto/src/asn1/cmp/Challenge.cs
index bee5f96f5..5c78c2a2b 100644 --- a/crypto/src/asn1/cmp/Challenge.cs +++ b/crypto/src/asn1/cmp/Challenge.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cmp { @@ -32,7 +33,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new Challenge((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public virtual AlgorithmIdentifier Owf diff --git a/crypto/src/asn1/cmp/CmpCertificate.cs b/crypto/src/asn1/cmp/CmpCertificate.cs
index 16ee30059..33356b486 100644 --- a/crypto/src/asn1/cmp/CmpCertificate.cs +++ b/crypto/src/asn1/cmp/CmpCertificate.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cmp { @@ -37,7 +38,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1TaggedObject) return new CmpCertificate(AttributeCertificate.GetInstance(((Asn1TaggedObject)obj).GetObject())); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public virtual bool IsX509v3PKCert diff --git a/crypto/src/asn1/cmp/CrlAnnContent.cs b/crypto/src/asn1/cmp/CrlAnnContent.cs
index 3dc11d32c..db8ecfa40 100644 --- a/crypto/src/asn1/cmp/CrlAnnContent.cs +++ b/crypto/src/asn1/cmp/CrlAnnContent.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cmp { @@ -22,7 +23,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new CrlAnnContent((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public virtual CertificateList[] ToCertificateListArray() diff --git a/crypto/src/asn1/cmp/ErrorMsgContent.cs b/crypto/src/asn1/cmp/ErrorMsgContent.cs
index f4dc584ea..5d2132bb8 100644 --- a/crypto/src/asn1/cmp/ErrorMsgContent.cs +++ b/crypto/src/asn1/cmp/ErrorMsgContent.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cmp { public class ErrorMsgContent @@ -35,7 +37,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new ErrorMsgContent((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public ErrorMsgContent(PkiStatusInfo pkiStatusInfo) @@ -86,8 +88,7 @@ namespace Org.BouncyCastle.Asn1.Cmp public override Asn1Object ToAsn1Object() { Asn1EncodableVector v = new Asn1EncodableVector(pkiStatusInfo); - v.AddOptional(errorCode); - v.AddOptional(errorDetails); + v.AddOptional(errorCode, errorDetails); return new DerSequence(v); } } diff --git a/crypto/src/asn1/cmp/GenMsgContent.cs b/crypto/src/asn1/cmp/GenMsgContent.cs
index 9f042491c..f3142b5c6 100644 --- a/crypto/src/asn1/cmp/GenMsgContent.cs +++ b/crypto/src/asn1/cmp/GenMsgContent.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cmp { public class GenMsgContent @@ -20,7 +22,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new GenMsgContent((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public GenMsgContent(params InfoTypeAndValue[] itv) diff --git a/crypto/src/asn1/cmp/GenRepContent.cs b/crypto/src/asn1/cmp/GenRepContent.cs
index 5bdc5550a..3c3573e37 100644 --- a/crypto/src/asn1/cmp/GenRepContent.cs +++ b/crypto/src/asn1/cmp/GenRepContent.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cmp { public class GenRepContent @@ -20,7 +22,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new GenRepContent((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public GenRepContent(params InfoTypeAndValue[] itv) diff --git a/crypto/src/asn1/cmp/InfoTypeAndValue.cs b/crypto/src/asn1/cmp/InfoTypeAndValue.cs
index 9b51dba02..0ce6f73ba 100644 --- a/crypto/src/asn1/cmp/InfoTypeAndValue.cs +++ b/crypto/src/asn1/cmp/InfoTypeAndValue.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cmp { /** @@ -69,7 +71,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new InfoTypeAndValue((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public InfoTypeAndValue( diff --git a/crypto/src/asn1/cmp/KeyRecRepContent.cs b/crypto/src/asn1/cmp/KeyRecRepContent.cs
index b0352f048..00c4612b9 100644 --- a/crypto/src/asn1/cmp/KeyRecRepContent.cs +++ b/crypto/src/asn1/cmp/KeyRecRepContent.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cmp { public class KeyRecRepContent @@ -43,7 +45,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new KeyRecRepContent((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public virtual PkiStatusInfo Status diff --git a/crypto/src/asn1/cmp/OobCertHash.cs b/crypto/src/asn1/cmp/OobCertHash.cs
index 63ddff7c4..cd8192b40 100644 --- a/crypto/src/asn1/cmp/OobCertHash.cs +++ b/crypto/src/asn1/cmp/OobCertHash.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Asn1.Crmf; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cmp { @@ -41,7 +42,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new OobCertHash((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public virtual AlgorithmIdentifier HashAlg diff --git a/crypto/src/asn1/cmp/PKIBody.cs b/crypto/src/asn1/cmp/PKIBody.cs
index 3205a907e..f17eed64d 100644 --- a/crypto/src/asn1/cmp/PKIBody.cs +++ b/crypto/src/asn1/cmp/PKIBody.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Asn1.Crmf; using Org.BouncyCastle.Asn1.Pkcs; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cmp { @@ -47,7 +48,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1TaggedObject) return new PkiBody((Asn1TaggedObject)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } private PkiBody(Asn1TaggedObject tagged) diff --git a/crypto/src/asn1/cmp/PKIConfirmContent.cs b/crypto/src/asn1/cmp/PKIConfirmContent.cs
index 98645766a..d154427a4 100644 --- a/crypto/src/asn1/cmp/PKIConfirmContent.cs +++ b/crypto/src/asn1/cmp/PKIConfirmContent.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cmp { public class PkiConfirmContent @@ -13,7 +15,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Null) return new PkiConfirmContent(); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public PkiConfirmContent() diff --git a/crypto/src/asn1/cmp/PKIFailureInfo.cs b/crypto/src/asn1/cmp/PKIFailureInfo.cs
index 1df0e0693..75a3ff0d7 100644 --- a/crypto/src/asn1/cmp/PKIFailureInfo.cs +++ b/crypto/src/asn1/cmp/PKIFailureInfo.cs
@@ -2,66 +2,89 @@ using System; namespace Org.BouncyCastle.Asn1.Cmp { - /** - * <pre> - * PKIFailureInfo ::= BIT STRING { - * badAlg (0), - * -- unrecognized or unsupported Algorithm Identifier - * badMessageCheck (1), -- integrity check failed (e.g., signature did not verify) - * badRequest (2), - * -- transaction not permitted or supported - * badTime (3), -- messageTime was not sufficiently close to the system time, as defined by local policy - * badCertId (4), -- no certificate could be found matching the provided criteria - * badDataFormat (5), - * -- the data submitted has the wrong format - * wrongAuthority (6), -- the authority indicated in the request is different from the one creating the response token - * incorrectData (7), -- the requester's data is incorrect (for notary services) - * missingTimeStamp (8), -- when the timestamp is missing but should be there (by policy) - * badPOP (9) -- the proof-of-possession failed - * timeNotAvailable (14), - * -- the TSA's time source is not available - * unacceptedPolicy (15), - * -- the requested TSA policy is not supported by the TSA - * unacceptedExtension (16), - * -- the requested extension is not supported by the TSA - * addInfoNotAvailable (17) - * -- the additional information requested could not be understood - * -- or is not available - * systemFailure (25) - * -- the request cannot be handled due to system failure - * </pre> - */ + /** + * <pre> + * PKIFailureInfo ::= BIT STRING { + * badAlg (0), + * -- unrecognized or unsupported Algorithm Identifier + * badMessageCheck (1), -- integrity check failed (e.g., signature did not verify) + * badRequest (2), + * -- transaction not permitted or supported + * badTime (3), -- messageTime was not sufficiently close to the system time, as defined by local policy + * badCertId (4), -- no certificate could be found matching the provided criteria + * badDataFormat (5), + * -- the data submitted has the wrong format + * wrongAuthority (6), -- the authority indicated in the request is different from the one creating the response token + * incorrectData (7), -- the requester's data is incorrect (for notary services) + * missingTimeStamp (8), -- when the timestamp is missing but should be there (by policy) + * badPOP (9) -- the proof-of-possession failed + * certRevoked (10), + * certConfirmed (11), + * wrongIntegrity (12), + * badRecipientNonce (13), + * timeNotAvailable (14), + * -- the TSA's time source is not available + * unacceptedPolicy (15), + * -- the requested TSA policy is not supported by the TSA + * unacceptedExtension (16), + * -- the requested extension is not supported by the TSA + * addInfoNotAvailable (17) + * -- the additional information requested could not be understood + * -- or is not available + * badSenderNonce (18), + * badCertTemplate (19), + * signerNotTrusted (20), + * transactionIdInUse (21), + * unsupportedVersion (22), + * notAuthorized (23), + * systemUnavail (24), + * systemFailure (25), + * -- the request cannot be handled due to system failure + * duplicateCertReq (26) + * </pre> + */ public class PkiFailureInfo : DerBitString { - public const int BadAlg = (1 << 7); // unrecognized or unsupported Algorithm Identifier - public const int BadMessageCheck = (1 << 6); // integrity check failed (e.g., signature did not verify) - public const int BadRequest = (1 << 5); - public const int BadTime = (1 << 4); // -- messageTime was not sufficiently close to the system time, as defined by local policy - public const int BadCertId = (1 << 3); // no certificate could be found matching the provided criteria - public const int BadDataFormat = (1 << 2); - public const int WrongAuthority = (1 << 1); // the authority indicated in the request is different from the one creating the response token - public const int IncorrectData = 1; // the requester's data is incorrect (for notary services) - public const int MissingTimeStamp = (1 << 15); // when the timestamp is missing but should be there (by policy) - public const int BadPop = (1 << 14); // the proof-of-possession failed - public const int TimeNotAvailable = (1 << 9); // the TSA's time source is not available - public const int UnacceptedPolicy = (1 << 8); // the requested TSA policy is not supported by the TSA - public const int UnacceptedExtension = (1 << 23); //the requested extension is not supported by the TSA - public const int AddInfoNotAvailable = (1 << 22); //the additional information requested could not be understood or is not available - public const int SystemFailure = (1 << 30); //the request cannot be handled due to system failure + public const int BadAlg = (1 << 7); // unrecognized or unsupported Algorithm Identifier + public const int BadMessageCheck = (1 << 6); // integrity check failed (e.g., signature did not verify) + public const int BadRequest = (1 << 5); + public const int BadTime = (1 << 4); // -- messageTime was not sufficiently close to the system time, as defined by local policy + public const int BadCertId = (1 << 3); // no certificate could be found matching the provided criteria + public const int BadDataFormat = (1 << 2); + public const int WrongAuthority = (1 << 1); // the authority indicated in the request is different from the one creating the response token + public const int IncorrectData = 1; // the requester's data is incorrect (for notary services) + public const int MissingTimeStamp = (1 << 15); // when the timestamp is missing but should be there (by policy) + public const int BadPop = (1 << 14); // the proof-of-possession failed + public const int CertRevoked = (1 << 13); + public const int CertConfirmed = (1 << 12); + public const int WrongIntegrity = (1 << 11); + public const int BadRecipientNonce = (1 << 10); + public const int TimeNotAvailable = (1 << 9); // the TSA's time source is not available + public const int UnacceptedPolicy = (1 << 8); // the requested TSA policy is not supported by the TSA + public const int UnacceptedExtension = (1 << 23); //the requested extension is not supported by the TSA + public const int AddInfoNotAvailable = (1 << 22); //the additional information requested could not be understood or is not available + public const int BadSenderNonce = (1 << 21); + public const int BadCertTemplate = (1 << 20); + public const int SignerNotTrusted = (1 << 19); + public const int TransactionIdInUse = (1 << 18); + public const int UnsupportedVersion = (1 << 17); + public const int NotAuthorized = (1 << 16); + public const int SystemUnavail = (1 << 31); + public const int SystemFailure = (1 << 30); //the request cannot be handled due to system failure + public const int DuplicateCertReq = (1 << 29); - /** + /** * Basic constructor. */ - public PkiFailureInfo( - int info) - : base(GetBytes(info), GetPadBits(info)) + public PkiFailureInfo(int info) + : base(info) { } public PkiFailureInfo( DerBitString info) - : base(info.GetBytes(), info.PadBits) + : base(info.GetBytes(), info.PadBits) { } diff --git a/crypto/src/asn1/cmp/PKIFreeText.cs b/crypto/src/asn1/cmp/PKIFreeText.cs
index 571c8d93a..fef525465 100644 --- a/crypto/src/asn1/cmp/PKIFreeText.cs +++ b/crypto/src/asn1/cmp/PKIFreeText.cs
@@ -1,6 +1,8 @@ using System; using System.Collections; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cmp { public class PkiFreeText @@ -27,7 +29,7 @@ namespace Org.BouncyCastle.Asn1.Cmp return new PkiFreeText((Asn1Sequence)obj); } - throw new ArgumentException("Unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public PkiFreeText( diff --git a/crypto/src/asn1/cmp/PKIHeader.cs b/crypto/src/asn1/cmp/PKIHeader.cs
index e758e9f16..577cb45df 100644 --- a/crypto/src/asn1/cmp/PKIHeader.cs +++ b/crypto/src/asn1/cmp/PKIHeader.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cmp { @@ -81,7 +82,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new PkiHeader((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public PkiHeader( diff --git a/crypto/src/asn1/cmp/PKIMessages.cs b/crypto/src/asn1/cmp/PKIMessages.cs
index ddabdf4ae..eb01e544a 100644 --- a/crypto/src/asn1/cmp/PKIMessages.cs +++ b/crypto/src/asn1/cmp/PKIMessages.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cmp { public class PkiMessages @@ -20,7 +22,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new PkiMessages((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public PkiMessages(params PkiMessage[] msgs) diff --git a/crypto/src/asn1/cmp/PKIStatus.cs b/crypto/src/asn1/cmp/PKIStatus.cs
index b03dd3d62..ba757dfcf 100644 --- a/crypto/src/asn1/cmp/PKIStatus.cs +++ b/crypto/src/asn1/cmp/PKIStatus.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Math; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cmp { @@ -46,7 +47,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is DerInteger) return new PkiStatusEncodable((DerInteger)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public virtual BigInteger Value diff --git a/crypto/src/asn1/cmp/PKIStatusInfo.cs b/crypto/src/asn1/cmp/PKIStatusInfo.cs
index 2463e0081..b19bf7459 100644 --- a/crypto/src/asn1/cmp/PKIStatusInfo.cs +++ b/crypto/src/asn1/cmp/PKIStatusInfo.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Math; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cmp { @@ -30,7 +31,7 @@ namespace Org.BouncyCastle.Asn1.Cmp return new PkiStatusInfo((Asn1Sequence)obj); } - throw new ArgumentException("Unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public PkiStatusInfo( diff --git a/crypto/src/asn1/cmp/PbmParameter.cs b/crypto/src/asn1/cmp/PbmParameter.cs
index 59b1bd7bb..206b89ba1 100644 --- a/crypto/src/asn1/cmp/PbmParameter.cs +++ b/crypto/src/asn1/cmp/PbmParameter.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cmp { @@ -28,7 +29,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new PbmParameter((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public PbmParameter( diff --git a/crypto/src/asn1/cmp/PollRepContent.cs b/crypto/src/asn1/cmp/PollRepContent.cs
index 4045ac7ed..f8bb098a2 100644 --- a/crypto/src/asn1/cmp/PollRepContent.cs +++ b/crypto/src/asn1/cmp/PollRepContent.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cmp { public class PollRepContent @@ -28,7 +30,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new PollRepContent((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public virtual DerInteger CertReqID diff --git a/crypto/src/asn1/cmp/PollReqContent.cs b/crypto/src/asn1/cmp/PollReqContent.cs
index ca2164151..dd9b0c352 100644 --- a/crypto/src/asn1/cmp/PollReqContent.cs +++ b/crypto/src/asn1/cmp/PollReqContent.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cmp { public class PollReqContent @@ -20,7 +22,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new PollReqContent((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public virtual DerInteger[][] GetCertReqIDs() diff --git a/crypto/src/asn1/cmp/PopoDecKeyChallContent.cs b/crypto/src/asn1/cmp/PopoDecKeyChallContent.cs
index 20b173b85..03a13a5d5 100644 --- a/crypto/src/asn1/cmp/PopoDecKeyChallContent.cs +++ b/crypto/src/asn1/cmp/PopoDecKeyChallContent.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cmp { public class PopoDecKeyChallContent @@ -20,7 +22,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new PopoDecKeyChallContent((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public virtual Challenge[] ToChallengeArray() diff --git a/crypto/src/asn1/cmp/PopoDecKeyRespContent.cs b/crypto/src/asn1/cmp/PopoDecKeyRespContent.cs
index 8c322e4ec..73f59b7c1 100644 --- a/crypto/src/asn1/cmp/PopoDecKeyRespContent.cs +++ b/crypto/src/asn1/cmp/PopoDecKeyRespContent.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cmp { public class PopoDecKeyRespContent @@ -20,7 +22,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new PopoDecKeyRespContent((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public virtual DerInteger[] ToDerIntegerArray() diff --git a/crypto/src/asn1/cmp/ProtectedPart.cs b/crypto/src/asn1/cmp/ProtectedPart.cs
index db6798fee..ed90708f9 100644 --- a/crypto/src/asn1/cmp/ProtectedPart.cs +++ b/crypto/src/asn1/cmp/ProtectedPart.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cmp { public class ProtectedPart @@ -22,7 +24,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new ProtectedPart((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public ProtectedPart(PkiHeader header, PkiBody body) diff --git a/crypto/src/asn1/cmp/RevAnnContent.cs b/crypto/src/asn1/cmp/RevAnnContent.cs
index 2c3bd5f77..d5d42625c 100644 --- a/crypto/src/asn1/cmp/RevAnnContent.cs +++ b/crypto/src/asn1/cmp/RevAnnContent.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Asn1.Crmf; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cmp { @@ -35,7 +36,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new RevAnnContent((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public virtual PkiStatusEncodable Status diff --git a/crypto/src/asn1/cmp/RevDetails.cs b/crypto/src/asn1/cmp/RevDetails.cs
index 6bdf5b2e9..7d2a65ab9 100644 --- a/crypto/src/asn1/cmp/RevDetails.cs +++ b/crypto/src/asn1/cmp/RevDetails.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Asn1.Crmf; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cmp { @@ -27,7 +28,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new RevDetails((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public RevDetails(CertTemplate certDetails) diff --git a/crypto/src/asn1/cmp/RevRepContent.cs b/crypto/src/asn1/cmp/RevRepContent.cs
index 47987265a..8e382a60d 100644 --- a/crypto/src/asn1/cmp/RevRepContent.cs +++ b/crypto/src/asn1/cmp/RevRepContent.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Asn1.Crmf; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cmp { @@ -39,7 +40,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new RevRepContent((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public virtual PkiStatusInfo[] GetStatus() diff --git a/crypto/src/asn1/cmp/RevReqContent.cs b/crypto/src/asn1/cmp/RevReqContent.cs
index fbf869203..1522d3789 100644 --- a/crypto/src/asn1/cmp/RevReqContent.cs +++ b/crypto/src/asn1/cmp/RevReqContent.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cmp { public class RevReqContent @@ -20,7 +22,7 @@ namespace Org.BouncyCastle.Asn1.Cmp if (obj is Asn1Sequence) return new RevReqContent((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public RevReqContent(params RevDetails[] revDetails) diff --git a/crypto/src/asn1/cms/Attribute.cs b/crypto/src/asn1/cms/Attribute.cs
index c4a104a3f..69ac44148 100644 --- a/crypto/src/asn1/cms/Attribute.cs +++ b/crypto/src/asn1/cms/Attribute.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cms { @@ -25,7 +25,7 @@ namespace Org.BouncyCastle.Asn1.Cms if (obj is Asn1Sequence) return new Attribute((Asn1Sequence) obj); - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public Attribute( diff --git a/crypto/src/asn1/cms/AuthEnvelopedData.cs b/crypto/src/asn1/cms/AuthEnvelopedData.cs
index 4260d80f9..c30ec6bbd 100644 --- a/crypto/src/asn1/cms/AuthEnvelopedData.cs +++ b/crypto/src/asn1/cms/AuthEnvelopedData.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cms { public class AuthEnvelopedData @@ -119,7 +121,7 @@ namespace Org.BouncyCastle.Asn1.Cms if (obj is Asn1Sequence) return new AuthEnvelopedData((Asn1Sequence)obj); - throw new ArgumentException("Invalid AuthEnvelopedData: " + obj.GetType().Name); + throw new ArgumentException("Invalid AuthEnvelopedData: " + Platform.GetTypeName(obj)); } public DerInteger Version diff --git a/crypto/src/asn1/cms/AuthenticatedData.cs b/crypto/src/asn1/cms/AuthenticatedData.cs
index 15286d1aa..6f13a6f30 100644 --- a/crypto/src/asn1/cms/AuthenticatedData.cs +++ b/crypto/src/asn1/cms/AuthenticatedData.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cms { @@ -123,7 +124,7 @@ namespace Org.BouncyCastle.Asn1.Cms return new AuthenticatedData((Asn1Sequence)obj); } - throw new ArgumentException("Invalid AuthenticatedData: " + obj.GetType().Name); + throw new ArgumentException("Invalid AuthenticatedData: " + Platform.GetTypeName(obj)); } public DerInteger Version diff --git a/crypto/src/asn1/cms/CompressedData.cs b/crypto/src/asn1/cms/CompressedData.cs
index 5a2869b8c..154ed35c0 100644 --- a/crypto/src/asn1/cms/CompressedData.cs +++ b/crypto/src/asn1/cms/CompressedData.cs
@@ -1,7 +1,7 @@ using System; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cms { @@ -70,7 +70,7 @@ namespace Org.BouncyCastle.Asn1.Cms if (obj is Asn1Sequence) return new CompressedData((Asn1Sequence) obj); - throw new ArgumentException("Invalid CompressedData: " + obj.GetType().Name); + throw new ArgumentException("Invalid CompressedData: " + Platform.GetTypeName(obj)); } public DerInteger Version diff --git a/crypto/src/asn1/cms/ContentInfo.cs b/crypto/src/asn1/cms/ContentInfo.cs
index 278ceca46..f130a4bc7 100644 --- a/crypto/src/asn1/cms/ContentInfo.cs +++ b/crypto/src/asn1/cms/ContentInfo.cs
@@ -1,7 +1,7 @@ using System; using System.Collections; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cms { @@ -20,7 +20,7 @@ namespace Org.BouncyCastle.Asn1.Cms if (obj is Asn1Sequence) return new ContentInfo((Asn1Sequence) obj); - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj)); } public static ContentInfo GetInstance(Asn1TaggedObject obj, bool isExplicit) diff --git a/crypto/src/asn1/cms/EncryptedContentInfo.cs b/crypto/src/asn1/cms/EncryptedContentInfo.cs
index 4fdc47138..999f2a01e 100644 --- a/crypto/src/asn1/cms/EncryptedContentInfo.cs +++ b/crypto/src/asn1/cms/EncryptedContentInfo.cs
@@ -1,7 +1,7 @@ using System; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cms { @@ -50,7 +50,7 @@ namespace Org.BouncyCastle.Asn1.Cms if (obj is Asn1Sequence) return new EncryptedContentInfo((Asn1Sequence)obj); - throw new ArgumentException("Invalid EncryptedContentInfo: " + obj.GetType().Name); + throw new ArgumentException("Invalid EncryptedContentInfo: " + Platform.GetTypeName(obj)); } public DerObjectIdentifier ContentType diff --git a/crypto/src/asn1/cms/EncryptedData.cs b/crypto/src/asn1/cms/EncryptedData.cs
index cb109a640..b8492d14b 100644 --- a/crypto/src/asn1/cms/EncryptedData.cs +++ b/crypto/src/asn1/cms/EncryptedData.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cms { public class EncryptedData @@ -18,7 +20,7 @@ namespace Org.BouncyCastle.Asn1.Cms if (obj is Asn1Sequence) return new EncryptedData((Asn1Sequence) obj); - throw new ArgumentException("Invalid EncryptedData: " + obj.GetType().Name); + throw new ArgumentException("Invalid EncryptedData: " + Platform.GetTypeName(obj)); } public EncryptedData( diff --git a/crypto/src/asn1/cms/Evidence.cs b/crypto/src/asn1/cms/Evidence.cs
index 4745e565b..8374aed55 100644 --- a/crypto/src/asn1/cms/Evidence.cs +++ b/crypto/src/asn1/cms/Evidence.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cms { public class Evidence @@ -28,7 +30,7 @@ namespace Org.BouncyCastle.Asn1.Cms if (obj is Asn1TaggedObject) return new Evidence(Asn1TaggedObject.GetInstance(obj)); - throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } public virtual TimeStampTokenEvidence TstEvidence diff --git a/crypto/src/asn1/cms/KEKIdentifier.cs b/crypto/src/asn1/cms/KEKIdentifier.cs
index e5d1d9090..a42217440 100644 --- a/crypto/src/asn1/cms/KEKIdentifier.cs +++ b/crypto/src/asn1/cms/KEKIdentifier.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cms { @@ -80,7 +80,7 @@ namespace Org.BouncyCastle.Asn1.Cms if (obj is Asn1Sequence) return new KekIdentifier((Asn1Sequence)obj); - throw new ArgumentException("Invalid KekIdentifier: " + obj.GetType().Name); + throw new ArgumentException("Invalid KekIdentifier: " + Platform.GetTypeName(obj)); } public Asn1OctetString KeyIdentifier diff --git a/crypto/src/asn1/cms/KEKRecipientInfo.cs b/crypto/src/asn1/cms/KEKRecipientInfo.cs
index d847b50cc..810e7fc97 100644 --- a/crypto/src/asn1/cms/KEKRecipientInfo.cs +++ b/crypto/src/asn1/cms/KEKRecipientInfo.cs
@@ -1,7 +1,7 @@ using System; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cms { @@ -64,7 +64,7 @@ namespace Org.BouncyCastle.Asn1.Cms if(obj is Asn1Sequence) return new KekRecipientInfo((Asn1Sequence)obj); - throw new ArgumentException("Invalid KekRecipientInfo: " + obj.GetType().Name); + throw new ArgumentException("Invalid KekRecipientInfo: " + Platform.GetTypeName(obj)); } public DerInteger Version diff --git a/crypto/src/asn1/cms/KeyAgreeRecipientIdentifier.cs b/crypto/src/asn1/cms/KeyAgreeRecipientIdentifier.cs
index fa6fdb0f3..0256c2dc2 100644 --- a/crypto/src/asn1/cms/KeyAgreeRecipientIdentifier.cs +++ b/crypto/src/asn1/cms/KeyAgreeRecipientIdentifier.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cms { public class KeyAgreeRecipientIdentifier @@ -42,7 +44,7 @@ namespace Org.BouncyCastle.Asn1.Cms (Asn1TaggedObject)obj, false)); } - throw new ArgumentException("Invalid KeyAgreeRecipientIdentifier: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Invalid KeyAgreeRecipientIdentifier: " + Platform.GetTypeName(obj), "obj"); } private readonly IssuerAndSerialNumber issuerSerial; diff --git a/crypto/src/asn1/cms/KeyAgreeRecipientInfo.cs b/crypto/src/asn1/cms/KeyAgreeRecipientInfo.cs
index aafb008d4..62a38925b 100644 --- a/crypto/src/asn1/cms/KeyAgreeRecipientInfo.cs +++ b/crypto/src/asn1/cms/KeyAgreeRecipientInfo.cs
@@ -1,7 +1,7 @@ using System; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cms { @@ -80,7 +80,7 @@ namespace Org.BouncyCastle.Asn1.Cms return new KeyAgreeRecipientInfo((Asn1Sequence)obj); throw new ArgumentException( - "Illegal object in KeyAgreeRecipientInfo: " + obj.GetType().Name); + "Illegal object in KeyAgreeRecipientInfo: " + Platform.GetTypeName(obj)); } diff --git a/crypto/src/asn1/cms/KeyTransRecipientInfo.cs b/crypto/src/asn1/cms/KeyTransRecipientInfo.cs
index aae18c59d..5e4fd22b4 100644 --- a/crypto/src/asn1/cms/KeyTransRecipientInfo.cs +++ b/crypto/src/asn1/cms/KeyTransRecipientInfo.cs
@@ -1,7 +1,7 @@ using System; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cms { @@ -57,7 +57,7 @@ namespace Org.BouncyCastle.Asn1.Cms return new KeyTransRecipientInfo((Asn1Sequence) obj); throw new ArgumentException( - "Illegal object in KeyTransRecipientInfo: " + obj.GetType().Name); + "Illegal object in KeyTransRecipientInfo: " + Platform.GetTypeName(obj)); } public DerInteger Version diff --git a/crypto/src/asn1/cms/OriginatorIdentifierOrKey.cs b/crypto/src/asn1/cms/OriginatorIdentifierOrKey.cs
index d33a11725..f197fe965 100644 --- a/crypto/src/asn1/cms/OriginatorIdentifierOrKey.cs +++ b/crypto/src/asn1/cms/OriginatorIdentifierOrKey.cs
@@ -1,7 +1,7 @@ using System; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cms { @@ -95,7 +95,7 @@ namespace Org.BouncyCastle.Asn1.Cms if (o is Asn1TaggedObject) return new OriginatorIdentifierOrKey((Asn1TaggedObject)o); - throw new ArgumentException("Invalid OriginatorIdentifierOrKey: " + o.GetType().Name); + throw new ArgumentException("Invalid OriginatorIdentifierOrKey: " + Platform.GetTypeName(o)); } public Asn1Encodable ID diff --git a/crypto/src/asn1/cms/OriginatorInfo.cs b/crypto/src/asn1/cms/OriginatorInfo.cs
index b4549bc36..33b049efa 100644 --- a/crypto/src/asn1/cms/OriginatorInfo.cs +++ b/crypto/src/asn1/cms/OriginatorInfo.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cms { @@ -79,7 +79,7 @@ namespace Org.BouncyCastle.Asn1.Cms if (obj is Asn1Sequence) return new OriginatorInfo((Asn1Sequence)obj); - throw new ArgumentException("Invalid OriginatorInfo: " + obj.GetType().Name); + throw new ArgumentException("Invalid OriginatorInfo: " + Platform.GetTypeName(obj)); } public Asn1Set Certificates diff --git a/crypto/src/asn1/cms/OriginatorPublicKey.cs b/crypto/src/asn1/cms/OriginatorPublicKey.cs
index aabaf4386..9f29c6242 100644 --- a/crypto/src/asn1/cms/OriginatorPublicKey.cs +++ b/crypto/src/asn1/cms/OriginatorPublicKey.cs
@@ -1,29 +1,30 @@ using System; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cms { public class OriginatorPublicKey : Asn1Encodable { - private AlgorithmIdentifier algorithm; - private DerBitString publicKey; + private readonly AlgorithmIdentifier mAlgorithm; + private readonly DerBitString mPublicKey; - public OriginatorPublicKey( + public OriginatorPublicKey( AlgorithmIdentifier algorithm, byte[] publicKey) { - this.algorithm = algorithm; - this.publicKey = new DerBitString(publicKey); + this.mAlgorithm = algorithm; + this.mPublicKey = new DerBitString(publicKey); } + [Obsolete("Use 'GetInstance' instead")] public OriginatorPublicKey( Asn1Sequence seq) { - algorithm = AlgorithmIdentifier.GetInstance(seq[0]); - publicKey = (DerBitString) seq[1]; + this.mAlgorithm = AlgorithmIdentifier.GetInstance(seq[0]); + this.mPublicKey = DerBitString.GetInstance(seq[1]); } /** @@ -55,19 +56,19 @@ namespace Org.BouncyCastle.Asn1.Cms return (OriginatorPublicKey)obj; if (obj is Asn1Sequence) - return new OriginatorPublicKey((Asn1Sequence) obj); + return new OriginatorPublicKey(Asn1Sequence.GetInstance(obj)); - throw new ArgumentException("Invalid OriginatorPublicKey: " + obj.GetType().Name); + throw new ArgumentException("Invalid OriginatorPublicKey: " + Platform.GetTypeName(obj)); } public AlgorithmIdentifier Algorithm { - get { return algorithm; } + get { return mAlgorithm; } } public DerBitString PublicKey { - get { return publicKey; } + get { return mPublicKey; } } /** @@ -81,7 +82,7 @@ namespace Org.BouncyCastle.Asn1.Cms */ public override Asn1Object ToAsn1Object() { - return new DerSequence(algorithm, publicKey); + return new DerSequence(mAlgorithm, mPublicKey); } } } diff --git a/crypto/src/asn1/cms/OtherKeyAttribute.cs b/crypto/src/asn1/cms/OtherKeyAttribute.cs
index 271059175..285c88154 100644 --- a/crypto/src/asn1/cms/OtherKeyAttribute.cs +++ b/crypto/src/asn1/cms/OtherKeyAttribute.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cms { @@ -25,7 +25,7 @@ namespace Org.BouncyCastle.Asn1.Cms if (obj is Asn1Sequence) return new OtherKeyAttribute((Asn1Sequence) obj); - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public OtherKeyAttribute( diff --git a/crypto/src/asn1/cms/PasswordRecipientInfo.cs b/crypto/src/asn1/cms/PasswordRecipientInfo.cs
index 800b57951..7f275fde7 100644 --- a/crypto/src/asn1/cms/PasswordRecipientInfo.cs +++ b/crypto/src/asn1/cms/PasswordRecipientInfo.cs
@@ -1,7 +1,7 @@ using System; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cms { @@ -82,7 +82,7 @@ namespace Org.BouncyCastle.Asn1.Cms if (obj is Asn1Sequence) return new PasswordRecipientInfo((Asn1Sequence) obj); - throw new ArgumentException("Invalid PasswordRecipientInfo: " + obj.GetType().Name); + throw new ArgumentException("Invalid PasswordRecipientInfo: " + Platform.GetTypeName(obj)); } public DerInteger Version diff --git a/crypto/src/asn1/cms/RecipientEncryptedKey.cs b/crypto/src/asn1/cms/RecipientEncryptedKey.cs
index 5ba25a742..1afba4ab1 100644 --- a/crypto/src/asn1/cms/RecipientEncryptedKey.cs +++ b/crypto/src/asn1/cms/RecipientEncryptedKey.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cms { public class RecipientEncryptedKey @@ -50,7 +52,7 @@ namespace Org.BouncyCastle.Asn1.Cms return new RecipientEncryptedKey((Asn1Sequence) obj); } - throw new ArgumentException("Invalid RecipientEncryptedKey: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Invalid RecipientEncryptedKey: " + Platform.GetTypeName(obj), "obj"); } public RecipientEncryptedKey( diff --git a/crypto/src/asn1/cms/RecipientIdentifier.cs b/crypto/src/asn1/cms/RecipientIdentifier.cs
index 4982bc16a..f29fa8d7c 100644 --- a/crypto/src/asn1/cms/RecipientIdentifier.cs +++ b/crypto/src/asn1/cms/RecipientIdentifier.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cms { @@ -49,7 +49,7 @@ namespace Org.BouncyCastle.Asn1.Cms return new RecipientIdentifier((Asn1Object) o); throw new ArgumentException( - "Illegal object in RecipientIdentifier: " + o.GetType().Name); + "Illegal object in RecipientIdentifier: " + Platform.GetTypeName(o)); } public bool IsTagged diff --git a/crypto/src/asn1/cms/RecipientInfo.cs b/crypto/src/asn1/cms/RecipientInfo.cs
index daaf5a5e4..c03ad907f 100644 --- a/crypto/src/asn1/cms/RecipientInfo.cs +++ b/crypto/src/asn1/cms/RecipientInfo.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cms { @@ -57,7 +57,7 @@ namespace Org.BouncyCastle.Asn1.Cms if (o is Asn1TaggedObject) return new RecipientInfo((Asn1TaggedObject) o); - throw new ArgumentException("unknown object in factory: " + o.GetType().Name); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(o)); } public DerInteger Version diff --git a/crypto/src/asn1/cms/RecipientKeyIdentifier.cs b/crypto/src/asn1/cms/RecipientKeyIdentifier.cs
index f3e45644b..995ddab51 100644 --- a/crypto/src/asn1/cms/RecipientKeyIdentifier.cs +++ b/crypto/src/asn1/cms/RecipientKeyIdentifier.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cms { @@ -97,7 +97,7 @@ namespace Org.BouncyCastle.Asn1.Cms if (obj is Asn1Sequence) return new RecipientKeyIdentifier((Asn1Sequence) obj); - throw new ArgumentException("Invalid RecipientKeyIdentifier: " + obj.GetType().Name); + throw new ArgumentException("Invalid RecipientKeyIdentifier: " + Platform.GetTypeName(obj)); } public Asn1OctetString SubjectKeyIdentifier diff --git a/crypto/src/asn1/cms/SignedData.cs b/crypto/src/asn1/cms/SignedData.cs
index 6cea79a49..957b81cd8 100644 --- a/crypto/src/asn1/cms/SignedData.cs +++ b/crypto/src/asn1/cms/SignedData.cs
@@ -1,7 +1,7 @@ using System; using System.Collections; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cms { @@ -34,7 +34,7 @@ namespace Org.BouncyCastle.Asn1.Cms if (obj is Asn1Sequence) return new SignedData((Asn1Sequence) obj); - throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public SignedData( diff --git a/crypto/src/asn1/cms/SignedDataParser.cs b/crypto/src/asn1/cms/SignedDataParser.cs
index 341309263..cd07f4057 100644 --- a/crypto/src/asn1/cms/SignedDataParser.cs +++ b/crypto/src/asn1/cms/SignedDataParser.cs
@@ -1,6 +1,8 @@ using System; using System.IO; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cms { /** @@ -32,7 +34,7 @@ namespace Org.BouncyCastle.Asn1.Cms if (o is Asn1SequenceParser) return new SignedDataParser((Asn1SequenceParser)o); - throw new IOException("unknown object encountered: " + o.GetType().Name); + throw new IOException("unknown object encountered: " + Platform.GetTypeName(o)); } public SignedDataParser( diff --git a/crypto/src/asn1/cms/SignerIdentifier.cs b/crypto/src/asn1/cms/SignerIdentifier.cs
index 5742cee75..195ab741f 100644 --- a/crypto/src/asn1/cms/SignerIdentifier.cs +++ b/crypto/src/asn1/cms/SignerIdentifier.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cms { @@ -49,7 +49,7 @@ namespace Org.BouncyCastle.Asn1.Cms return new SignerIdentifier((Asn1Object) o); throw new ArgumentException( - "Illegal object in SignerIdentifier: " + o.GetType().Name); + "Illegal object in SignerIdentifier: " + Platform.GetTypeName(o)); } public bool IsTagged diff --git a/crypto/src/asn1/cms/SignerInfo.cs b/crypto/src/asn1/cms/SignerInfo.cs
index a4e893d96..b6bd319b0 100644 --- a/crypto/src/asn1/cms/SignerInfo.cs +++ b/crypto/src/asn1/cms/SignerInfo.cs
@@ -1,8 +1,8 @@ using System; using System.Collections; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Cms { @@ -26,7 +26,7 @@ namespace Org.BouncyCastle.Asn1.Cms if (obj is Asn1Sequence) return new SignerInfo((Asn1Sequence) obj); - throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public SignerInfo( diff --git a/crypto/src/asn1/cms/Time.cs b/crypto/src/asn1/cms/Time.cs
index e5730245e..52fb4f937 100644 --- a/crypto/src/asn1/cms/Time.cs +++ b/crypto/src/asn1/cms/Time.cs
@@ -1,6 +1,8 @@ using System; using System.Globalization; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cms { public class Time @@ -58,7 +60,7 @@ namespace Org.BouncyCastle.Asn1.Cms if (obj is DerGeneralizedTime) return new Time((DerGeneralizedTime)obj); - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public string TimeString diff --git a/crypto/src/asn1/cms/ecc/MQVuserKeyingMaterial.cs b/crypto/src/asn1/cms/ecc/MQVuserKeyingMaterial.cs
index 53c5c706b..dc4ac1a4a 100644 --- a/crypto/src/asn1/cms/ecc/MQVuserKeyingMaterial.cs +++ b/crypto/src/asn1/cms/ecc/MQVuserKeyingMaterial.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Cms.Ecc { public class MQVuserKeyingMaterial @@ -67,7 +69,7 @@ namespace Org.BouncyCastle.Asn1.Cms.Ecc return new MQVuserKeyingMaterial((Asn1Sequence)obj); } - throw new ArgumentException("Invalid MQVuserKeyingMaterial: " + obj.GetType().Name); + throw new ArgumentException("Invalid MQVuserKeyingMaterial: " + Platform.GetTypeName(obj)); } public OriginatorPublicKey EphemeralPublicKey diff --git a/crypto/src/asn1/crmf/AttributeTypeAndValue.cs b/crypto/src/asn1/crmf/AttributeTypeAndValue.cs
index 823668992..0a4b5bdbe 100644 --- a/crypto/src/asn1/crmf/AttributeTypeAndValue.cs +++ b/crypto/src/asn1/crmf/AttributeTypeAndValue.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Crmf { public class AttributeTypeAndValue @@ -22,7 +24,7 @@ namespace Org.BouncyCastle.Asn1.Crmf if (obj is Asn1Sequence) return new AttributeTypeAndValue((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public AttributeTypeAndValue( diff --git a/crypto/src/asn1/crmf/CertId.cs b/crypto/src/asn1/crmf/CertId.cs
index 10c2cc8b4..f0cc94691 100644 --- a/crypto/src/asn1/crmf/CertId.cs +++ b/crypto/src/asn1/crmf/CertId.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Crmf { @@ -24,7 +25,7 @@ namespace Org.BouncyCastle.Asn1.Crmf if (obj is Asn1Sequence) return new CertId((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public static CertId GetInstance(Asn1TaggedObject obj, bool isExplicit) diff --git a/crypto/src/asn1/crmf/CertReqMessages.cs b/crypto/src/asn1/crmf/CertReqMessages.cs
index 9247281e8..422950b9e 100644 --- a/crypto/src/asn1/crmf/CertReqMessages.cs +++ b/crypto/src/asn1/crmf/CertReqMessages.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Crmf { public class CertReqMessages @@ -20,7 +22,7 @@ namespace Org.BouncyCastle.Asn1.Crmf if (obj is Asn1Sequence) return new CertReqMessages((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public CertReqMessages(params CertReqMsg[] msgs) diff --git a/crypto/src/asn1/crmf/CertReqMsg.cs b/crypto/src/asn1/crmf/CertReqMsg.cs
index 2ca319a57..20fd4179a 100644 --- a/crypto/src/asn1/crmf/CertReqMsg.cs +++ b/crypto/src/asn1/crmf/CertReqMsg.cs
@@ -98,8 +98,7 @@ namespace Org.BouncyCastle.Asn1.Crmf public override Asn1Object ToAsn1Object() { Asn1EncodableVector v = new Asn1EncodableVector(certReq); - v.AddOptional(popo); - v.AddOptional(regInfo); + v.AddOptional(popo, regInfo); return new DerSequence(v); } } diff --git a/crypto/src/asn1/crmf/Controls.cs b/crypto/src/asn1/crmf/Controls.cs
index cc52ea4bb..e8b9f3db0 100644 --- a/crypto/src/asn1/crmf/Controls.cs +++ b/crypto/src/asn1/crmf/Controls.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Crmf { public class Controls @@ -20,7 +22,7 @@ namespace Org.BouncyCastle.Asn1.Crmf if (obj is Asn1Sequence) return new Controls((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public Controls(params AttributeTypeAndValue[] atvs) diff --git a/crypto/src/asn1/crmf/PKIArchiveOptions.cs b/crypto/src/asn1/crmf/PKIArchiveOptions.cs
index 910f73b22..1813d87a7 100644 --- a/crypto/src/asn1/crmf/PKIArchiveOptions.cs +++ b/crypto/src/asn1/crmf/PKIArchiveOptions.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Crmf { public class PkiArchiveOptions @@ -19,7 +21,7 @@ namespace Org.BouncyCastle.Asn1.Crmf if (obj is Asn1TaggedObject) return new PkiArchiveOptions((Asn1TaggedObject)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } private PkiArchiveOptions(Asn1TaggedObject tagged) diff --git a/crypto/src/asn1/crmf/PKIPublicationInfo.cs b/crypto/src/asn1/crmf/PKIPublicationInfo.cs
index c8bc1403e..a7d2bc603 100644 --- a/crypto/src/asn1/crmf/PKIPublicationInfo.cs +++ b/crypto/src/asn1/crmf/PKIPublicationInfo.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Crmf { public class PkiPublicationInfo @@ -22,7 +24,7 @@ namespace Org.BouncyCastle.Asn1.Crmf if (obj is Asn1Sequence) return new PkiPublicationInfo((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public virtual DerInteger Action diff --git a/crypto/src/asn1/crmf/PKMacValue.cs b/crypto/src/asn1/crmf/PKMacValue.cs
index 20a08fd1d..e104c08dd 100644 --- a/crypto/src/asn1/crmf/PKMacValue.cs +++ b/crypto/src/asn1/crmf/PKMacValue.cs
@@ -2,6 +2,7 @@ using Org.BouncyCastle.Asn1.Cmp; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Crmf { @@ -28,7 +29,7 @@ namespace Org.BouncyCastle.Asn1.Crmf if (obj is Asn1Sequence) return new PKMacValue((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public static PKMacValue GetInstance(Asn1TaggedObject obj, bool isExplicit) diff --git a/crypto/src/asn1/crmf/PopoSigningKey.cs b/crypto/src/asn1/crmf/PopoSigningKey.cs
index 614278eda..1c24db8ee 100644 --- a/crypto/src/asn1/crmf/PopoSigningKey.cs +++ b/crypto/src/asn1/crmf/PopoSigningKey.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Crmf { @@ -37,7 +38,7 @@ namespace Org.BouncyCastle.Asn1.Crmf if (obj is Asn1Sequence) return new PopoSigningKey((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public static PopoSigningKey GetInstance(Asn1TaggedObject obj, bool isExplicit) diff --git a/crypto/src/asn1/crmf/PopoSigningKeyInput.cs b/crypto/src/asn1/crmf/PopoSigningKeyInput.cs
index 63695262f..e43fa138e 100644 --- a/crypto/src/asn1/crmf/PopoSigningKeyInput.cs +++ b/crypto/src/asn1/crmf/PopoSigningKeyInput.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Crmf { @@ -40,7 +41,7 @@ namespace Org.BouncyCastle.Asn1.Crmf if (obj is Asn1Sequence) return new PopoSigningKeyInput((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } /** Creates a new PopoSigningKeyInput with sender name as authInfo. */ diff --git a/crypto/src/asn1/crmf/ProofOfPossession.cs b/crypto/src/asn1/crmf/ProofOfPossession.cs
index fc00edb32..8957169d7 100644 --- a/crypto/src/asn1/crmf/ProofOfPossession.cs +++ b/crypto/src/asn1/crmf/ProofOfPossession.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Crmf { public class ProofOfPossession @@ -41,7 +43,7 @@ namespace Org.BouncyCastle.Asn1.Crmf if (obj is Asn1TaggedObject) return new ProofOfPossession((Asn1TaggedObject)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } /** Creates a ProofOfPossession with type raVerified. */ diff --git a/crypto/src/asn1/crmf/SinglePubInfo.cs b/crypto/src/asn1/crmf/SinglePubInfo.cs
index eaf8a3efd..5205ce366 100644 --- a/crypto/src/asn1/crmf/SinglePubInfo.cs +++ b/crypto/src/asn1/crmf/SinglePubInfo.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Crmf { @@ -28,7 +29,7 @@ namespace Org.BouncyCastle.Asn1.Crmf if (obj is Asn1Sequence) return new SinglePubInfo((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Invalid object: " + Platform.GetTypeName(obj), "obj"); } public virtual GeneralName PubLocation diff --git a/crypto/src/asn1/cryptopro/ECGOST3410ParamSetParameters.cs b/crypto/src/asn1/cryptopro/ECGOST3410ParamSetParameters.cs
index 6f4435d7b..8e568a229 100644 --- a/crypto/src/asn1/cryptopro/ECGOST3410ParamSetParameters.cs +++ b/crypto/src/asn1/cryptopro/ECGOST3410ParamSetParameters.cs
@@ -2,6 +2,7 @@ using System; using System.Collections; using Org.BouncyCastle.Math; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.CryptoPro { @@ -30,7 +31,7 @@ namespace Org.BouncyCastle.Asn1.CryptoPro return new ECGost3410ParamSetParameters((Asn1Sequence) obj); } - throw new ArgumentException("Invalid GOST3410Parameter: " + obj.GetType().Name); + throw new ArgumentException("Invalid GOST3410Parameter: " + Platform.GetTypeName(obj)); } public ECGost3410ParamSetParameters( diff --git a/crypto/src/asn1/cryptopro/GOST28147Parameters.cs b/crypto/src/asn1/cryptopro/GOST28147Parameters.cs
index eb7e0e3f6..fc0d792d1 100644 --- a/crypto/src/asn1/cryptopro/GOST28147Parameters.cs +++ b/crypto/src/asn1/cryptopro/GOST28147Parameters.cs
@@ -1,7 +1,7 @@ using System; using System.Collections; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.CryptoPro { @@ -31,7 +31,7 @@ namespace Org.BouncyCastle.Asn1.CryptoPro return new Gost28147Parameters((Asn1Sequence) obj); } - throw new ArgumentException("Invalid GOST3410Parameter: " + obj.GetType().Name); + throw new ArgumentException("Invalid GOST3410Parameter: " + Platform.GetTypeName(obj)); } private Gost28147Parameters( diff --git a/crypto/src/asn1/cryptopro/GOST3410ParamSetParameters.cs b/crypto/src/asn1/cryptopro/GOST3410ParamSetParameters.cs
index f133cdf1b..b347f8dbd 100644 --- a/crypto/src/asn1/cryptopro/GOST3410ParamSetParameters.cs +++ b/crypto/src/asn1/cryptopro/GOST3410ParamSetParameters.cs
@@ -1,8 +1,8 @@ using System; using System.Collections; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Math; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.CryptoPro { @@ -32,7 +32,7 @@ namespace Org.BouncyCastle.Asn1.CryptoPro return new Gost3410ParamSetParameters((Asn1Sequence) obj); } - throw new ArgumentException("Invalid GOST3410Parameter: " + obj.GetType().Name); + throw new ArgumentException("Invalid GOST3410Parameter: " + Platform.GetTypeName(obj)); } public Gost3410ParamSetParameters( diff --git a/crypto/src/asn1/cryptopro/GOST3410PublicKeyAlgParameters.cs b/crypto/src/asn1/cryptopro/GOST3410PublicKeyAlgParameters.cs
index 8bc1460af..10c45ba4d 100644 --- a/crypto/src/asn1/cryptopro/GOST3410PublicKeyAlgParameters.cs +++ b/crypto/src/asn1/cryptopro/GOST3410PublicKeyAlgParameters.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.CryptoPro { @@ -31,7 +31,7 @@ namespace Org.BouncyCastle.Asn1.CryptoPro return new Gost3410PublicKeyAlgParameters((Asn1Sequence) obj); } - throw new ArgumentException("Invalid GOST3410Parameter: " + obj.GetType().Name); + throw new ArgumentException("Invalid GOST3410Parameter: " + Platform.GetTypeName(obj)); } public Gost3410PublicKeyAlgParameters( diff --git a/crypto/src/asn1/esf/CertificateValues.cs b/crypto/src/asn1/esf/CertificateValues.cs
index e0fb39b83..30a719177 100644 --- a/crypto/src/asn1/esf/CertificateValues.cs +++ b/crypto/src/asn1/esf/CertificateValues.cs
@@ -2,6 +2,7 @@ using System; using System.Collections; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; namespace Org.BouncyCastle.Asn1.Esf @@ -28,7 +29,7 @@ namespace Org.BouncyCastle.Asn1.Esf throw new ArgumentException( "Unknown object in 'CertificateValues' factory: " - + obj.GetType().Name, + + Platform.GetTypeName(obj), "obj"); } diff --git a/crypto/src/asn1/esf/CommitmentTypeIndication.cs b/crypto/src/asn1/esf/CommitmentTypeIndication.cs
index 8342cbf8d..196a613a6 100644 --- a/crypto/src/asn1/esf/CommitmentTypeIndication.cs +++ b/crypto/src/asn1/esf/CommitmentTypeIndication.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Esf { @@ -21,7 +21,7 @@ namespace Org.BouncyCastle.Asn1.Esf throw new ArgumentException( "Unknown object in 'CommitmentTypeIndication' factory: " - + obj.GetType().Name, + + Platform.GetTypeName(obj), "obj"); } diff --git a/crypto/src/asn1/esf/CommitmentTypeQualifier.cs b/crypto/src/asn1/esf/CommitmentTypeQualifier.cs
index 09ff70714..30bf0edfc 100644 --- a/crypto/src/asn1/esf/CommitmentTypeQualifier.cs +++ b/crypto/src/asn1/esf/CommitmentTypeQualifier.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Esf { @@ -84,7 +84,7 @@ namespace Org.BouncyCastle.Asn1.Esf throw new ArgumentException( "Unknown object in 'CommitmentTypeQualifier' factory: " - + obj.GetType().Name, + + Platform.GetTypeName(obj), "obj"); } diff --git a/crypto/src/asn1/esf/CompleteCertificateRefs.cs b/crypto/src/asn1/esf/CompleteCertificateRefs.cs
index 7f1c835c9..af93700be 100644 --- a/crypto/src/asn1/esf/CompleteCertificateRefs.cs +++ b/crypto/src/asn1/esf/CompleteCertificateRefs.cs
@@ -1,6 +1,7 @@ using System; using System.Collections; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; namespace Org.BouncyCastle.Asn1.Esf @@ -27,7 +28,7 @@ namespace Org.BouncyCastle.Asn1.Esf throw new ArgumentException( "Unknown object in 'CompleteCertificateRefs' factory: " - + obj.GetType().Name, + + Platform.GetTypeName(obj), "obj"); } diff --git a/crypto/src/asn1/esf/CompleteRevocationRefs.cs b/crypto/src/asn1/esf/CompleteRevocationRefs.cs
index 4e1fb403d..348e63fdb 100644 --- a/crypto/src/asn1/esf/CompleteRevocationRefs.cs +++ b/crypto/src/asn1/esf/CompleteRevocationRefs.cs
@@ -1,6 +1,7 @@ using System; using System.Collections; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; namespace Org.BouncyCastle.Asn1.Esf @@ -27,7 +28,7 @@ namespace Org.BouncyCastle.Asn1.Esf throw new ArgumentException( "Unknown object in 'CompleteRevocationRefs' factory: " - + obj.GetType().Name, + + Platform.GetTypeName(obj), "obj"); } diff --git a/crypto/src/asn1/esf/CrlIdentifier.cs b/crypto/src/asn1/esf/CrlIdentifier.cs
index dfff7d838..96b50e211 100644 --- a/crypto/src/asn1/esf/CrlIdentifier.cs +++ b/crypto/src/asn1/esf/CrlIdentifier.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Math; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Esf { @@ -34,7 +35,7 @@ namespace Org.BouncyCastle.Asn1.Esf throw new ArgumentException( "Unknown object in 'CrlIdentifier' factory: " - + obj.GetType().Name, + + Platform.GetTypeName(obj), "obj"); } diff --git a/crypto/src/asn1/esf/CrlListID.cs b/crypto/src/asn1/esf/CrlListID.cs
index 2aae9b965..fbd4fb27c 100644 --- a/crypto/src/asn1/esf/CrlListID.cs +++ b/crypto/src/asn1/esf/CrlListID.cs
@@ -1,6 +1,7 @@ using System; using System.Collections; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; namespace Org.BouncyCastle.Asn1.Esf @@ -30,7 +31,7 @@ namespace Org.BouncyCastle.Asn1.Esf throw new ArgumentException( "Unknown object in 'CrlListID' factory: " - + obj.GetType().Name, + + Platform.GetTypeName(obj), "obj"); } diff --git a/crypto/src/asn1/esf/CrlOcspRef.cs b/crypto/src/asn1/esf/CrlOcspRef.cs
index c8e10d504..6153e0c53 100644 --- a/crypto/src/asn1/esf/CrlOcspRef.cs +++ b/crypto/src/asn1/esf/CrlOcspRef.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Esf { /// <remarks> @@ -30,7 +32,7 @@ namespace Org.BouncyCastle.Asn1.Esf throw new ArgumentException( "Unknown object in 'CrlOcspRef' factory: " - + obj.GetType().Name, + + Platform.GetTypeName(obj), "obj"); } diff --git a/crypto/src/asn1/esf/CrlValidatedID.cs b/crypto/src/asn1/esf/CrlValidatedID.cs
index 165f547a8..e8cd17a19 100644 --- a/crypto/src/asn1/esf/CrlValidatedID.cs +++ b/crypto/src/asn1/esf/CrlValidatedID.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Esf { /// <remarks> @@ -27,7 +29,7 @@ namespace Org.BouncyCastle.Asn1.Esf throw new ArgumentException( "Unknown object in 'CrlValidatedID' factory: " - + obj.GetType().Name, + + Platform.GetTypeName(obj), "obj"); } diff --git a/crypto/src/asn1/esf/OcspIdentifier.cs b/crypto/src/asn1/esf/OcspIdentifier.cs
index 949b68243..e65f1cfe7 100644 --- a/crypto/src/asn1/esf/OcspIdentifier.cs +++ b/crypto/src/asn1/esf/OcspIdentifier.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.Ocsp; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Esf { @@ -32,7 +33,7 @@ namespace Org.BouncyCastle.Asn1.Esf throw new ArgumentException( "Unknown object in 'OcspIdentifier' factory: " - + obj.GetType().Name, + + Platform.GetTypeName(obj), "obj"); } diff --git a/crypto/src/asn1/esf/OcspListID.cs b/crypto/src/asn1/esf/OcspListID.cs
index 1f3f3a337..1c8edb16b 100644 --- a/crypto/src/asn1/esf/OcspListID.cs +++ b/crypto/src/asn1/esf/OcspListID.cs
@@ -1,6 +1,7 @@ using System; using System.Collections; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; namespace Org.BouncyCastle.Asn1.Esf @@ -29,7 +30,7 @@ namespace Org.BouncyCastle.Asn1.Esf throw new ArgumentException( "Unknown object in 'OcspListID' factory: " - + obj.GetType().Name, + + Platform.GetTypeName(obj), "obj"); } diff --git a/crypto/src/asn1/esf/OcspResponsesID.cs b/crypto/src/asn1/esf/OcspResponsesID.cs
index e09508a01..8718188fc 100644 --- a/crypto/src/asn1/esf/OcspResponsesID.cs +++ b/crypto/src/asn1/esf/OcspResponsesID.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Esf { /// <remarks> @@ -28,7 +30,7 @@ namespace Org.BouncyCastle.Asn1.Esf throw new ArgumentException( "Unknown object in 'OcspResponsesID' factory: " - + obj.GetType().Name, + + Platform.GetTypeName(obj), "obj"); } diff --git a/crypto/src/asn1/esf/OtherCertID.cs b/crypto/src/asn1/esf/OtherCertID.cs
index 6d1255535..19d173aa2 100644 --- a/crypto/src/asn1/esf/OtherCertID.cs +++ b/crypto/src/asn1/esf/OtherCertID.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Esf { @@ -29,7 +30,7 @@ namespace Org.BouncyCastle.Asn1.Esf throw new ArgumentException( "Unknown object in 'OtherCertID' factory: " - + obj.GetType().Name, + + Platform.GetTypeName(obj), "obj"); } diff --git a/crypto/src/asn1/esf/OtherHashAlgAndValue.cs b/crypto/src/asn1/esf/OtherHashAlgAndValue.cs
index b6bd4f498..00eb24c54 100644 --- a/crypto/src/asn1/esf/OtherHashAlgAndValue.cs +++ b/crypto/src/asn1/esf/OtherHashAlgAndValue.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Esf { @@ -34,7 +35,7 @@ namespace Org.BouncyCastle.Asn1.Esf throw new ArgumentException( "Unknown object in 'OtherHashAlgAndValue' factory: " - + obj.GetType().Name, + + Platform.GetTypeName(obj), "obj"); } diff --git a/crypto/src/asn1/esf/OtherRevRefs.cs b/crypto/src/asn1/esf/OtherRevRefs.cs
index 56713e3f2..446031e5a 100644 --- a/crypto/src/asn1/esf/OtherRevRefs.cs +++ b/crypto/src/asn1/esf/OtherRevRefs.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Esf { /// <remarks> @@ -31,7 +33,7 @@ namespace Org.BouncyCastle.Asn1.Esf throw new ArgumentException( "Unknown object in 'OtherRevRefs' factory: " - + obj.GetType().Name, + + Platform.GetTypeName(obj), "obj"); } diff --git a/crypto/src/asn1/esf/OtherRevVals.cs b/crypto/src/asn1/esf/OtherRevVals.cs
index b88a1a72a..7b904565a 100644 --- a/crypto/src/asn1/esf/OtherRevVals.cs +++ b/crypto/src/asn1/esf/OtherRevVals.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Esf { /// <remarks> @@ -31,7 +33,7 @@ namespace Org.BouncyCastle.Asn1.Esf throw new ArgumentException( "Unknown object in 'OtherRevVals' factory: " - + obj.GetType().Name, + + Platform.GetTypeName(obj), "obj"); } diff --git a/crypto/src/asn1/esf/OtherSigningCertificate.cs b/crypto/src/asn1/esf/OtherSigningCertificate.cs
index 90e385a33..f7b9f5e66 100644 --- a/crypto/src/asn1/esf/OtherSigningCertificate.cs +++ b/crypto/src/asn1/esf/OtherSigningCertificate.cs
@@ -2,6 +2,7 @@ using System; using System.Collections; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; namespace Org.BouncyCastle.Asn1.Esf @@ -31,7 +32,7 @@ namespace Org.BouncyCastle.Asn1.Esf throw new ArgumentException( "Unknown object in 'OtherSigningCertificate' factory: " - + obj.GetType().Name, + + Platform.GetTypeName(obj), "obj"); } diff --git a/crypto/src/asn1/esf/SigPolicyQualifierInfo.cs b/crypto/src/asn1/esf/SigPolicyQualifierInfo.cs
index 2d36bc751..470c5c873 100644 --- a/crypto/src/asn1/esf/SigPolicyQualifierInfo.cs +++ b/crypto/src/asn1/esf/SigPolicyQualifierInfo.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Esf { /// <remarks> @@ -29,7 +31,7 @@ namespace Org.BouncyCastle.Asn1.Esf throw new ArgumentException( "Unknown object in 'SigPolicyQualifierInfo' factory: " - + obj.GetType().Name, + + Platform.GetTypeName(obj), "obj"); } diff --git a/crypto/src/asn1/esf/SignaturePolicyId.cs b/crypto/src/asn1/esf/SignaturePolicyId.cs
index 545be2cf4..7146bb4c1 100644 --- a/crypto/src/asn1/esf/SignaturePolicyId.cs +++ b/crypto/src/asn1/esf/SignaturePolicyId.cs
@@ -1,6 +1,7 @@ using System; using System.Collections; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; namespace Org.BouncyCastle.Asn1.Esf @@ -36,7 +37,7 @@ namespace Org.BouncyCastle.Asn1.Esf throw new ArgumentException( "Unknown object in 'SignaturePolicyId' factory: " - + obj.GetType().Name, + + Platform.GetTypeName(obj), "obj"); } diff --git a/crypto/src/asn1/esf/SignaturePolicyIdentifier.cs b/crypto/src/asn1/esf/SignaturePolicyIdentifier.cs
index 3a639f444..12257f2f0 100644 --- a/crypto/src/asn1/esf/SignaturePolicyIdentifier.cs +++ b/crypto/src/asn1/esf/SignaturePolicyIdentifier.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Esf { /// <remarks> @@ -31,7 +33,7 @@ namespace Org.BouncyCastle.Asn1.Esf throw new ArgumentException( "Unknown object in 'SignaturePolicyIdentifier' factory: " - + obj.GetType().Name, + + Platform.GetTypeName(obj), "obj"); } diff --git a/crypto/src/asn1/esf/SignerAttribute.cs b/crypto/src/asn1/esf/SignerAttribute.cs
index ddee53c69..39bd910b2 100644 --- a/crypto/src/asn1/esf/SignerAttribute.cs +++ b/crypto/src/asn1/esf/SignerAttribute.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Esf { @@ -21,7 +22,7 @@ namespace Org.BouncyCastle.Asn1.Esf throw new ArgumentException( "Unknown object in 'SignerAttribute' factory: " - + obj.GetType().Name, + + Platform.GetTypeName(obj), "obj"); } diff --git a/crypto/src/asn1/ess/ContentHints.cs b/crypto/src/asn1/ess/ContentHints.cs
index a430fea8d..cfd174b3a 100644 --- a/crypto/src/asn1/ess/ContentHints.cs +++ b/crypto/src/asn1/ess/ContentHints.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Ess { public class ContentHints @@ -22,7 +24,7 @@ namespace Org.BouncyCastle.Asn1.Ess } throw new ArgumentException("unknown object in 'ContentHints' factory : " - + o.GetType().Name + "."); + + Platform.GetTypeName(o) + "."); } /** diff --git a/crypto/src/asn1/ess/ContentIdentifier.cs b/crypto/src/asn1/ess/ContentIdentifier.cs
index 8058dcc53..430185e11 100644 --- a/crypto/src/asn1/ess/ContentIdentifier.cs +++ b/crypto/src/asn1/ess/ContentIdentifier.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Ess { public class ContentIdentifier @@ -22,7 +24,7 @@ namespace Org.BouncyCastle.Asn1.Ess throw new ArgumentException( "unknown object in 'ContentIdentifier' factory : " - + o.GetType().Name + "."); + + Platform.GetTypeName(o) + "."); } /** diff --git a/crypto/src/asn1/ess/ESSCertID.cs b/crypto/src/asn1/ess/ESSCertID.cs
index 4d449a746..b4465ea4f 100644 --- a/crypto/src/asn1/ess/ESSCertID.cs +++ b/crypto/src/asn1/ess/ESSCertID.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Ess { @@ -25,7 +26,7 @@ namespace Org.BouncyCastle.Asn1.Ess throw new ArgumentException( "unknown object in 'EssCertID' factory : " - + o.GetType().Name + "."); + + Platform.GetTypeName(o) + "."); } /** diff --git a/crypto/src/asn1/ess/OtherCertID.cs b/crypto/src/asn1/ess/OtherCertID.cs
index 972ef8c6b..7794c81fa 100644 --- a/crypto/src/asn1/ess/OtherCertID.cs +++ b/crypto/src/asn1/ess/OtherCertID.cs
@@ -1,6 +1,8 @@ using System; +using Org.BouncyCastle.Asn1.Oiw; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Ess { @@ -26,7 +28,7 @@ namespace Org.BouncyCastle.Asn1.Ess throw new ArgumentException( "unknown object in 'OtherCertID' factory : " - + o.GetType().Name + "."); + + Platform.GetTypeName(o) + "."); } /** @@ -78,7 +80,7 @@ namespace Org.BouncyCastle.Asn1.Ess if (otherCertHash.ToAsn1Object() is Asn1OctetString) { // SHA-1 - return new AlgorithmIdentifier("1.3.14.3.2.26"); + return new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1); } return DigestInfo.GetInstance(otherCertHash).AlgorithmID; diff --git a/crypto/src/asn1/ess/OtherSigningCertificate.cs b/crypto/src/asn1/ess/OtherSigningCertificate.cs
index c165fecea..6cef92b62 100644 --- a/crypto/src/asn1/ess/OtherSigningCertificate.cs +++ b/crypto/src/asn1/ess/OtherSigningCertificate.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Ess { @@ -25,7 +26,7 @@ namespace Org.BouncyCastle.Asn1.Ess throw new ArgumentException( "unknown object in 'OtherSigningCertificate' factory : " - + o.GetType().Name + "."); + + Platform.GetTypeName(o) + "."); } /** diff --git a/crypto/src/asn1/ess/SigningCertificate.cs b/crypto/src/asn1/ess/SigningCertificate.cs
index 366749bc3..51f67c1ff 100644 --- a/crypto/src/asn1/ess/SigningCertificate.cs +++ b/crypto/src/asn1/ess/SigningCertificate.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Ess { @@ -24,7 +25,7 @@ namespace Org.BouncyCastle.Asn1.Ess throw new ArgumentException( "unknown object in 'SigningCertificate' factory : " - + o.GetType().Name + "."); + + Platform.GetTypeName(o) + "."); } /** diff --git a/crypto/src/asn1/ess/SigningCertificateV2.cs b/crypto/src/asn1/ess/SigningCertificateV2.cs
index cabecc1ba..91eda9e33 100644 --- a/crypto/src/asn1/ess/SigningCertificateV2.cs +++ b/crypto/src/asn1/ess/SigningCertificateV2.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Ess { @@ -21,7 +22,7 @@ namespace Org.BouncyCastle.Asn1.Ess throw new ArgumentException( "unknown object in 'SigningCertificateV2' factory : " - + o.GetType().Name + "."); + + Platform.GetTypeName(o) + "."); } private SigningCertificateV2( diff --git a/crypto/src/asn1/isismtt/ocsp/CertHash.cs b/crypto/src/asn1/isismtt/ocsp/CertHash.cs
index da5b530e4..5773e1c56 100644 --- a/crypto/src/asn1/isismtt/ocsp/CertHash.cs +++ b/crypto/src/asn1/isismtt/ocsp/CertHash.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.IsisMtt.Ocsp { @@ -43,7 +44,7 @@ namespace Org.BouncyCastle.Asn1.IsisMtt.Ocsp return new CertHash((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } /** diff --git a/crypto/src/asn1/isismtt/ocsp/RequestedCertificate.cs b/crypto/src/asn1/isismtt/ocsp/RequestedCertificate.cs
index 7724bfed6..413b3bd7f 100644 --- a/crypto/src/asn1/isismtt/ocsp/RequestedCertificate.cs +++ b/crypto/src/asn1/isismtt/ocsp/RequestedCertificate.cs
@@ -1,6 +1,8 @@ using System; using System.IO; + using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.IsisMtt.Ocsp { @@ -69,7 +71,7 @@ namespace Org.BouncyCastle.Asn1.IsisMtt.Ocsp return new RequestedCertificate((Asn1TaggedObject) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public static RequestedCertificate GetInstance( diff --git a/crypto/src/asn1/isismtt/x509/AdditionalInformationSyntax.cs b/crypto/src/asn1/isismtt/x509/AdditionalInformationSyntax.cs
index f81d459c6..53a8e98a7 100644 --- a/crypto/src/asn1/isismtt/x509/AdditionalInformationSyntax.cs +++ b/crypto/src/asn1/isismtt/x509/AdditionalInformationSyntax.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X500; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.IsisMtt.X509 { @@ -26,7 +27,7 @@ namespace Org.BouncyCastle.Asn1.IsisMtt.X509 if (obj is IAsn1String) return new AdditionalInformationSyntax(DirectoryString.GetInstance(obj)); - throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } private AdditionalInformationSyntax( diff --git a/crypto/src/asn1/isismtt/x509/AdmissionSyntax.cs b/crypto/src/asn1/isismtt/x509/AdmissionSyntax.cs
index dc473ee08..4b6264ae0 100644 --- a/crypto/src/asn1/isismtt/x509/AdmissionSyntax.cs +++ b/crypto/src/asn1/isismtt/x509/AdmissionSyntax.cs
@@ -1,277 +1,278 @@ -using System; +using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.IsisMtt.X509 { - /** - * Attribute to indicate admissions to certain professions. - * <p/> - * <pre> - * AdmissionSyntax ::= SEQUENCE - * { - * admissionAuthority GeneralName OPTIONAL, - * contentsOfAdmissions SEQUENCE OF Admissions - * } - * <p/> - * Admissions ::= SEQUENCE - * { - * admissionAuthority [0] EXPLICIT GeneralName OPTIONAL - * namingAuthority [1] EXPLICIT NamingAuthority OPTIONAL - * professionInfos SEQUENCE OF ProfessionInfo - * } - * <p/> - * NamingAuthority ::= SEQUENCE - * { - * namingAuthorityId OBJECT IDENTIFIER OPTIONAL, - * namingAuthorityUrl IA5String OPTIONAL, - * namingAuthorityText DirectoryString(SIZE(1..128)) OPTIONAL - * } - * <p/> - * ProfessionInfo ::= SEQUENCE - * { - * namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL, - * professionItems SEQUENCE OF DirectoryString (SIZE(1..128)), - * professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL, - * registrationNumber PrintableString(SIZE(1..128)) OPTIONAL, - * addProfessionInfo OCTET STRING OPTIONAL - * } - * </pre> - * <p/> - * <p/> - * ISIS-MTT PROFILE: The relatively complex structure of AdmissionSyntax - * supports the following concepts and requirements: - * <ul> - * <li> External institutions (e.g. professional associations, chambers, unions, - * administrative bodies, companies, etc.), which are responsible for granting - * and verifying professional admissions, are indicated by means of the data - * field admissionAuthority. An admission authority is indicated by a - * GeneralName object. Here an X.501 directory name (distinguished name) can be - * indicated in the field directoryName, a URL address can be indicated in the - * field uniformResourceIdentifier, and an object identifier can be indicated in - * the field registeredId.</li> - * <li> The names of authorities which are responsible for the administration of - * title registers are indicated in the data field namingAuthority. The name of - * the authority can be identified by an object identifier in the field - * namingAuthorityId, by means of a text string in the field - * namingAuthorityText, by means of a URL address in the field - * namingAuthorityUrl, or by a combination of them. For example, the text string - * can contain the name of the authority, the country and the name of the title - * register. The URL-option refers to a web page which contains lists with - * �officially� registered professions (text and possibly OID) as well as - * further information on these professions. Object identifiers for the - * component namingAuthorityId are grouped under the OID-branch - * id-isis-at-namingAuthorities and must be applied for.</li> - * <li>See http://www.teletrust.de/anwend.asp?Id=30200&amp;Sprache=E_&amp;HomePG=0 - * for an application form and http://www.teletrust.de/links.asp?id=30220,11 - * for an overview of registered naming authorities.</li> - * <li> By means of the data type ProfessionInfo certain professions, - * specializations, disciplines, fields of activity, etc. are identified. A - * profession is represented by one or more text strings, resp. profession OIDs - * in the fields professionItems and professionOIDs and by a registration number - * in the field registrationNumber. An indication in text form must always be - * present, whereas the other indications are optional. The component - * addProfessionInfo may contain additional applicationspecific information in - * DER-encoded form.</li> - * </ul> - * <p/> - * By means of different namingAuthority-OIDs or profession OIDs hierarchies of - * professions, specializations, disciplines, fields of activity, etc. can be - * expressed. The issuing admission authority should always be indicated (field - * admissionAuthority), whenever a registration number is presented. Still, - * information on admissions can be given without indicating an admission or a - * naming authority by the exclusive use of the component professionItems. In - * this case the certification authority is responsible for the verification of - * the admission information. - * <p/> - * <p/> - * <p/> - * This attribute is single-valued. Still, several admissions can be captured in - * the sequence structure of the component contentsOfAdmissions of - * AdmissionSyntax or in the component professionInfos of Admissions. The - * component admissionAuthority of AdmissionSyntax serves as default value for - * the component admissionAuthority of Admissions. Within the latter component - * the default value can be overwritten, in case that another authority is - * responsible. The component namingAuthority of Admissions serves as a default - * value for the component namingAuthority of ProfessionInfo. Within the latter - * component the default value can be overwritten, in case that another naming - * authority needs to be recorded. - * <p/> - * The length of the string objects is limited to 128 characters. It is - * recommended to indicate a namingAuthorityURL in all issued attribute - * certificates. If a namingAuthorityURL is indicated, the field professionItems - * of ProfessionInfo should contain only registered titles. If the field - * professionOIDs exists, it has to contain the OIDs of the professions listed - * in professionItems in the same order. In general, the field professionInfos - * should contain only one entry, unless the admissions that are to be listed - * are logically connected (e.g. they have been issued under the same admission - * number). - * - * @see Org.BouncyCastle.Asn1.IsisMtt.X509.Admissions - * @see Org.BouncyCastle.Asn1.IsisMtt.X509.ProfessionInfo - * @see Org.BouncyCastle.Asn1.IsisMtt.X509.NamingAuthority - */ - public class AdmissionSyntax - : Asn1Encodable - { - private readonly GeneralName admissionAuthority; - private readonly Asn1Sequence contentsOfAdmissions; + /** + * Attribute to indicate admissions to certain professions. + * <p/> + * <pre> + * AdmissionSyntax ::= SEQUENCE + * { + * admissionAuthority GeneralName OPTIONAL, + * contentsOfAdmissions SEQUENCE OF Admissions + * } + * <p/> + * Admissions ::= SEQUENCE + * { + * admissionAuthority [0] EXPLICIT GeneralName OPTIONAL + * namingAuthority [1] EXPLICIT NamingAuthority OPTIONAL + * professionInfos SEQUENCE OF ProfessionInfo + * } + * <p/> + * NamingAuthority ::= SEQUENCE + * { + * namingAuthorityId OBJECT IDENTIFIER OPTIONAL, + * namingAuthorityUrl IA5String OPTIONAL, + * namingAuthorityText DirectoryString(SIZE(1..128)) OPTIONAL + * } + * <p/> + * ProfessionInfo ::= SEQUENCE + * { + * namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL, + * professionItems SEQUENCE OF DirectoryString (SIZE(1..128)), + * professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL, + * registrationNumber PrintableString(SIZE(1..128)) OPTIONAL, + * addProfessionInfo OCTET STRING OPTIONAL + * } + * </pre> + * <p/> + * <p/> + * ISIS-MTT PROFILE: The relatively complex structure of AdmissionSyntax + * supports the following concepts and requirements: + * <ul> + * <li> External institutions (e.g. professional associations, chambers, unions, + * administrative bodies, companies, etc.), which are responsible for granting + * and verifying professional admissions, are indicated by means of the data + * field admissionAuthority. An admission authority is indicated by a + * GeneralName object. Here an X.501 directory name (distinguished name) can be + * indicated in the field directoryName, a URL address can be indicated in the + * field uniformResourceIdentifier, and an object identifier can be indicated in + * the field registeredId.</li> + * <li> The names of authorities which are responsible for the administration of + * title registers are indicated in the data field namingAuthority. The name of + * the authority can be identified by an object identifier in the field + * namingAuthorityId, by means of a text string in the field + * namingAuthorityText, by means of a URL address in the field + * namingAuthorityUrl, or by a combination of them. For example, the text string + * can contain the name of the authority, the country and the name of the title + * register. The URL-option refers to a web page which contains lists with + * officially registered professions (text and possibly OID) as well as + * further information on these professions. Object identifiers for the + * component namingAuthorityId are grouped under the OID-branch + * id-isis-at-namingAuthorities and must be applied for.</li> + * <li>See http://www.teletrust.de/anwend.asp?Id=30200&amp;Sprache=E_&amp;HomePG=0 + * for an application form and http://www.teletrust.de/links.asp?id=30220,11 + * for an overview of registered naming authorities.</li> + * <li> By means of the data type ProfessionInfo certain professions, + * specializations, disciplines, fields of activity, etc. are identified. A + * profession is represented by one or more text strings, resp. profession OIDs + * in the fields professionItems and professionOIDs and by a registration number + * in the field registrationNumber. An indication in text form must always be + * present, whereas the other indications are optional. The component + * addProfessionInfo may contain additional applicationspecific information in + * DER-encoded form.</li> + * </ul> + * <p/> + * By means of different namingAuthority-OIDs or profession OIDs hierarchies of + * professions, specializations, disciplines, fields of activity, etc. can be + * expressed. The issuing admission authority should always be indicated (field + * admissionAuthority), whenever a registration number is presented. Still, + * information on admissions can be given without indicating an admission or a + * naming authority by the exclusive use of the component professionItems. In + * this case the certification authority is responsible for the verification of + * the admission information. + * <p/> + * <p/> + * <p/> + * This attribute is single-valued. Still, several admissions can be captured in + * the sequence structure of the component contentsOfAdmissions of + * AdmissionSyntax or in the component professionInfos of Admissions. The + * component admissionAuthority of AdmissionSyntax serves as default value for + * the component admissionAuthority of Admissions. Within the latter component + * the default value can be overwritten, in case that another authority is + * responsible. The component namingAuthority of Admissions serves as a default + * value for the component namingAuthority of ProfessionInfo. Within the latter + * component the default value can be overwritten, in case that another naming + * authority needs to be recorded. + * <p/> + * The length of the string objects is limited to 128 characters. It is + * recommended to indicate a namingAuthorityURL in all issued attribute + * certificates. If a namingAuthorityURL is indicated, the field professionItems + * of ProfessionInfo should contain only registered titles. If the field + * professionOIDs exists, it has to contain the OIDs of the professions listed + * in professionItems in the same order. In general, the field professionInfos + * should contain only one entry, unless the admissions that are to be listed + * are logically connected (e.g. they have been issued under the same admission + * number). + * + * @see Org.BouncyCastle.Asn1.IsisMtt.X509.Admissions + * @see Org.BouncyCastle.Asn1.IsisMtt.X509.ProfessionInfo + * @see Org.BouncyCastle.Asn1.IsisMtt.X509.NamingAuthority + */ + public class AdmissionSyntax + : Asn1Encodable + { + private readonly GeneralName admissionAuthority; + private readonly Asn1Sequence contentsOfAdmissions; - public static AdmissionSyntax GetInstance( - object obj) - { - if (obj == null || obj is AdmissionSyntax) - { - return (AdmissionSyntax) obj; - } + public static AdmissionSyntax GetInstance( + object obj) + { + if (obj == null || obj is AdmissionSyntax) + { + return (AdmissionSyntax)obj; + } - if (obj is Asn1Sequence) - { - return new AdmissionSyntax((Asn1Sequence) obj); - } + if (obj is Asn1Sequence) + { + return new AdmissionSyntax((Asn1Sequence)obj); + } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); - } + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); + } - /** - * Constructor from Asn1Sequence. - * <p/> - * The sequence is of type ProcurationSyntax: - * <p/> - * <pre> - * AdmissionSyntax ::= SEQUENCE - * { - * admissionAuthority GeneralName OPTIONAL, - * contentsOfAdmissions SEQUENCE OF Admissions - * } - * <p/> - * Admissions ::= SEQUENCE - * { - * admissionAuthority [0] EXPLICIT GeneralName OPTIONAL - * namingAuthority [1] EXPLICIT NamingAuthority OPTIONAL - * professionInfos SEQUENCE OF ProfessionInfo - * } - * <p/> - * NamingAuthority ::= SEQUENCE - * { - * namingAuthorityId OBJECT IDENTIFIER OPTIONAL, - * namingAuthorityUrl IA5String OPTIONAL, - * namingAuthorityText DirectoryString(SIZE(1..128)) OPTIONAL - * } - * <p/> - * ProfessionInfo ::= SEQUENCE - * { - * namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL, - * professionItems SEQUENCE OF DirectoryString (SIZE(1..128)), - * professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL, - * registrationNumber PrintableString(SIZE(1..128)) OPTIONAL, - * addProfessionInfo OCTET STRING OPTIONAL - * } - * </pre> - * - * @param seq The ASN.1 sequence. - */ - private AdmissionSyntax( - Asn1Sequence seq) - { - switch (seq.Count) - { - case 1: - this.contentsOfAdmissions = DerSequence.GetInstance(seq[0]); - break; - case 2: - admissionAuthority = GeneralName.GetInstance(seq[0]); - contentsOfAdmissions = DerSequence.GetInstance(seq[1]); - break; - default: - throw new ArgumentException("Bad sequence size: " + seq.Count); - } - } + /** + * Constructor from Asn1Sequence. + * <p/> + * The sequence is of type ProcurationSyntax: + * <p/> + * <pre> + * AdmissionSyntax ::= SEQUENCE + * { + * admissionAuthority GeneralName OPTIONAL, + * contentsOfAdmissions SEQUENCE OF Admissions + * } + * <p/> + * Admissions ::= SEQUENCE + * { + * admissionAuthority [0] EXPLICIT GeneralName OPTIONAL + * namingAuthority [1] EXPLICIT NamingAuthority OPTIONAL + * professionInfos SEQUENCE OF ProfessionInfo + * } + * <p/> + * NamingAuthority ::= SEQUENCE + * { + * namingAuthorityId OBJECT IDENTIFIER OPTIONAL, + * namingAuthorityUrl IA5String OPTIONAL, + * namingAuthorityText DirectoryString(SIZE(1..128)) OPTIONAL + * } + * <p/> + * ProfessionInfo ::= SEQUENCE + * { + * namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL, + * professionItems SEQUENCE OF DirectoryString (SIZE(1..128)), + * professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL, + * registrationNumber PrintableString(SIZE(1..128)) OPTIONAL, + * addProfessionInfo OCTET STRING OPTIONAL + * } + * </pre> + * + * @param seq The ASN.1 sequence. + */ + private AdmissionSyntax( + Asn1Sequence seq) + { + switch (seq.Count) + { + case 1: + this.contentsOfAdmissions = DerSequence.GetInstance(seq[0]); + break; + case 2: + admissionAuthority = GeneralName.GetInstance(seq[0]); + contentsOfAdmissions = DerSequence.GetInstance(seq[1]); + break; + default: + throw new ArgumentException("Bad sequence size: " + seq.Count); + } + } - /** - * Constructor from given details. - * - * @param admissionAuthority The admission authority. - * @param contentsOfAdmissions The admissions. - */ - public AdmissionSyntax( - GeneralName admissionAuthority, - Asn1Sequence contentsOfAdmissions) - { - this.admissionAuthority = admissionAuthority; - this.contentsOfAdmissions = contentsOfAdmissions; - } + /** + * Constructor from given details. + * + * @param admissionAuthority The admission authority. + * @param contentsOfAdmissions The admissions. + */ + public AdmissionSyntax( + GeneralName admissionAuthority, + Asn1Sequence contentsOfAdmissions) + { + this.admissionAuthority = admissionAuthority; + this.contentsOfAdmissions = contentsOfAdmissions; + } - /** - * Produce an object suitable for an Asn1OutputStream. - * <p/> - * Returns: - * <p/> - * <pre> - * AdmissionSyntax ::= SEQUENCE - * { - * admissionAuthority GeneralName OPTIONAL, - * contentsOfAdmissions SEQUENCE OF Admissions - * } - * <p/> - * Admissions ::= SEQUENCE - * { - * admissionAuthority [0] EXPLICIT GeneralName OPTIONAL - * namingAuthority [1] EXPLICIT NamingAuthority OPTIONAL - * professionInfos SEQUENCE OF ProfessionInfo - * } - * <p/> - * NamingAuthority ::= SEQUENCE - * { - * namingAuthorityId OBJECT IDENTIFIER OPTIONAL, - * namingAuthorityUrl IA5String OPTIONAL, - * namingAuthorityText DirectoryString(SIZE(1..128)) OPTIONAL - * } - * <p/> - * ProfessionInfo ::= SEQUENCE - * { - * namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL, - * professionItems SEQUENCE OF DirectoryString (SIZE(1..128)), - * professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL, - * registrationNumber PrintableString(SIZE(1..128)) OPTIONAL, - * addProfessionInfo OCTET STRING OPTIONAL - * } - * </pre> - * - * @return an Asn1Object - */ - public override Asn1Object ToAsn1Object() - { - Asn1EncodableVector vec = new Asn1EncodableVector(); - if (admissionAuthority != null) - { - vec.Add(admissionAuthority); - } - vec.Add(contentsOfAdmissions); - return new DerSequence(vec); - } + /** + * Produce an object suitable for an Asn1OutputStream. + * <p/> + * Returns: + * <p/> + * <pre> + * AdmissionSyntax ::= SEQUENCE + * { + * admissionAuthority GeneralName OPTIONAL, + * contentsOfAdmissions SEQUENCE OF Admissions + * } + * <p/> + * Admissions ::= SEQUENCE + * { + * admissionAuthority [0] EXPLICIT GeneralName OPTIONAL + * namingAuthority [1] EXPLICIT NamingAuthority OPTIONAL + * professionInfos SEQUENCE OF ProfessionInfo + * } + * <p/> + * NamingAuthority ::= SEQUENCE + * { + * namingAuthorityId OBJECT IDENTIFIER OPTIONAL, + * namingAuthorityUrl IA5String OPTIONAL, + * namingAuthorityText DirectoryString(SIZE(1..128)) OPTIONAL + * } + * <p/> + * ProfessionInfo ::= SEQUENCE + * { + * namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL, + * professionItems SEQUENCE OF DirectoryString (SIZE(1..128)), + * professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL, + * registrationNumber PrintableString(SIZE(1..128)) OPTIONAL, + * addProfessionInfo OCTET STRING OPTIONAL + * } + * </pre> + * + * @return an Asn1Object + */ + public override Asn1Object ToAsn1Object() + { + Asn1EncodableVector vec = new Asn1EncodableVector(); + if (admissionAuthority != null) + { + vec.Add(admissionAuthority); + } + vec.Add(contentsOfAdmissions); + return new DerSequence(vec); + } - /** - * @return Returns the admissionAuthority if present, null otherwise. - */ - public virtual GeneralName AdmissionAuthority - { - get { return admissionAuthority; } - } + /** + * @return Returns the admissionAuthority if present, null otherwise. + */ + public virtual GeneralName AdmissionAuthority + { + get { return admissionAuthority; } + } - /** - * @return Returns the contentsOfAdmissions. - */ - public virtual Admissions[] GetContentsOfAdmissions() - { - Admissions[] result = new Admissions[contentsOfAdmissions.Count]; + /** + * @return Returns the contentsOfAdmissions. + */ + public virtual Admissions[] GetContentsOfAdmissions() + { + Admissions[] result = new Admissions[contentsOfAdmissions.Count]; - for (int i = 0; i < contentsOfAdmissions.Count; ++i) - { - result[i] = Admissions.GetInstance(contentsOfAdmissions[i]); - } + for (int i = 0; i < contentsOfAdmissions.Count; ++i) + { + result[i] = Admissions.GetInstance(contentsOfAdmissions[i]); + } - return result; - } - } + return result; + } + } } diff --git a/crypto/src/asn1/isismtt/x509/Admissions.cs b/crypto/src/asn1/isismtt/x509/Admissions.cs
index 40290c608..e914db0b5 100644 --- a/crypto/src/asn1/isismtt/x509/Admissions.cs +++ b/crypto/src/asn1/isismtt/x509/Admissions.cs
@@ -2,6 +2,7 @@ using System; using System.Collections; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.IsisMtt.X509 { @@ -42,7 +43,7 @@ namespace Org.BouncyCastle.Asn1.IsisMtt.X509 return new Admissions((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } /** @@ -103,7 +104,7 @@ namespace Org.BouncyCastle.Asn1.IsisMtt.X509 professionInfos = Asn1Sequence.GetInstance(o); if (e.MoveNext()) { - throw new ArgumentException("Bad object encountered: " + e.Current.GetType().Name); + throw new ArgumentException("Bad object encountered: " + Platform.GetTypeName(e.Current)); } } diff --git a/crypto/src/asn1/isismtt/x509/DeclarationOfMajority.cs b/crypto/src/asn1/isismtt/x509/DeclarationOfMajority.cs
index dfac65040..c4ebb2b72 100644 --- a/crypto/src/asn1/isismtt/x509/DeclarationOfMajority.cs +++ b/crypto/src/asn1/isismtt/x509/DeclarationOfMajority.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.IsisMtt.X509 { /** @@ -80,7 +82,7 @@ namespace Org.BouncyCastle.Asn1.IsisMtt.X509 return new DeclarationOfMajority((Asn1TaggedObject) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } private DeclarationOfMajority( diff --git a/crypto/src/asn1/isismtt/x509/MonetaryLimit.cs b/crypto/src/asn1/isismtt/x509/MonetaryLimit.cs
index 80b6b684b..b792fffda 100644 --- a/crypto/src/asn1/isismtt/x509/MonetaryLimit.cs +++ b/crypto/src/asn1/isismtt/x509/MonetaryLimit.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Math; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.IsisMtt.X509 { @@ -48,7 +49,7 @@ namespace Org.BouncyCastle.Asn1.IsisMtt.X509 return new MonetaryLimit(Asn1Sequence.GetInstance(obj)); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } private MonetaryLimit( diff --git a/crypto/src/asn1/isismtt/x509/NamingAuthority.cs b/crypto/src/asn1/isismtt/x509/NamingAuthority.cs
index 4262fd0f4..35539f488 100644 --- a/crypto/src/asn1/isismtt/x509/NamingAuthority.cs +++ b/crypto/src/asn1/isismtt/x509/NamingAuthority.cs
@@ -2,6 +2,7 @@ using System; using System.Collections; using Org.BouncyCastle.Asn1.X500; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.IsisMtt.X509 { @@ -49,7 +50,7 @@ namespace Org.BouncyCastle.Asn1.IsisMtt.X509 return new NamingAuthority((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public static NamingAuthority GetInstance( @@ -99,7 +100,7 @@ namespace Org.BouncyCastle.Asn1.IsisMtt.X509 } else { - throw new ArgumentException("Bad object encountered: " + o.GetType().Name); + throw new ArgumentException("Bad object encountered: " + Platform.GetTypeName(o)); } } @@ -116,7 +117,7 @@ namespace Org.BouncyCastle.Asn1.IsisMtt.X509 } else { - throw new ArgumentException("Bad object encountered: " + o.GetType().Name); + throw new ArgumentException("Bad object encountered: " + Platform.GetTypeName(o)); } } @@ -129,7 +130,7 @@ namespace Org.BouncyCastle.Asn1.IsisMtt.X509 } else { - throw new ArgumentException("Bad object encountered: " + o.GetType().Name); + throw new ArgumentException("Bad object encountered: " + Platform.GetTypeName(o)); } } } diff --git a/crypto/src/asn1/isismtt/x509/ProcurationSyntax.cs b/crypto/src/asn1/isismtt/x509/ProcurationSyntax.cs
index a25df225e..f42364699 100644 --- a/crypto/src/asn1/isismtt/x509/ProcurationSyntax.cs +++ b/crypto/src/asn1/isismtt/x509/ProcurationSyntax.cs
@@ -3,6 +3,7 @@ using System.Collections; using Org.BouncyCastle.Asn1.X500; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.IsisMtt.X509 { @@ -61,7 +62,7 @@ namespace Org.BouncyCastle.Asn1.IsisMtt.X509 return new ProcurationSyntax((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } /** diff --git a/crypto/src/asn1/isismtt/x509/ProfessionInfo.cs b/crypto/src/asn1/isismtt/x509/ProfessionInfo.cs
index 3bad2cbc4..671a465af 100644 --- a/crypto/src/asn1/isismtt/x509/ProfessionInfo.cs +++ b/crypto/src/asn1/isismtt/x509/ProfessionInfo.cs
@@ -2,6 +2,7 @@ using System; using System.Collections; using Org.BouncyCastle.Asn1.X500; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.IsisMtt.X509 { @@ -157,7 +158,7 @@ namespace Org.BouncyCastle.Asn1.IsisMtt.X509 return new ProfessionInfo((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } /** @@ -218,7 +219,7 @@ namespace Org.BouncyCastle.Asn1.IsisMtt.X509 } else { - throw new ArgumentException("Bad object encountered: " + o.GetType().Name); + throw new ArgumentException("Bad object encountered: " + Platform.GetTypeName(o)); } } @@ -235,7 +236,7 @@ namespace Org.BouncyCastle.Asn1.IsisMtt.X509 } else { - throw new ArgumentException("Bad object encountered: " + o.GetType().Name); + throw new ArgumentException("Bad object encountered: " + Platform.GetTypeName(o)); } } @@ -248,7 +249,7 @@ namespace Org.BouncyCastle.Asn1.IsisMtt.X509 } else { - throw new ArgumentException("Bad object encountered: " + o.GetType().Name); + throw new ArgumentException("Bad object encountered: " + Platform.GetTypeName(o)); } } } diff --git a/crypto/src/asn1/isismtt/x509/Restriction.cs b/crypto/src/asn1/isismtt/x509/Restriction.cs
index c97766999..75df25201 100644 --- a/crypto/src/asn1/isismtt/x509/Restriction.cs +++ b/crypto/src/asn1/isismtt/x509/Restriction.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X500; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.IsisMtt.X509 { @@ -25,7 +26,7 @@ namespace Org.BouncyCastle.Asn1.IsisMtt.X509 if (obj is IAsn1String) return new Restriction(DirectoryString.GetInstance(obj)); - throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().Name, "obj"); + throw new ArgumentException("Unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } /** diff --git a/crypto/src/asn1/misc/NetscapeCertType.cs b/crypto/src/asn1/misc/NetscapeCertType.cs
index d5db6523d..d809eae66 100644 --- a/crypto/src/asn1/misc/NetscapeCertType.cs +++ b/crypto/src/asn1/misc/NetscapeCertType.cs
@@ -36,7 +36,7 @@ namespace Org.BouncyCastle.Asn1.Misc * e.g. (X509NetscapeCertType.sslCA | X509NetscapeCertType.smimeCA) */ public NetscapeCertType(int usage) - : base(GetBytes(usage), GetPadBits(usage)) + : base(usage) { } diff --git a/crypto/src/asn1/mozilla/PublicKeyAndChallenge.cs b/crypto/src/asn1/mozilla/PublicKeyAndChallenge.cs
index 1e08b809d..ff2a1199f 100644 --- a/crypto/src/asn1/mozilla/PublicKeyAndChallenge.cs +++ b/crypto/src/asn1/mozilla/PublicKeyAndChallenge.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Mozilla { @@ -38,7 +39,7 @@ namespace Org.BouncyCastle.Asn1.Mozilla throw new ArgumentException( "unknown object in 'PublicKeyAndChallenge' factory : " - + obj.GetType().Name + "."); + + Platform.GetTypeName(obj) + "."); } public PublicKeyAndChallenge( diff --git a/crypto/src/asn1/ocsp/BasicOCSPResponse.cs b/crypto/src/asn1/ocsp/BasicOCSPResponse.cs
index dd666addf..e6aa1f86b 100644 --- a/crypto/src/asn1/ocsp/BasicOCSPResponse.cs +++ b/crypto/src/asn1/ocsp/BasicOCSPResponse.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Ocsp { @@ -33,7 +34,7 @@ namespace Org.BouncyCastle.Asn1.Ocsp return new BasicOcspResponse((Asn1Sequence)obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public BasicOcspResponse( @@ -94,7 +95,12 @@ namespace Org.BouncyCastle.Asn1.Ocsp get { return signature; } } - [Obsolete("Use Certs property instead")] + public byte[] GetSignatureOctets() + { + return signature.GetOctets(); + } + + [Obsolete("Use Certs property instead")] public Asn1Sequence GetCerts() { return certs; diff --git a/crypto/src/asn1/ocsp/CertID.cs b/crypto/src/asn1/ocsp/CertID.cs
index 4b251095b..523f6b87c 100644 --- a/crypto/src/asn1/ocsp/CertID.cs +++ b/crypto/src/asn1/ocsp/CertID.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Ocsp { @@ -33,7 +34,7 @@ namespace Org.BouncyCastle.Asn1.Ocsp return new CertID((Asn1Sequence)obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public CertID( diff --git a/crypto/src/asn1/ocsp/CertStatus.cs b/crypto/src/asn1/ocsp/CertStatus.cs
index d5b1a94a2..b524364c9 100644 --- a/crypto/src/asn1/ocsp/CertStatus.cs +++ b/crypto/src/asn1/ocsp/CertStatus.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Ocsp { @@ -64,7 +64,7 @@ namespace Org.BouncyCastle.Asn1.Ocsp return new CertStatus((Asn1TaggedObject)obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public int TagNo diff --git a/crypto/src/asn1/ocsp/OCSPRequest.cs b/crypto/src/asn1/ocsp/OCSPRequest.cs
index 1e804d78e..2407678b4 100644 --- a/crypto/src/asn1/ocsp/OCSPRequest.cs +++ b/crypto/src/asn1/ocsp/OCSPRequest.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Ocsp { @@ -30,7 +30,7 @@ namespace Org.BouncyCastle.Asn1.Ocsp return new OcspRequest((Asn1Sequence)obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public OcspRequest( diff --git a/crypto/src/asn1/ocsp/OCSPResponse.cs b/crypto/src/asn1/ocsp/OCSPResponse.cs
index e9aad8100..9477b61c0 100644 --- a/crypto/src/asn1/ocsp/OCSPResponse.cs +++ b/crypto/src/asn1/ocsp/OCSPResponse.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Ocsp { @@ -30,7 +30,7 @@ namespace Org.BouncyCastle.Asn1.Ocsp return new OcspResponse((Asn1Sequence)obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public OcspResponse( diff --git a/crypto/src/asn1/ocsp/Request.cs b/crypto/src/asn1/ocsp/Request.cs
index 116c15e73..26e81ba70 100644 --- a/crypto/src/asn1/ocsp/Request.cs +++ b/crypto/src/asn1/ocsp/Request.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Ocsp { @@ -31,7 +32,7 @@ namespace Org.BouncyCastle.Asn1.Ocsp return new Request((Asn1Sequence)obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public Request( diff --git a/crypto/src/asn1/ocsp/ResponseBytes.cs b/crypto/src/asn1/ocsp/ResponseBytes.cs
index 2ce59faea..d3ea044bf 100644 --- a/crypto/src/asn1/ocsp/ResponseBytes.cs +++ b/crypto/src/asn1/ocsp/ResponseBytes.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Ocsp { @@ -30,7 +30,7 @@ namespace Org.BouncyCastle.Asn1.Ocsp return new ResponseBytes((Asn1Sequence)obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public ResponseBytes( diff --git a/crypto/src/asn1/ocsp/ResponseData.cs b/crypto/src/asn1/ocsp/ResponseData.cs
index 173829db8..70620cbc3 100644 --- a/crypto/src/asn1/ocsp/ResponseData.cs +++ b/crypto/src/asn1/ocsp/ResponseData.cs
@@ -1,7 +1,7 @@ using System; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Ocsp { @@ -37,7 +37,7 @@ namespace Org.BouncyCastle.Asn1.Ocsp return new ResponseData((Asn1Sequence)obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public ResponseData( diff --git a/crypto/src/asn1/ocsp/RevokedInfo.cs b/crypto/src/asn1/ocsp/RevokedInfo.cs
index 7d9d590e3..ee9e55429 100644 --- a/crypto/src/asn1/ocsp/RevokedInfo.cs +++ b/crypto/src/asn1/ocsp/RevokedInfo.cs
@@ -1,7 +1,7 @@ using System; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Ocsp { @@ -31,7 +31,7 @@ namespace Org.BouncyCastle.Asn1.Ocsp return new RevokedInfo((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public RevokedInfo( diff --git a/crypto/src/asn1/ocsp/ServiceLocator.cs b/crypto/src/asn1/ocsp/ServiceLocator.cs
index 56bc49ded..4ba252be3 100644 --- a/crypto/src/asn1/ocsp/ServiceLocator.cs +++ b/crypto/src/asn1/ocsp/ServiceLocator.cs
@@ -1,7 +1,7 @@ using System; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Ocsp { @@ -31,7 +31,7 @@ namespace Org.BouncyCastle.Asn1.Ocsp return new ServiceLocator((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public ServiceLocator( diff --git a/crypto/src/asn1/ocsp/Signature.cs b/crypto/src/asn1/ocsp/Signature.cs
index a07e7a709..d6b4ccfbf 100644 --- a/crypto/src/asn1/ocsp/Signature.cs +++ b/crypto/src/asn1/ocsp/Signature.cs
@@ -1,7 +1,7 @@ using System; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Ocsp { @@ -32,7 +32,7 @@ namespace Org.BouncyCastle.Asn1.Ocsp return new Signature((Asn1Sequence)obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public Signature( @@ -80,7 +80,12 @@ namespace Org.BouncyCastle.Asn1.Ocsp get { return signatureValue; } } - public Asn1Sequence Certs + public byte[] GetSignatureOctets() + { + return signatureValue.GetOctets(); + } + + public Asn1Sequence Certs { get { return certs; } } diff --git a/crypto/src/asn1/ocsp/SingleResponse.cs b/crypto/src/asn1/ocsp/SingleResponse.cs
index 93d4c21d6..544232abe 100644 --- a/crypto/src/asn1/ocsp/SingleResponse.cs +++ b/crypto/src/asn1/ocsp/SingleResponse.cs
@@ -1,8 +1,8 @@ -using Org.BouncyCastle.Asn1; -using Org.BouncyCastle.Asn1.X509; - using System; +using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Ocsp { public class SingleResponse @@ -77,7 +77,7 @@ namespace Org.BouncyCastle.Asn1.Ocsp return new SingleResponse((Asn1Sequence)obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public CertID CertId diff --git a/crypto/src/asn1/ocsp/TBSRequest.cs b/crypto/src/asn1/ocsp/TBSRequest.cs
index 6bf75eb96..1ad8649f8 100644 --- a/crypto/src/asn1/ocsp/TBSRequest.cs +++ b/crypto/src/asn1/ocsp/TBSRequest.cs
@@ -1,8 +1,8 @@ -using Org.BouncyCastle.Asn1; -using Org.BouncyCastle.Asn1.X509; - using System; +using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Ocsp { public class TbsRequest @@ -37,7 +37,7 @@ namespace Org.BouncyCastle.Asn1.Ocsp return new TbsRequest((Asn1Sequence)obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public TbsRequest( diff --git a/crypto/src/asn1/pkcs/Attribute.cs b/crypto/src/asn1/pkcs/Attribute.cs
index ceec115bd..185828596 100644 --- a/crypto/src/asn1/pkcs/Attribute.cs +++ b/crypto/src/asn1/pkcs/Attribute.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Pkcs { @@ -31,7 +31,7 @@ namespace Org.BouncyCastle.Asn1.Pkcs return new AttributePkcs(seq); } - throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } private AttributePkcs( diff --git a/crypto/src/asn1/pkcs/CertificationRequest.cs b/crypto/src/asn1/pkcs/CertificationRequest.cs
index 32b1612d2..35bdd56eb 100644 --- a/crypto/src/asn1/pkcs/CertificationRequest.cs +++ b/crypto/src/asn1/pkcs/CertificationRequest.cs
@@ -73,7 +73,12 @@ namespace Org.BouncyCastle.Asn1.Pkcs get { return sigBits; } } - public override Asn1Object ToAsn1Object() + public byte[] GetSignatureOctets() + { + return sigBits.GetOctets(); + } + + public override Asn1Object ToAsn1Object() { return new DerSequence(reqInfo, sigAlgId, sigBits); } diff --git a/crypto/src/asn1/pkcs/CertificationRequestInfo.cs b/crypto/src/asn1/pkcs/CertificationRequestInfo.cs
index 690d06878..d57753235 100644 --- a/crypto/src/asn1/pkcs/CertificationRequestInfo.cs +++ b/crypto/src/asn1/pkcs/CertificationRequestInfo.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Pkcs { @@ -43,7 +44,7 @@ namespace Org.BouncyCastle.Asn1.Pkcs return new CertificationRequestInfo((Asn1Sequence) obj); } - throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public CertificationRequestInfo( diff --git a/crypto/src/asn1/pkcs/EncryptedData.cs b/crypto/src/asn1/pkcs/EncryptedData.cs
index 912064ace..7e95eb586 100644 --- a/crypto/src/asn1/pkcs/EncryptedData.cs +++ b/crypto/src/asn1/pkcs/EncryptedData.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Pkcs { @@ -42,7 +43,7 @@ namespace Org.BouncyCastle.Asn1.Pkcs return new EncryptedData((Asn1Sequence) obj); } - throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } private EncryptedData( diff --git a/crypto/src/asn1/pkcs/EncryptedPrivateKeyInfo.cs b/crypto/src/asn1/pkcs/EncryptedPrivateKeyInfo.cs
index b97b8f5ea..987027009 100644 --- a/crypto/src/asn1/pkcs/EncryptedPrivateKeyInfo.cs +++ b/crypto/src/asn1/pkcs/EncryptedPrivateKeyInfo.cs
@@ -2,6 +2,7 @@ using System; using System.Collections; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Pkcs { @@ -42,7 +43,7 @@ namespace Org.BouncyCastle.Asn1.Pkcs return new EncryptedPrivateKeyInfo((Asn1Sequence) obj); } - throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public AlgorithmIdentifier EncryptionAlgorithm diff --git a/crypto/src/asn1/pkcs/EncryptionScheme.cs b/crypto/src/asn1/pkcs/EncryptionScheme.cs
index 5b64d6f67..7b90ece53 100644 --- a/crypto/src/asn1/pkcs/EncryptionScheme.cs +++ b/crypto/src/asn1/pkcs/EncryptionScheme.cs
@@ -1,7 +1,7 @@ using System; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Pkcs { @@ -33,7 +33,7 @@ namespace Org.BouncyCastle.Asn1.Pkcs return new EncryptionScheme((Asn1Sequence)obj); } - throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public Asn1Object Asn1Object @@ -43,7 +43,7 @@ namespace Org.BouncyCastle.Asn1.Pkcs public override Asn1Object ToAsn1Object() { - return new DerSequence(ObjectID, Parameters); + return new DerSequence(Algorithm, Parameters); } } } diff --git a/crypto/src/asn1/pkcs/IssuerAndSerialNumber.cs b/crypto/src/asn1/pkcs/IssuerAndSerialNumber.cs
index ff608f15b..da863cb62 100644 --- a/crypto/src/asn1/pkcs/IssuerAndSerialNumber.cs +++ b/crypto/src/asn1/pkcs/IssuerAndSerialNumber.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Math; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Pkcs { @@ -24,7 +25,7 @@ namespace Org.BouncyCastle.Asn1.Pkcs return new IssuerAndSerialNumber((Asn1Sequence) obj); } - throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } private IssuerAndSerialNumber( diff --git a/crypto/src/asn1/pkcs/MacData.cs b/crypto/src/asn1/pkcs/MacData.cs
index 780b24153..c4b7df176 100644 --- a/crypto/src/asn1/pkcs/MacData.cs +++ b/crypto/src/asn1/pkcs/MacData.cs
@@ -1,8 +1,8 @@ using System; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Math; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Pkcs { @@ -26,7 +26,7 @@ namespace Org.BouncyCastle.Asn1.Pkcs return new MacData((Asn1Sequence) obj); } - throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } private MacData( diff --git a/crypto/src/asn1/pkcs/PBEParameter.cs b/crypto/src/asn1/pkcs/PBEParameter.cs
index 80d5ec3e1..56cea5fb7 100644 --- a/crypto/src/asn1/pkcs/PBEParameter.cs +++ b/crypto/src/asn1/pkcs/PBEParameter.cs
@@ -1,8 +1,8 @@ using System; using System.Collections; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Math; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Pkcs { @@ -24,7 +24,7 @@ namespace Org.BouncyCastle.Asn1.Pkcs return new PbeParameter((Asn1Sequence) obj); } - throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } private PbeParameter(Asn1Sequence seq) diff --git a/crypto/src/asn1/pkcs/PBKDF2Params.cs b/crypto/src/asn1/pkcs/PBKDF2Params.cs
index 5d1e9854f..279f30de8 100644 --- a/crypto/src/asn1/pkcs/PBKDF2Params.cs +++ b/crypto/src/asn1/pkcs/PBKDF2Params.cs
@@ -1,6 +1,8 @@ using System; + using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Math; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Pkcs { @@ -22,7 +24,7 @@ namespace Org.BouncyCastle.Asn1.Pkcs if (obj is Asn1Sequence) return new Pbkdf2Params((Asn1Sequence)obj); - throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public Pbkdf2Params( diff --git a/crypto/src/asn1/pkcs/PKCS12PBEParams.cs b/crypto/src/asn1/pkcs/PKCS12PBEParams.cs
index 7521f93ea..b41c289d8 100644 --- a/crypto/src/asn1/pkcs/PKCS12PBEParams.cs +++ b/crypto/src/asn1/pkcs/PKCS12PBEParams.cs
@@ -1,7 +1,7 @@ using System; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Math; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Pkcs { @@ -42,7 +42,7 @@ namespace Org.BouncyCastle.Asn1.Pkcs return new Pkcs12PbeParams((Asn1Sequence) obj); } - throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public BigInteger Iterations diff --git a/crypto/src/asn1/pkcs/PrivateKeyInfo.cs b/crypto/src/asn1/pkcs/PrivateKeyInfo.cs
index 404277ba6..c5be7a315 100644 --- a/crypto/src/asn1/pkcs/PrivateKeyInfo.cs +++ b/crypto/src/asn1/pkcs/PrivateKeyInfo.cs
@@ -29,14 +29,14 @@ namespace Org.BouncyCastle.Asn1.Pkcs return new PrivateKeyInfo(Asn1Sequence.GetInstance(obj)); } - public PrivateKeyInfo(AlgorithmIdentifier algID, Asn1Object privateKey) + public PrivateKeyInfo(AlgorithmIdentifier algID, Asn1Encodable privateKey) : this(algID, privateKey, null) { } public PrivateKeyInfo( AlgorithmIdentifier algID, - Asn1Object privateKey, + Asn1Encodable privateKey, Asn1Set attributes) { this.algID = algID; diff --git a/crypto/src/asn1/pkcs/RC2CBCParameter.cs b/crypto/src/asn1/pkcs/RC2CBCParameter.cs
index f5355d012..880ca7443 100644 --- a/crypto/src/asn1/pkcs/RC2CBCParameter.cs +++ b/crypto/src/asn1/pkcs/RC2CBCParameter.cs
@@ -1,6 +1,5 @@ using System; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Math; using Org.BouncyCastle.Utilities; @@ -20,7 +19,7 @@ namespace Org.BouncyCastle.Asn1.Pkcs return new RC2CbcParameter((Asn1Sequence) obj); } - throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public RC2CbcParameter( diff --git a/crypto/src/asn1/pkcs/RSAESOAEPparams.cs b/crypto/src/asn1/pkcs/RSAESOAEPparams.cs
index 5ecb394fd..0cf22f860 100644 --- a/crypto/src/asn1/pkcs/RSAESOAEPparams.cs +++ b/crypto/src/asn1/pkcs/RSAESOAEPparams.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Asn1.Oiw; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Pkcs { @@ -28,7 +29,7 @@ namespace Org.BouncyCastle.Asn1.Pkcs return new RsaesOaepParameters((Asn1Sequence)obj); } - throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } /** diff --git a/crypto/src/asn1/pkcs/RSASSAPSSparams.cs b/crypto/src/asn1/pkcs/RSASSAPSSparams.cs
index 941620761..85849c362 100644 --- a/crypto/src/asn1/pkcs/RSASSAPSSparams.cs +++ b/crypto/src/asn1/pkcs/RSASSAPSSparams.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Asn1.Oiw; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Pkcs { @@ -31,7 +32,7 @@ namespace Org.BouncyCastle.Asn1.Pkcs return new RsassaPssParameters((Asn1Sequence)obj); } - throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } /** diff --git a/crypto/src/asn1/pkcs/SignerInfo.cs b/crypto/src/asn1/pkcs/SignerInfo.cs
index 1e4694547..a3dc48b5b 100644 --- a/crypto/src/asn1/pkcs/SignerInfo.cs +++ b/crypto/src/asn1/pkcs/SignerInfo.cs
@@ -1,8 +1,8 @@ using System; using System.Collections; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Pkcs { @@ -33,7 +33,7 @@ namespace Org.BouncyCastle.Asn1.Pkcs return new SignerInfo((Asn1Sequence) obj); } - throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public SignerInfo( diff --git a/crypto/src/asn1/sec/ECPrivateKeyStructure.cs b/crypto/src/asn1/sec/ECPrivateKeyStructure.cs
index 8d805fa30..32e020c0b 100644 --- a/crypto/src/asn1/sec/ECPrivateKeyStructure.cs +++ b/crypto/src/asn1/sec/ECPrivateKeyStructure.cs
@@ -23,6 +23,7 @@ namespace Org.BouncyCastle.Asn1.Sec return new ECPrivateKeyStructure(Asn1Sequence.GetInstance(obj)); } + [Obsolete("Use 'GetInstance' instead")] public ECPrivateKeyStructure( Asn1Sequence seq) { @@ -32,6 +33,7 @@ namespace Org.BouncyCastle.Asn1.Sec this.seq = seq; } + [Obsolete("Use constructor which takes 'orderBitLength' instead, to guarantee correct encoding")] public ECPrivateKeyStructure( BigInteger key) { @@ -44,12 +46,30 @@ namespace Org.BouncyCastle.Asn1.Sec } public ECPrivateKeyStructure( + int orderBitLength, + BigInteger key) + { + if (key == null) + throw new ArgumentNullException("key"); + if (orderBitLength < key.BitLength) + throw new ArgumentException("must be >= key bitlength", "orderBitLength"); + + byte[] bytes = BigIntegers.AsUnsignedByteArray((orderBitLength + 7) / 8, key); + + this.seq = new DerSequence( + new DerInteger(1), + new DerOctetString(bytes)); + } + + [Obsolete("Use constructor which takes 'orderBitLength' instead, to guarantee correct encoding")] + public ECPrivateKeyStructure( BigInteger key, Asn1Encodable parameters) : this(key, null, parameters) { } + [Obsolete("Use constructor which takes 'orderBitLength' instead, to guarantee correct encoding")] public ECPrivateKeyStructure( BigInteger key, DerBitString publicKey, @@ -75,6 +95,44 @@ namespace Org.BouncyCastle.Asn1.Sec this.seq = new DerSequence(v); } + public ECPrivateKeyStructure( + int orderBitLength, + BigInteger key, + Asn1Encodable parameters) + : this(orderBitLength, key, null, parameters) + { + } + + public ECPrivateKeyStructure( + int orderBitLength, + BigInteger key, + DerBitString publicKey, + Asn1Encodable parameters) + { + if (key == null) + throw new ArgumentNullException("key"); + if (orderBitLength < key.BitLength) + throw new ArgumentException("must be >= key bitlength", "orderBitLength"); + + byte[] bytes = BigIntegers.AsUnsignedByteArray((orderBitLength + 7) / 8, key); + + Asn1EncodableVector v = new Asn1EncodableVector( + new DerInteger(1), + new DerOctetString(bytes)); + + if (parameters != null) + { + v.Add(new DerTaggedObject(true, 0, parameters)); + } + + if (publicKey != null) + { + v.Add(new DerTaggedObject(true, 1, publicKey)); + } + + this.seq = new DerSequence(v); + } + public virtual BigInteger GetKey() { Asn1OctetString octs = (Asn1OctetString) seq[1]; diff --git a/crypto/src/asn1/sec/SECNamedCurves.cs b/crypto/src/asn1/sec/SECNamedCurves.cs
index ca71a4e66..b753ac5d1 100644 --- a/crypto/src/asn1/sec/SECNamedCurves.cs +++ b/crypto/src/asn1/sec/SECNamedCurves.cs
@@ -1088,7 +1088,7 @@ namespace Org.BouncyCastle.Asn1.Sec DerObjectIdentifier oid, X9ECParametersHolder holder) { - objIds.Add(Platform.ToLowerInvariant(name), oid); + objIds.Add(Platform.ToUpperInvariant(name), oid); names.Add(oid, name); curves.Add(oid, holder); } @@ -1160,7 +1160,7 @@ namespace Org.BouncyCastle.Asn1.Sec public static DerObjectIdentifier GetOid( string name) { - return (DerObjectIdentifier)objIds[Platform.ToLowerInvariant(name)]; + return (DerObjectIdentifier)objIds[Platform.ToUpperInvariant(name)]; } /** diff --git a/crypto/src/asn1/smime/SMIMECapabilities.cs b/crypto/src/asn1/smime/SMIMECapabilities.cs
index 6435caf68..5bf48f321 100644 --- a/crypto/src/asn1/smime/SMIMECapabilities.cs +++ b/crypto/src/asn1/smime/SMIMECapabilities.cs
@@ -62,7 +62,7 @@ namespace Org.BouncyCastle.Asn1.Smime (Asn1Sequence)(((AttributeX509) obj).AttrValues[0])); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public SmimeCapabilities( diff --git a/crypto/src/asn1/teletrust/TeleTrusTNamedCurves.cs b/crypto/src/asn1/teletrust/TeleTrusTNamedCurves.cs
index ba3eda620..9a82db319 100644 --- a/crypto/src/asn1/teletrust/TeleTrusTNamedCurves.cs +++ b/crypto/src/asn1/teletrust/TeleTrusTNamedCurves.cs
@@ -387,7 +387,7 @@ namespace Org.BouncyCastle.Asn1.TeleTrust DerObjectIdentifier oid, X9ECParametersHolder holder) { - objIds.Add(Platform.ToLowerInvariant(name), oid); + objIds.Add(Platform.ToUpperInvariant(name), oid); names.Add(oid, name); curves.Add(oid, holder); } @@ -439,7 +439,7 @@ namespace Org.BouncyCastle.Asn1.TeleTrust public static DerObjectIdentifier GetOid( string name) { - return (DerObjectIdentifier)objIds[Platform.ToLowerInvariant(name)]; + return (DerObjectIdentifier)objIds[Platform.ToUpperInvariant(name)]; } /** diff --git a/crypto/src/asn1/tsp/Accuracy.cs b/crypto/src/asn1/tsp/Accuracy.cs
index a193f52ff..9f2c7e8cc 100644 --- a/crypto/src/asn1/tsp/Accuracy.cs +++ b/crypto/src/asn1/tsp/Accuracy.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Tsp { public class Accuracy @@ -97,7 +99,7 @@ namespace Org.BouncyCastle.Asn1.Tsp } throw new ArgumentException( - "Unknown object in 'Accuracy' factory: " + o.GetType().FullName); + "Unknown object in 'Accuracy' factory: " + Platform.GetTypeName(o)); } public DerInteger Seconds diff --git a/crypto/src/asn1/tsp/MessageImprint.cs b/crypto/src/asn1/tsp/MessageImprint.cs
index 0933bae21..44ef7d177 100644 --- a/crypto/src/asn1/tsp/MessageImprint.cs +++ b/crypto/src/asn1/tsp/MessageImprint.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Tsp { @@ -28,7 +29,7 @@ namespace Org.BouncyCastle.Asn1.Tsp } throw new ArgumentException( - "Unknown object in 'MessageImprint' factory: " + o.GetType().FullName); + "Unknown object in 'MessageImprint' factory: " + Platform.GetTypeName(o)); } private MessageImprint( diff --git a/crypto/src/asn1/tsp/TSTInfo.cs b/crypto/src/asn1/tsp/TSTInfo.cs
index 61d5399c7..89f3e8b38 100644 --- a/crypto/src/asn1/tsp/TSTInfo.cs +++ b/crypto/src/asn1/tsp/TSTInfo.cs
@@ -3,6 +3,7 @@ using System.Collections; using System.IO; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Tsp { @@ -48,7 +49,7 @@ namespace Org.BouncyCastle.Asn1.Tsp } throw new ArgumentException( - "Unknown object in 'TstInfo' factory: " + o.GetType().FullName); + "Unknown object in 'TstInfo' factory: " + Platform.GetTypeName(o)); } private TstInfo( diff --git a/crypto/src/asn1/tsp/TimeStampReq.cs b/crypto/src/asn1/tsp/TimeStampReq.cs
index 55e973e76..5b05f3369 100644 --- a/crypto/src/asn1/tsp/TimeStampReq.cs +++ b/crypto/src/asn1/tsp/TimeStampReq.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Tsp { @@ -28,7 +29,7 @@ namespace Org.BouncyCastle.Asn1.Tsp } throw new ArgumentException( - "Unknown object in 'TimeStampReq' factory: " + o.GetType().FullName); + "Unknown object in 'TimeStampReq' factory: " + Platform.GetTypeName(o)); } private TimeStampReq( diff --git a/crypto/src/asn1/tsp/TimeStampResp.cs b/crypto/src/asn1/tsp/TimeStampResp.cs
index f26fb30bd..b91026064 100644 --- a/crypto/src/asn1/tsp/TimeStampResp.cs +++ b/crypto/src/asn1/tsp/TimeStampResp.cs
@@ -1,8 +1,8 @@ using System; -using System.Collections; using Org.BouncyCastle.Asn1.Cmp; using Org.BouncyCastle.Asn1.Cms; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.Tsp { @@ -26,7 +26,7 @@ namespace Org.BouncyCastle.Asn1.Tsp } throw new ArgumentException( - "Unknown object in 'TimeStampResp' factory: " + o.GetType().FullName); + "Unknown object in 'TimeStampResp' factory: " + Platform.GetTypeName(o)); } private TimeStampResp( diff --git a/crypto/src/asn1/util/Dump.cs b/crypto/src/asn1/util/Dump.cs
index 99ced5836..e313fe879 100644 --- a/crypto/src/asn1/util/Dump.cs +++ b/crypto/src/asn1/util/Dump.cs
@@ -2,6 +2,8 @@ using System; using System.IO; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Utilities { public sealed class Dump @@ -21,7 +23,7 @@ namespace Org.BouncyCastle.Asn1.Utilities Console.WriteLine(Asn1Dump.DumpAsString(obj)); } - bIn.Close(); + Platform.Dispose(bIn); } } } diff --git a/crypto/src/asn1/util/FilterStream.cs b/crypto/src/asn1/util/FilterStream.cs
index 980e7f176..0c38c5b6e 100644 --- a/crypto/src/asn1/util/FilterStream.cs +++ b/crypto/src/asn1/util/FilterStream.cs
@@ -1,6 +1,8 @@ using System; using System.IO; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.Utilities { [Obsolete("Use Org.BouncyCastle.Utilities.IO.FilterStream")] @@ -32,10 +34,22 @@ namespace Org.BouncyCastle.Asn1.Utilities get { return s.Position; } set { s.Position = value; } } +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + Platform.Dispose(s); + } + base.Dispose(disposing); + } +#else public override void Close() { - s.Close(); + Platform.Dispose(s); + base.Close(); } +#endif public override void Flush() { s.Flush(); diff --git a/crypto/src/asn1/x500/DirectoryString.cs b/crypto/src/asn1/x500/DirectoryString.cs
index 78ecc2663..d907c6456 100644 --- a/crypto/src/asn1/x500/DirectoryString.cs +++ b/crypto/src/asn1/x500/DirectoryString.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.X500 { public class DirectoryString @@ -27,7 +29,7 @@ namespace Org.BouncyCastle.Asn1.X500 } } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public static DirectoryString GetInstance( diff --git a/crypto/src/asn1/x509/AccessDescription.cs b/crypto/src/asn1/x509/AccessDescription.cs
index 09b5b5920..47374be8f 100644 --- a/crypto/src/asn1/x509/AccessDescription.cs +++ b/crypto/src/asn1/x509/AccessDescription.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.X509 { /** @@ -28,7 +30,7 @@ namespace Org.BouncyCastle.Asn1.X509 if (obj is Asn1Sequence) return new AccessDescription((Asn1Sequence) obj); - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } private AccessDescription( diff --git a/crypto/src/asn1/x509/AlgorithmIdentifier.cs b/crypto/src/asn1/x509/AlgorithmIdentifier.cs
index c6f4af5bf..00e7ad8bc 100644 --- a/crypto/src/asn1/x509/AlgorithmIdentifier.cs +++ b/crypto/src/asn1/x509/AlgorithmIdentifier.cs
@@ -5,9 +5,8 @@ namespace Org.BouncyCastle.Asn1.X509 public class AlgorithmIdentifier : Asn1Encodable { - private readonly DerObjectIdentifier objectID; + private readonly DerObjectIdentifier algorithm; private readonly Asn1Encodable parameters; - private readonly bool parametersDefined; public static AlgorithmIdentifier GetInstance( Asn1TaggedObject obj, @@ -19,39 +18,32 @@ namespace Org.BouncyCastle.Asn1.X509 public static AlgorithmIdentifier GetInstance( object obj) { - if (obj == null || obj is AlgorithmIdentifier) - return (AlgorithmIdentifier) obj; - - // TODO: delete - if (obj is DerObjectIdentifier) - return new AlgorithmIdentifier((DerObjectIdentifier) obj); - - // TODO: delete - if (obj is string) - return new AlgorithmIdentifier((string) obj); - + if (obj == null) + return null; + if (obj is AlgorithmIdentifier) + return (AlgorithmIdentifier)obj; return new AlgorithmIdentifier(Asn1Sequence.GetInstance(obj)); } public AlgorithmIdentifier( - DerObjectIdentifier objectID) + DerObjectIdentifier algorithm) { - this.objectID = objectID; + this.algorithm = algorithm; } + [Obsolete("Use version taking a DerObjectIdentifier")] public AlgorithmIdentifier( - string objectID) + string algorithm) { - this.objectID = new DerObjectIdentifier(objectID); + this.algorithm = new DerObjectIdentifier(algorithm); } public AlgorithmIdentifier( - DerObjectIdentifier objectID, + DerObjectIdentifier algorithm, Asn1Encodable parameters) { - this.objectID = objectID; + this.algorithm = algorithm; this.parameters = parameters; - this.parametersDefined = true; } internal AlgorithmIdentifier( @@ -60,13 +52,8 @@ namespace Org.BouncyCastle.Asn1.X509 if (seq.Count < 1 || seq.Count > 2) throw new ArgumentException("Bad sequence size: " + seq.Count); - this.objectID = DerObjectIdentifier.GetInstance(seq[0]); - this.parametersDefined = (seq.Count == 2); - - if (parametersDefined) - { - this.parameters = seq[1]; - } + this.algorithm = DerObjectIdentifier.GetInstance(seq[0]); + this.parameters = seq.Count < 2 ? null : seq[1]; } /// <summary> @@ -74,18 +61,19 @@ namespace Org.BouncyCastle.Asn1.X509 /// </summary> public virtual DerObjectIdentifier Algorithm { - get { return objectID; } + get { return algorithm; } } + [Obsolete("Use 'Algorithm' property instead")] public virtual DerObjectIdentifier ObjectID { - get { return objectID; } + get { return algorithm; } } /// <summary> /// Return the parameters structure in the Parameters entry of this identifier. /// </summary> - public Asn1Encodable Parameters + public virtual Asn1Encodable Parameters { get { return parameters; } } @@ -100,20 +88,8 @@ namespace Org.BouncyCastle.Asn1.X509 */ public override Asn1Object ToAsn1Object() { - Asn1EncodableVector v = new Asn1EncodableVector(objectID); - - if (parametersDefined) - { - if (parameters != null) - { - v.Add(parameters); - } - else - { - v.Add(DerNull.Instance); - } - } - + Asn1EncodableVector v = new Asn1EncodableVector(algorithm); + v.AddOptional(parameters); return new DerSequence(v); } } diff --git a/crypto/src/asn1/x509/AttCertIssuer.cs b/crypto/src/asn1/x509/AttCertIssuer.cs
index e9314fa92..407c4ae7a 100644 --- a/crypto/src/asn1/x509/AttCertIssuer.cs +++ b/crypto/src/asn1/x509/AttCertIssuer.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.X509 { @@ -34,7 +34,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new AttCertIssuer(GeneralNames.GetInstance(obj)); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public static AttCertIssuer GetInstance( diff --git a/crypto/src/asn1/x509/AttCertValidityPeriod.cs b/crypto/src/asn1/x509/AttCertValidityPeriod.cs
index 7f86cd0b8..d31e07402 100644 --- a/crypto/src/asn1/x509/AttCertValidityPeriod.cs +++ b/crypto/src/asn1/x509/AttCertValidityPeriod.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.X509 { @@ -23,7 +23,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new AttCertValidityPeriod((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public static AttCertValidityPeriod GetInstance( diff --git a/crypto/src/asn1/x509/Attribute.cs b/crypto/src/asn1/x509/Attribute.cs
index d26db93e9..da59b4285 100644 --- a/crypto/src/asn1/x509/Attribute.cs +++ b/crypto/src/asn1/x509/Attribute.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.X509 { @@ -29,7 +29,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new AttributeX509((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } private AttributeX509( diff --git a/crypto/src/asn1/x509/AttributeCertificate.cs b/crypto/src/asn1/x509/AttributeCertificate.cs
index 5f85910da..41893b6b4 100644 --- a/crypto/src/asn1/x509/AttributeCertificate.cs +++ b/crypto/src/asn1/x509/AttributeCertificate.cs
@@ -63,7 +63,12 @@ namespace Org.BouncyCastle.Asn1.X509 get { return signatureValue; } } - /** + public byte[] GetSignatureOctets() + { + return signatureValue.GetOctets(); + } + + /** * Produce an object suitable for an Asn1OutputStream. * <pre> * AttributeCertificate ::= Sequence { diff --git a/crypto/src/asn1/x509/AttributeCertificateInfo.cs b/crypto/src/asn1/x509/AttributeCertificateInfo.cs
index dcef3d472..526f8e69b 100644 --- a/crypto/src/asn1/x509/AttributeCertificateInfo.cs +++ b/crypto/src/asn1/x509/AttributeCertificateInfo.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.X509 { @@ -37,7 +37,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new AttributeCertificateInfo((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } private AttributeCertificateInfo( diff --git a/crypto/src/asn1/x509/AuthorityKeyIdentifier.cs b/crypto/src/asn1/x509/AuthorityKeyIdentifier.cs
index 12ccacfc7..d5a9048cc 100644 --- a/crypto/src/asn1/x509/AuthorityKeyIdentifier.cs +++ b/crypto/src/asn1/x509/AuthorityKeyIdentifier.cs
@@ -1,10 +1,10 @@ using System; using System.Collections; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Digests; using Org.BouncyCastle.Math; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.X509 { @@ -54,7 +54,7 @@ namespace Org.BouncyCastle.Asn1.X509 return GetInstance(X509Extension.ConvertValueToObject((X509Extension) obj)); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } protected internal AuthorityKeyIdentifier( diff --git a/crypto/src/asn1/x509/BasicConstraints.cs b/crypto/src/asn1/x509/BasicConstraints.cs
index 522cb61cc..098801f22 100644 --- a/crypto/src/asn1/x509/BasicConstraints.cs +++ b/crypto/src/asn1/x509/BasicConstraints.cs
@@ -1,7 +1,7 @@ using System; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Math; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.X509 { @@ -36,7 +36,7 @@ namespace Org.BouncyCastle.Asn1.X509 return GetInstance(X509Extension.ConvertValueToObject((X509Extension) obj)); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } private BasicConstraints( diff --git a/crypto/src/asn1/x509/CRLDistPoint.cs b/crypto/src/asn1/x509/CRLDistPoint.cs
index 2b5c19798..56ba79ca5 100644 --- a/crypto/src/asn1/x509/CRLDistPoint.cs +++ b/crypto/src/asn1/x509/CRLDistPoint.cs
@@ -30,7 +30,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new CrlDistPoint((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } private CrlDistPoint( diff --git a/crypto/src/asn1/x509/CertificateList.cs b/crypto/src/asn1/x509/CertificateList.cs
index 0412e0816..567cf132a 100644 --- a/crypto/src/asn1/x509/CertificateList.cs +++ b/crypto/src/asn1/x509/CertificateList.cs
@@ -80,7 +80,12 @@ namespace Org.BouncyCastle.Asn1.X509 get { return sig; } } - public int Version + public byte[] GetSignatureOctets() + { + return sig.GetOctets(); + } + + public int Version { get { return tbsCertList.Version; } } diff --git a/crypto/src/asn1/x509/CertificatePair.cs b/crypto/src/asn1/x509/CertificatePair.cs
index 8baa64719..da9236010 100644 --- a/crypto/src/asn1/x509/CertificatePair.cs +++ b/crypto/src/asn1/x509/CertificatePair.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.X509 { /** @@ -53,7 +55,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new CertificatePair((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } /** diff --git a/crypto/src/asn1/x509/DSAParameter.cs b/crypto/src/asn1/x509/DSAParameter.cs
index b2b325f4d..2eb65024b 100644 --- a/crypto/src/asn1/x509/DSAParameter.cs +++ b/crypto/src/asn1/x509/DSAParameter.cs
@@ -2,6 +2,7 @@ using System; using System.Collections; using Org.BouncyCastle.Math; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.X509 { @@ -30,7 +31,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new DsaParameter((Asn1Sequence) obj); } - throw new ArgumentException("Invalid DsaParameter: " + obj.GetType().Name); + throw new ArgumentException("Invalid DsaParameter: " + Platform.GetTypeName(obj)); } public DsaParameter( diff --git a/crypto/src/asn1/x509/DigestInfo.cs b/crypto/src/asn1/x509/DigestInfo.cs
index 1dec227fa..3ac535e2e 100644 --- a/crypto/src/asn1/x509/DigestInfo.cs +++ b/crypto/src/asn1/x509/DigestInfo.cs
@@ -1,6 +1,8 @@ using System; using System.Collections; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.X509 { /** @@ -37,7 +39,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new DigestInfo((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public DigestInfo( diff --git a/crypto/src/asn1/x509/DisplayText.cs b/crypto/src/asn1/x509/DisplayText.cs
index 699f39031..39b3c98d7 100644 --- a/crypto/src/asn1/x509/DisplayText.cs +++ b/crypto/src/asn1/x509/DisplayText.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.X509 { /** @@ -151,7 +153,7 @@ namespace Org.BouncyCastle.Asn1.X509 return (DisplayText) obj; } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public override Asn1Object ToAsn1Object() diff --git a/crypto/src/asn1/x509/DistributionPoint.cs b/crypto/src/asn1/x509/DistributionPoint.cs
index ad1d3989e..40814c7a8 100644 --- a/crypto/src/asn1/x509/DistributionPoint.cs +++ b/crypto/src/asn1/x509/DistributionPoint.cs
@@ -42,7 +42,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new DistributionPoint((Asn1Sequence) obj); } - throw new ArgumentException("Invalid DistributionPoint: " + obj.GetType().Name); + throw new ArgumentException("Invalid DistributionPoint: " + Platform.GetTypeName(obj)); } private DistributionPoint( diff --git a/crypto/src/asn1/x509/DistributionPointName.cs b/crypto/src/asn1/x509/DistributionPointName.cs
index 1a9d24241..43fdaf533 100644 --- a/crypto/src/asn1/x509/DistributionPointName.cs +++ b/crypto/src/asn1/x509/DistributionPointName.cs
@@ -43,7 +43,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new DistributionPointName((Asn1TaggedObject) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public DistributionPointName( diff --git a/crypto/src/asn1/x509/ExtendedKeyUsage.cs b/crypto/src/asn1/x509/ExtendedKeyUsage.cs
index 9b1400db9..8f7e6a353 100644 --- a/crypto/src/asn1/x509/ExtendedKeyUsage.cs +++ b/crypto/src/asn1/x509/ExtendedKeyUsage.cs
@@ -42,7 +42,7 @@ namespace Org.BouncyCastle.Asn1.X509 return GetInstance(X509Extension.ConvertValueToObject((X509Extension) obj)); } - throw new ArgumentException("Invalid ExtendedKeyUsage: " + obj.GetType().Name); + throw new ArgumentException("Invalid ExtendedKeyUsage: " + Platform.GetTypeName(obj)); } private ExtendedKeyUsage( diff --git a/crypto/src/asn1/x509/GeneralName.cs b/crypto/src/asn1/x509/GeneralName.cs
index 710ddc922..b8794ea8f 100644 --- a/crypto/src/asn1/x509/GeneralName.cs +++ b/crypto/src/asn1/x509/GeneralName.cs
@@ -4,6 +4,7 @@ using System.Globalization; using System.IO; using System.Text; +using Org.BouncyCastle.Utilities; using NetUtils = Org.BouncyCastle.Utilities.Net; namespace Org.BouncyCastle.Asn1.X509 @@ -202,7 +203,7 @@ namespace Org.BouncyCastle.Asn1.X509 } } - throw new ArgumentException("unknown object in GetInstance: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } public static GeneralName GetInstance( @@ -356,11 +357,11 @@ namespace Org.BouncyCastle.Asn1.X509 private int[] parseIPv6(string ip) { - if (ip.StartsWith("::")) + if (Platform.StartsWith(ip, "::")) { ip = ip.Substring(1); } - else if (ip.EndsWith("::")) + else if (Platform.EndsWith(ip, "::")) { ip = ip.Substring(0, ip.Length - 1); } diff --git a/crypto/src/asn1/x509/GeneralNames.cs b/crypto/src/asn1/x509/GeneralNames.cs
index 6c5c8e690..fcd2ecb24 100644 --- a/crypto/src/asn1/x509/GeneralNames.cs +++ b/crypto/src/asn1/x509/GeneralNames.cs
@@ -23,7 +23,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new GeneralNames((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public static GeneralNames GetInstance( diff --git a/crypto/src/asn1/x509/Holder.cs b/crypto/src/asn1/x509/Holder.cs
index d04f1cb60..6e5315b80 100644 --- a/crypto/src/asn1/x509/Holder.cs +++ b/crypto/src/asn1/x509/Holder.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.X509 { /** @@ -58,7 +60,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new Holder((Asn1TaggedObject) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } /** diff --git a/crypto/src/asn1/x509/IssuerSerial.cs b/crypto/src/asn1/x509/IssuerSerial.cs
index 6a24e7333..1e47e022b 100644 --- a/crypto/src/asn1/x509/IssuerSerial.cs +++ b/crypto/src/asn1/x509/IssuerSerial.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.X509 { public class IssuerSerial @@ -22,7 +24,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new IssuerSerial((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public static IssuerSerial GetInstance( diff --git a/crypto/src/asn1/x509/IssuingDistributionPoint.cs b/crypto/src/asn1/x509/IssuingDistributionPoint.cs
index 3af0d565f..8e9362b90 100644 --- a/crypto/src/asn1/x509/IssuingDistributionPoint.cs +++ b/crypto/src/asn1/x509/IssuingDistributionPoint.cs
@@ -48,7 +48,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new IssuingDistributionPoint((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } /** diff --git a/crypto/src/asn1/x509/KeyUsage.cs b/crypto/src/asn1/x509/KeyUsage.cs
index fef04e8b9..aeaffb708 100644 --- a/crypto/src/asn1/x509/KeyUsage.cs +++ b/crypto/src/asn1/x509/KeyUsage.cs
@@ -53,9 +53,8 @@ namespace Org.BouncyCastle.Asn1.X509 * allowed uses for the key. * e.g. (KeyUsage.keyEncipherment | KeyUsage.dataEncipherment) */ - public KeyUsage( - int usage) - : base(GetBytes(usage), GetPadBits(usage)) + public KeyUsage(int usage) + : base(usage) { } diff --git a/crypto/src/asn1/x509/NameConstraints.cs b/crypto/src/asn1/x509/NameConstraints.cs
index c178f5b45..0c5fea8b3 100644 --- a/crypto/src/asn1/x509/NameConstraints.cs +++ b/crypto/src/asn1/x509/NameConstraints.cs
@@ -1,6 +1,8 @@ using System; using System.Collections; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.X509 { public class NameConstraints @@ -21,7 +23,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new NameConstraints((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public NameConstraints( diff --git a/crypto/src/asn1/x509/ObjectDigestInfo.cs b/crypto/src/asn1/x509/ObjectDigestInfo.cs
index 6d5b9c692..9cd9a5f4c 100644 --- a/crypto/src/asn1/x509/ObjectDigestInfo.cs +++ b/crypto/src/asn1/x509/ObjectDigestInfo.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.X509 { /** @@ -58,7 +60,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new ObjectDigestInfo((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public static ObjectDigestInfo GetInstance( diff --git a/crypto/src/asn1/x509/PrivateKeyUsagePeriod.cs b/crypto/src/asn1/x509/PrivateKeyUsagePeriod.cs
index ad2961eb0..a3d7a3608 100644 --- a/crypto/src/asn1/x509/PrivateKeyUsagePeriod.cs +++ b/crypto/src/asn1/x509/PrivateKeyUsagePeriod.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.X509 { /// <remarks> @@ -31,7 +33,7 @@ namespace Org.BouncyCastle.Asn1.X509 return GetInstance(X509Extension.ConvertValueToObject((X509Extension) obj)); } - throw new ArgumentException("unknown object in GetInstance: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } private DerGeneralizedTime _notBefore, _notAfter; diff --git a/crypto/src/asn1/x509/RSAPublicKeyStructure.cs b/crypto/src/asn1/x509/RSAPublicKeyStructure.cs
index bdcba783e..20fdd96ac 100644 --- a/crypto/src/asn1/x509/RSAPublicKeyStructure.cs +++ b/crypto/src/asn1/x509/RSAPublicKeyStructure.cs
@@ -1,9 +1,10 @@ -using Org.BouncyCastle.Asn1; -using Org.BouncyCastle.Math; - using System; using System.Collections; +using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Math; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.X509 { public class RsaPublicKeyStructure @@ -32,7 +33,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new RsaPublicKeyStructure((Asn1Sequence) obj); } - throw new ArgumentException("Invalid RsaPublicKeyStructure: " + obj.GetType().Name); + throw new ArgumentException("Invalid RsaPublicKeyStructure: " + Platform.GetTypeName(obj)); } public RsaPublicKeyStructure( diff --git a/crypto/src/asn1/x509/ReasonFlags.cs b/crypto/src/asn1/x509/ReasonFlags.cs
index f204c36aa..ad45e84ae 100644 --- a/crypto/src/asn1/x509/ReasonFlags.cs +++ b/crypto/src/asn1/x509/ReasonFlags.cs
@@ -31,13 +31,12 @@ namespace Org.BouncyCastle.Asn1.X509 * @param reasons - the bitwise OR of the Key Reason flags giving the * allowed uses for the key. */ - public ReasonFlags( - int reasons) - : base(GetBytes(reasons), GetPadBits(reasons)) + public ReasonFlags(int reasons) + : base(reasons) { } - public ReasonFlags( + public ReasonFlags( DerBitString reasons) : base(reasons.GetBytes(), reasons.PadBits) { diff --git a/crypto/src/asn1/x509/SubjectDirectoryAttributes.cs b/crypto/src/asn1/x509/SubjectDirectoryAttributes.cs
index c76d94d78..77923e0d2 100644 --- a/crypto/src/asn1/x509/SubjectDirectoryAttributes.cs +++ b/crypto/src/asn1/x509/SubjectDirectoryAttributes.cs
@@ -43,7 +43,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new SubjectDirectoryAttributes((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } /** diff --git a/crypto/src/asn1/x509/SubjectKeyIdentifier.cs b/crypto/src/asn1/x509/SubjectKeyIdentifier.cs
index e640760f3..f2e6cc006 100644 --- a/crypto/src/asn1/x509/SubjectKeyIdentifier.cs +++ b/crypto/src/asn1/x509/SubjectKeyIdentifier.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Digests; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.X509 { @@ -46,7 +47,7 @@ namespace Org.BouncyCastle.Asn1.X509 return GetInstance(X509Extension.ConvertValueToObject((X509Extension) obj)); } - throw new ArgumentException("Invalid SubjectKeyIdentifier: " + obj.GetType().Name); + throw new ArgumentException("Invalid SubjectKeyIdentifier: " + Platform.GetTypeName(obj)); } public SubjectKeyIdentifier( diff --git a/crypto/src/asn1/x509/SubjectPublicKeyInfo.cs b/crypto/src/asn1/x509/SubjectPublicKeyInfo.cs
index 8ce4b2762..477329b7e 100644 --- a/crypto/src/asn1/x509/SubjectPublicKeyInfo.cs +++ b/crypto/src/asn1/x509/SubjectPublicKeyInfo.cs
@@ -75,7 +75,7 @@ namespace Org.BouncyCastle.Asn1.X509 */ public Asn1Object GetPublicKey() { - return Asn1Object.FromByteArray(keyData.GetBytes()); + return Asn1Object.FromByteArray(keyData.GetOctets()); } /** diff --git a/crypto/src/asn1/x509/TBSCertList.cs b/crypto/src/asn1/x509/TBSCertList.cs
index b5934a230..5767a7f21 100644 --- a/crypto/src/asn1/x509/TBSCertList.cs +++ b/crypto/src/asn1/x509/TBSCertList.cs
@@ -1,6 +1,7 @@ using System; using System.Collections; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; namespace Org.BouncyCastle.Asn1.X509 @@ -155,7 +156,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new TbsCertificateList((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } internal TbsCertificateList( diff --git a/crypto/src/asn1/x509/Target.cs b/crypto/src/asn1/x509/Target.cs
index 309b28c95..7c4f9db7e 100644 --- a/crypto/src/asn1/x509/Target.cs +++ b/crypto/src/asn1/x509/Target.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.X509 { /** @@ -53,7 +55,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new Target((Asn1TaggedObject) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } /** diff --git a/crypto/src/asn1/x509/TargetInformation.cs b/crypto/src/asn1/x509/TargetInformation.cs
index 75b18c0c9..2bf218977 100644 --- a/crypto/src/asn1/x509/TargetInformation.cs +++ b/crypto/src/asn1/x509/TargetInformation.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.X509 { /** @@ -38,7 +40,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new TargetInformation((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } /** diff --git a/crypto/src/asn1/x509/Targets.cs b/crypto/src/asn1/x509/Targets.cs
index 3e436d8d8..0387e1f6b 100644 --- a/crypto/src/asn1/x509/Targets.cs +++ b/crypto/src/asn1/x509/Targets.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.X509 { /** @@ -52,7 +54,7 @@ namespace Org.BouncyCastle.Asn1.X509 return new Targets((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } /** diff --git a/crypto/src/asn1/x509/Time.cs b/crypto/src/asn1/x509/Time.cs
index 8350339bb..fa3936d63 100644 --- a/crypto/src/asn1/x509/Time.cs +++ b/crypto/src/asn1/x509/Time.cs
@@ -1,6 +1,8 @@ using System; using System.Globalization; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.X509 { public class Time @@ -34,7 +36,11 @@ namespace Org.BouncyCastle.Asn1.X509 public Time( DateTime date) { +#if PORTABLE + string d = date.ToUniversalTime().ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture) + "Z"; +#else string d = date.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture) + "Z"; +#endif int year = int.Parse(d.Substring(0, 4)); @@ -58,7 +64,7 @@ namespace Org.BouncyCastle.Asn1.X509 if (obj is DerGeneralizedTime) return new Time((DerGeneralizedTime)obj); - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } public string GetTime() diff --git a/crypto/src/asn1/x509/X509CertificateStructure.cs b/crypto/src/asn1/x509/X509CertificateStructure.cs
index c8558ae61..6e7c85de6 100644 --- a/crypto/src/asn1/x509/X509CertificateStructure.cs +++ b/crypto/src/asn1/x509/X509CertificateStructure.cs
@@ -119,6 +119,11 @@ namespace Org.BouncyCastle.Asn1.X509 get { return sig; } } + public byte[] GetSignatureOctets() + { + return sig.GetOctets(); + } + public override Asn1Object ToAsn1Object() { return new DerSequence(tbsCert, sigAlgID, sig); diff --git a/crypto/src/asn1/x509/X509Extensions.cs b/crypto/src/asn1/x509/X509Extensions.cs
index 1896450f5..2ef73f629 100644 --- a/crypto/src/asn1/x509/X509Extensions.cs +++ b/crypto/src/asn1/x509/X509Extensions.cs
@@ -192,7 +192,7 @@ namespace Org.BouncyCastle.Asn1.X509 return GetInstance(((Asn1TaggedObject) obj).GetObject()); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } /** diff --git a/crypto/src/asn1/x509/X509Name.cs b/crypto/src/asn1/x509/X509Name.cs
index fb404a3ec..01a7ec04a 100644 --- a/crypto/src/asn1/x509/X509Name.cs +++ b/crypto/src/asn1/x509/X509Name.cs
@@ -399,7 +399,7 @@ namespace Org.BouncyCastle.Asn1.X509 if (derValue is IAsn1String && !(derValue is DerUniversalString)) { string v = ((IAsn1String)derValue).GetString(); - if (v.StartsWith("#")) + if (Platform.StartsWith(v, "#")) { v = "\\" + v; } @@ -499,12 +499,6 @@ namespace Org.BouncyCastle.Asn1.X509 } } -// private static bool IsEncoded( -// string s) -// { -// return s.StartsWith("#"); -// } - /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes. @@ -581,7 +575,7 @@ namespace Org.BouncyCastle.Asn1.X509 string name, IDictionary lookUp) { - if (Platform.ToUpperInvariant(name).StartsWith("OID.")) + if (Platform.StartsWith(Platform.ToUpperInvariant(name), "OID.")) { return new DerObjectIdentifier(name.Substring(4)); } @@ -724,7 +718,7 @@ namespace Org.BouncyCastle.Asn1.X509 { string val = (string)values[i]; - if (val.StartsWith("\\#")) + if (Platform.StartsWith(val, "\\#")) { val = val.Substring(1); } @@ -911,7 +905,7 @@ namespace Org.BouncyCastle.Asn1.X509 { string v = Platform.ToLowerInvariant(s).Trim(); - if (v.StartsWith("#")) + if (Platform.StartsWith(v, "#")) { Asn1Object obj = decodeObject(v); @@ -987,7 +981,7 @@ namespace Org.BouncyCastle.Asn1.X509 int end = buf.Length; - if (val.StartsWith("\\#")) + if (Platform.StartsWith(val, "\\#")) { index += 2; } diff --git a/crypto/src/asn1/x509/qualified/BiometricData.cs b/crypto/src/asn1/x509/qualified/BiometricData.cs
index 61d7c99cb..bb70c342c 100644 --- a/crypto/src/asn1/x509/qualified/BiometricData.cs +++ b/crypto/src/asn1/x509/qualified/BiometricData.cs
@@ -1,8 +1,6 @@ using System; -using System.Collections; -using Org.BouncyCastle.Asn1; -using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.X509.Qualified { @@ -37,7 +35,7 @@ namespace Org.BouncyCastle.Asn1.X509.Qualified return new BiometricData(Asn1Sequence.GetInstance(obj)); } - throw new ArgumentException("unknown object in GetInstance: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } private BiometricData( diff --git a/crypto/src/asn1/x509/qualified/Iso4217CurrencyCode.cs b/crypto/src/asn1/x509/qualified/Iso4217CurrencyCode.cs
index 3300562c8..9ec88f5ed 100644 --- a/crypto/src/asn1/x509/qualified/Iso4217CurrencyCode.cs +++ b/crypto/src/asn1/x509/qualified/Iso4217CurrencyCode.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.X509.Qualified { @@ -45,7 +45,7 @@ namespace Org.BouncyCastle.Asn1.X509.Qualified return new Iso4217CurrencyCode(alphabetic.GetString()); } - throw new ArgumentException("unknown object in GetInstance: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } public Iso4217CurrencyCode( @@ -53,7 +53,7 @@ namespace Org.BouncyCastle.Asn1.X509.Qualified { if (numeric > NumericMaxSize || numeric < NumericMinSize) { - throw new ArgumentException("wrong size in numeric code : not in (" +NumericMinSize +".."+ NumericMaxSize +")"); + throw new ArgumentException("wrong size in numeric code : not in (" + NumericMinSize + ".." + NumericMaxSize + ")"); } obj = new DerInteger(numeric); diff --git a/crypto/src/asn1/x509/qualified/MonetaryValue.cs b/crypto/src/asn1/x509/qualified/MonetaryValue.cs
index 45e113671..d703de943 100644 --- a/crypto/src/asn1/x509/qualified/MonetaryValue.cs +++ b/crypto/src/asn1/x509/qualified/MonetaryValue.cs
@@ -1,8 +1,8 @@ using System; using System.Collections; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Math; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.X509.Qualified { @@ -36,7 +36,7 @@ namespace Org.BouncyCastle.Asn1.X509.Qualified return new MonetaryValue(Asn1Sequence.GetInstance(obj)); } - throw new ArgumentException("unknown object in GetInstance: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } private MonetaryValue( diff --git a/crypto/src/asn1/x509/qualified/QCStatement.cs b/crypto/src/asn1/x509/qualified/QCStatement.cs
index 317f03447..a8e214cbf 100644 --- a/crypto/src/asn1/x509/qualified/QCStatement.cs +++ b/crypto/src/asn1/x509/qualified/QCStatement.cs
@@ -1,7 +1,6 @@ using System; -using System.Collections; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.X509.Qualified { @@ -32,7 +31,7 @@ namespace Org.BouncyCastle.Asn1.X509.Qualified return new QCStatement(Asn1Sequence.GetInstance(obj)); } - throw new ArgumentException("unknown object in GetInstance: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } private QCStatement( diff --git a/crypto/src/asn1/x509/qualified/SemanticsInformation.cs b/crypto/src/asn1/x509/qualified/SemanticsInformation.cs
index 72e7cd0e1..5fe5f936c 100644 --- a/crypto/src/asn1/x509/qualified/SemanticsInformation.cs +++ b/crypto/src/asn1/x509/qualified/SemanticsInformation.cs
@@ -1,8 +1,8 @@ using System; using System.Collections; -using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.X509.Qualified { @@ -39,7 +39,7 @@ namespace Org.BouncyCastle.Asn1.X509.Qualified return new SemanticsInformation(Asn1Sequence.GetInstance(obj)); } - throw new ArgumentException("unknown object in GetInstance: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } public SemanticsInformation( diff --git a/crypto/src/asn1/x509/qualified/TypeOfBiometricData.cs b/crypto/src/asn1/x509/qualified/TypeOfBiometricData.cs
index a77e54acb..17b7841c3 100644 --- a/crypto/src/asn1/x509/qualified/TypeOfBiometricData.cs +++ b/crypto/src/asn1/x509/qualified/TypeOfBiometricData.cs
@@ -1,6 +1,6 @@ using System; -using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.X509.Qualified { @@ -46,7 +46,7 @@ namespace Org.BouncyCastle.Asn1.X509.Qualified return new TypeOfBiometricData(BiometricDataOid); } - throw new ArgumentException("unknown object in GetInstance: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj"); } public TypeOfBiometricData( diff --git a/crypto/src/asn1/x509/sigi/NameOrPseudonym.cs b/crypto/src/asn1/x509/sigi/NameOrPseudonym.cs
index 222895cf1..2402e3832 100644 --- a/crypto/src/asn1/x509/sigi/NameOrPseudonym.cs +++ b/crypto/src/asn1/x509/sigi/NameOrPseudonym.cs
@@ -2,6 +2,7 @@ using System; using System.Collections; using Org.BouncyCastle.Asn1.X500; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.X509.SigI { @@ -46,7 +47,7 @@ namespace Org.BouncyCastle.Asn1.X509.SigI return new NameOrPseudonym((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } /** @@ -95,7 +96,7 @@ namespace Org.BouncyCastle.Asn1.X509.SigI throw new ArgumentException("Bad sequence size: " + seq.Count); if (!(seq[0] is IAsn1String)) - throw new ArgumentException("Bad object encountered: " + seq[0].GetType().Name); + throw new ArgumentException("Bad object encountered: " + Platform.GetTypeName(seq[0])); surname = DirectoryString.GetInstance(seq[0]); givenName = Asn1Sequence.GetInstance(seq[1]); diff --git a/crypto/src/asn1/x509/sigi/PersonalData.cs b/crypto/src/asn1/x509/sigi/PersonalData.cs
index 6acdc7308..dba345c42 100644 --- a/crypto/src/asn1/x509/sigi/PersonalData.cs +++ b/crypto/src/asn1/x509/sigi/PersonalData.cs
@@ -3,6 +3,7 @@ using System.Collections; using Org.BouncyCastle.Asn1.X500; using Org.BouncyCastle.Math; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1.X509.SigI { @@ -47,7 +48,7 @@ namespace Org.BouncyCastle.Asn1.X509.SigI return new PersonalData((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); + throw new ArgumentException("unknown object in factory: " + Platform.GetTypeName(obj), "obj"); } /** diff --git a/crypto/src/asn1/x9/DHDomainParameters.cs b/crypto/src/asn1/x9/DHDomainParameters.cs
index 8de869694..b8c1ac030 100644 --- a/crypto/src/asn1/x9/DHDomainParameters.cs +++ b/crypto/src/asn1/x9/DHDomainParameters.cs
@@ -1,6 +1,8 @@ using System; using System.Collections; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.X9 { public class DHDomainParameters @@ -22,7 +24,7 @@ namespace Org.BouncyCastle.Asn1.X9 if (obj is Asn1Sequence) return new DHDomainParameters((Asn1Sequence)obj); - throw new ArgumentException("Invalid DHDomainParameters: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Invalid DHDomainParameters: " + Platform.GetTypeName(obj), "obj"); } public DHDomainParameters(DerInteger p, DerInteger g, DerInteger q, DerInteger j, diff --git a/crypto/src/asn1/x9/DHPublicKey.cs b/crypto/src/asn1/x9/DHPublicKey.cs
index 1a20a8a16..74a14a2ee 100644 --- a/crypto/src/asn1/x9/DHPublicKey.cs +++ b/crypto/src/asn1/x9/DHPublicKey.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.X9 { public class DHPublicKey @@ -20,7 +22,7 @@ namespace Org.BouncyCastle.Asn1.X9 if (obj is DerInteger) return new DHPublicKey((DerInteger)obj); - throw new ArgumentException("Invalid DHPublicKey: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Invalid DHPublicKey: " + Platform.GetTypeName(obj), "obj"); } public DHPublicKey(DerInteger y) diff --git a/crypto/src/asn1/x9/DHValidationParms.cs b/crypto/src/asn1/x9/DHValidationParms.cs
index a37964cfb..c63c50205 100644 --- a/crypto/src/asn1/x9/DHValidationParms.cs +++ b/crypto/src/asn1/x9/DHValidationParms.cs
@@ -1,5 +1,7 @@ using System; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Asn1.X9 { public class DHValidationParms @@ -21,7 +23,7 @@ namespace Org.BouncyCastle.Asn1.X9 if (obj is Asn1Sequence) return new DHValidationParms((Asn1Sequence)obj); - throw new ArgumentException("Invalid DHValidationParms: " + obj.GetType().FullName, "obj"); + throw new ArgumentException("Invalid DHValidationParms: " + Platform.GetTypeName(obj), "obj"); } public DHValidationParms(DerBitString seed, DerInteger pgenCounter) diff --git a/crypto/src/asn1/x9/X962NamedCurves.cs b/crypto/src/asn1/x9/X962NamedCurves.cs
index 6fa4e7c4b..14f7f818a 100644 --- a/crypto/src/asn1/x9/X962NamedCurves.cs +++ b/crypto/src/asn1/x9/X962NamedCurves.cs
@@ -666,7 +666,7 @@ namespace Org.BouncyCastle.Asn1.X9 DerObjectIdentifier oid, X9ECParametersHolder holder) { - objIds.Add(Platform.ToLowerInvariant(name), oid); + objIds.Add(Platform.ToUpperInvariant(name), oid); names.Add(oid, name); curves.Add(oid, holder); } @@ -727,7 +727,7 @@ namespace Org.BouncyCastle.Asn1.X9 public static DerObjectIdentifier GetOid( string name) { - return (DerObjectIdentifier)objIds[Platform.ToLowerInvariant(name)]; + return (DerObjectIdentifier)objIds[Platform.ToUpperInvariant(name)]; } /** diff --git a/crypto/src/asn1/x9/X962Parameters.cs b/crypto/src/asn1/x9/X962Parameters.cs
index 5b7eaa1de..04a5c9cbe 100644 --- a/crypto/src/asn1/x9/X962Parameters.cs +++ b/crypto/src/asn1/x9/X962Parameters.cs
@@ -1,3 +1,5 @@ +using System; + using Org.BouncyCastle.Asn1; namespace Org.BouncyCastle.Asn1.X9 @@ -7,6 +9,34 @@ namespace Org.BouncyCastle.Asn1.X9 { private readonly Asn1Object _params; + public static X962Parameters GetInstance( + object obj) + { + if (obj == null || obj is X962Parameters) + { + return (X962Parameters)obj; + } + + if (obj is Asn1Object) + { + return new X962Parameters((Asn1Object)obj); + } + + if (obj is byte[]) + { + try + { + return new X962Parameters(Asn1Object.FromByteArray((byte[])obj)); + } + catch (Exception e) + { + throw new ArgumentException("unable to parse encoded data: " + e.Message, e); + } + } + + throw new ArgumentException("unknown object in getInstance()"); + } + public X962Parameters( X9ECParameters ecParameters) { @@ -30,6 +60,11 @@ namespace Org.BouncyCastle.Asn1.X9 get { return (_params is DerObjectIdentifier); } } + public bool IsImplicitlyCA + { + get { return (_params is Asn1Null); } + } + public Asn1Object Parameters { get { return _params; } diff --git a/crypto/src/asn1/x9/X9ECParameters.cs b/crypto/src/asn1/x9/X9ECParameters.cs
index 2b6b14bcb..0fa343768 100644 --- a/crypto/src/asn1/x9/X9ECParameters.cs +++ b/crypto/src/asn1/x9/X9ECParameters.cs
@@ -20,6 +20,21 @@ namespace Org.BouncyCastle.Asn1.X9 private BigInteger h; private byte[] seed; + public static X9ECParameters GetInstance(Object obj) + { + if (obj is X9ECParameters) + { + return (X9ECParameters)obj; + } + + if (obj != null) + { + return new X9ECParameters(Asn1Sequence.GetInstance(obj)); + } + + return null; + } + public X9ECParameters( Asn1Sequence seq) { diff --git a/crypto/src/bcpg/ArmoredInputStream.cs b/crypto/src/bcpg/ArmoredInputStream.cs
index 3109dd4fd..d5d9f7ffb 100644 --- a/crypto/src/bcpg/ArmoredInputStream.cs +++ b/crypto/src/bcpg/ArmoredInputStream.cs
@@ -504,10 +504,21 @@ namespace Org.BouncyCastle.Bcpg return pos - offset; } +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + Platform.Dispose(input); + } + base.Dispose(disposing); + } +#else public override void Close() { - input.Close(); + Platform.Dispose(input); base.Close(); } +#endif } } diff --git a/crypto/src/bcpg/ArmoredOutputStream.cs b/crypto/src/bcpg/ArmoredOutputStream.cs
index fb1f6eb29..1f0e412d8 100644 --- a/crypto/src/bcpg/ArmoredOutputStream.cs +++ b/crypto/src/bcpg/ArmoredOutputStream.cs
@@ -101,16 +101,7 @@ namespace Org.BouncyCastle.Bcpg private static readonly string footerStart = "-----END PGP "; private static readonly string footerTail = "-----"; - private static readonly string version = "BCPG C# v" -#if PORTABLE - + Assembly.GetExecutingAssembly() - .GetCustomAttributes(typeof(AssemblyVersionAttribute), true) - .Cast<AssemblyVersionAttribute>() - .First() - .Version; -#else - + Assembly.GetExecutingAssembly().GetName().Version; -#endif + private static readonly string version = "BCPG C# v" + AssemblyInfo.Version; private readonly IDictionary headers; @@ -292,37 +283,60 @@ namespace Org.BouncyCastle.Bcpg * <b>Note</b>: Close() does not close the underlying stream. So it is possible to write * multiple objects using armoring to a single stream. */ - public override void Close() +#if PORTABLE + protected override void Dispose(bool disposing) { - if (type != null) + if (disposing) { - if (bufPtr > 0) - { - Encode(outStream, buf, bufPtr); - } + if (type == null) + return; - DoWrite(nl + '='); + DoClose(); - int crcV = crc.Value; + type = null; + start = true; + } + base.Dispose(disposing); + } +#else + public override void Close() + { + if (type == null) + return; - buf[0] = ((crcV >> 16) & 0xff); - buf[1] = ((crcV >> 8) & 0xff); - buf[2] = (crcV & 0xff); + DoClose(); - Encode(outStream, buf, 3); + type = null; + start = true; - DoWrite(nl); - DoWrite(footerStart); - DoWrite(type); - DoWrite(footerTail); - DoWrite(nl); - - outStream.Flush(); + base.Close(); + } +#endif - type = null; - start = true; - base.Close(); + private void DoClose() + { + if (bufPtr > 0) + { + Encode(outStream, buf, bufPtr); } + + DoWrite(nl + '='); + + int crcV = crc.Value; + + buf[0] = ((crcV >> 16) & 0xff); + buf[1] = ((crcV >> 8) & 0xff); + buf[2] = (crcV & 0xff); + + Encode(outStream, buf, 3); + + DoWrite(nl); + DoWrite(footerStart); + DoWrite(type); + DoWrite(footerTail); + DoWrite(nl); + + outStream.Flush(); } private void WriteHeaderEntry( diff --git a/crypto/src/bcpg/BcpgInputStream.cs b/crypto/src/bcpg/BcpgInputStream.cs
index 2e08cd090..f9627fde0 100644 --- a/crypto/src/bcpg/BcpgInputStream.cs +++ b/crypto/src/bcpg/BcpgInputStream.cs
@@ -2,6 +2,7 @@ using System; using System.IO; using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.IO; namespace Org.BouncyCastle.Bcpg @@ -246,11 +247,22 @@ namespace Org.BouncyCastle.Bcpg } } +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + Platform.Dispose(m_in); + } + base.Dispose(disposing); + } +#else public override void Close() { - m_in.Close(); + Platform.Dispose(m_in); base.Close(); } +#endif /// <summary> /// A stream that overlays our input stream, allowing the user to only read a segment of it. diff --git a/crypto/src/bcpg/BcpgOutputStream.cs b/crypto/src/bcpg/BcpgOutputStream.cs
index 204f65b50..7ab661edb 100644 --- a/crypto/src/bcpg/BcpgOutputStream.cs +++ b/crypto/src/bcpg/BcpgOutputStream.cs
@@ -1,6 +1,7 @@ using System; using System.IO; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.IO; namespace Org.BouncyCastle.Bcpg @@ -379,12 +380,25 @@ namespace Org.BouncyCastle.Bcpg } } - public override void Close() +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + this.Finish(); + outStr.Flush(); + Platform.Dispose(outStr); + } + base.Dispose(disposing); + } +#else + public override void Close() { this.Finish(); outStr.Flush(); - outStr.Close(); + Platform.Dispose(outStr); base.Close(); } +#endif } } diff --git a/crypto/src/bcpg/PublicKeyEncSessionPacket.cs b/crypto/src/bcpg/PublicKeyEncSessionPacket.cs
index 74d04f7aa..831b5a189 100644 --- a/crypto/src/bcpg/PublicKeyEncSessionPacket.cs +++ b/crypto/src/bcpg/PublicKeyEncSessionPacket.cs
@@ -107,7 +107,7 @@ namespace Org.BouncyCastle.Bcpg pOut.Write(data[i]); } - pOut.Close(); + Platform.Dispose(pOut); bcpgOut.WritePacket(PacketTag.PublicKeyEncryptedSession , bOut.ToArray(), true); } diff --git a/crypto/src/cms/CMSAuthenticatedData.cs b/crypto/src/cms/CMSAuthenticatedData.cs
index 5e234da2b..33b4cc22c 100644 --- a/crypto/src/cms/CMSAuthenticatedData.cs +++ b/crypto/src/cms/CMSAuthenticatedData.cs
@@ -83,7 +83,7 @@ namespace Org.BouncyCastle.Cms */ public string MacAlgOid { - get { return macAlg.ObjectID.Id; } + get { return macAlg.Algorithm.Id; } } /** diff --git a/crypto/src/cms/CMSAuthenticatedDataGenerator.cs b/crypto/src/cms/CMSAuthenticatedDataGenerator.cs
index 846c19a24..131a4753f 100644 --- a/crypto/src/cms/CMSAuthenticatedDataGenerator.cs +++ b/crypto/src/cms/CMSAuthenticatedDataGenerator.cs
@@ -9,6 +9,7 @@ using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.IO; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.IO; namespace Org.BouncyCastle.Cms @@ -83,10 +84,9 @@ namespace Org.BouncyCastle.Cms content.Write(mOut); - mOut.Close(); - bOut.Close(); + Platform.Dispose(mOut); - encContent = new BerOctetString(bOut.ToArray()); + encContent = new BerOctetString(bOut.ToArray()); byte[] macOctets = MacUtilities.DoFinal(mac); macResult = new DerOctetString(macOctets); diff --git a/crypto/src/cms/CMSAuthenticatedDataParser.cs b/crypto/src/cms/CMSAuthenticatedDataParser.cs
index c99aac61c..7defafc07 100644 --- a/crypto/src/cms/CMSAuthenticatedDataParser.cs +++ b/crypto/src/cms/CMSAuthenticatedDataParser.cs
@@ -111,7 +111,7 @@ namespace Org.BouncyCastle.Cms */ public string MacAlgOid { - get { return macAlg.ObjectID.Id; } + get { return macAlg.Algorithm.Id; } } diff --git a/crypto/src/cms/CMSAuthenticatedDataStreamGenerator.cs b/crypto/src/cms/CMSAuthenticatedDataStreamGenerator.cs
index 2603cb380..4d18d10d4 100644 --- a/crypto/src/cms/CMSAuthenticatedDataStreamGenerator.cs +++ b/crypto/src/cms/CMSAuthenticatedDataStreamGenerator.cs
@@ -9,6 +9,7 @@ using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.IO; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.IO; namespace Org.BouncyCastle.Cms @@ -164,7 +165,7 @@ namespace Org.BouncyCastle.Cms Stream octetOutputStream = CmsUtilities.CreateBerOctetOutputStream( eiGen.GetRawOutputStream(), 0, false, _bufferSize); - IMac mac = MacUtilities.GetMac(macAlgId.ObjectID); + IMac mac = MacUtilities.GetMac(macAlgId.Algorithm); // TODO Confirm no ParametersWithRandom needed mac.Init(cipherParameters); Stream mOut = new TeeOutputStream(octetOutputStream, new MacOutputStream(mac)); @@ -251,11 +252,33 @@ namespace Org.BouncyCastle.Cms macStream.Write(bytes, off, len); } - public override void Close() +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + Platform.Dispose(macStream); + + // TODO Parent context(s) should really be be closed explicitly + + eiGen.Close(); + + // [TODO] auth attributes go here + byte[] macOctets = MacUtilities.DoFinal(mac); + authGen.AddObject(new DerOctetString(macOctets)); + // [TODO] unauth attributes go here + + authGen.Close(); + cGen.Close(); + } + base.Dispose(disposing); + } +#else + public override void Close() { - macStream.Close(); + Platform.Dispose(macStream); - // TODO Parent context(s) should really be be closed explicitly + // TODO Parent context(s) should really be be closed explicitly eiGen.Close(); @@ -266,7 +289,9 @@ namespace Org.BouncyCastle.Cms authGen.Close(); cGen.Close(); + base.Close(); } +#endif } } } diff --git a/crypto/src/cms/CMSCompressedData.cs b/crypto/src/cms/CMSCompressedData.cs
index 2d0107e88..21651f041 100644 --- a/crypto/src/cms/CMSCompressedData.cs +++ b/crypto/src/cms/CMSCompressedData.cs
@@ -3,6 +3,7 @@ using System.IO; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Cms; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Zlib; namespace Org.BouncyCastle.Cms @@ -56,7 +57,7 @@ namespace Org.BouncyCastle.Cms } finally { - zIn.Close(); + Platform.Dispose(zIn); } } diff --git a/crypto/src/cms/CMSCompressedDataGenerator.cs b/crypto/src/cms/CMSCompressedDataGenerator.cs
index 00e2a3df4..d51de1026 100644 --- a/crypto/src/cms/CMSCompressedDataGenerator.cs +++ b/crypto/src/cms/CMSCompressedDataGenerator.cs
@@ -5,6 +5,7 @@ using System.IO; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Cms; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Zlib; namespace Org.BouncyCastle.Cms @@ -45,9 +46,9 @@ namespace Org.BouncyCastle.Cms content.Write(zOut); - zOut.Close(); + Platform.Dispose(zOut); - comAlgId = new AlgorithmIdentifier(new DerObjectIdentifier(compressionOid)); + comAlgId = new AlgorithmIdentifier(new DerObjectIdentifier(compressionOid)); comOcts = new BerOctetString(bOut.ToArray()); } catch (IOException e) diff --git a/crypto/src/cms/CMSCompressedDataStreamGenerator.cs b/crypto/src/cms/CMSCompressedDataStreamGenerator.cs
index db0d19845..0cb1bb641 100644 --- a/crypto/src/cms/CMSCompressedDataStreamGenerator.cs +++ b/crypto/src/cms/CMSCompressedDataStreamGenerator.cs
@@ -4,6 +4,7 @@ using System.IO; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Cms; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.IO; using Org.BouncyCastle.Utilities.Zlib; @@ -124,17 +125,34 @@ namespace Org.BouncyCastle.Cms _out.Write(bytes, off, len); } - public override void Close() +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + Platform.Dispose(_out); + + // TODO Parent context(s) should really be be closed explicitly + + _eiGen.Close(); + _cGen.Close(); + _sGen.Close(); + } + base.Dispose(disposing); + } +#else + public override void Close() { - _out.Close(); + Platform.Dispose(_out); - // TODO Parent context(s) should really be be closed explicitly + // TODO Parent context(s) should really be be closed explicitly - _eiGen.Close(); + _eiGen.Close(); _cGen.Close(); _sGen.Close(); base.Close(); } +#endif } } } diff --git a/crypto/src/cms/CMSContentInfoParser.cs b/crypto/src/cms/CMSContentInfoParser.cs
index fde06cf4c..a7b43f295 100644 --- a/crypto/src/cms/CMSContentInfoParser.cs +++ b/crypto/src/cms/CMSContentInfoParser.cs
@@ -3,6 +3,7 @@ using System.IO; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Cms; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Cms { @@ -41,7 +42,7 @@ namespace Org.BouncyCastle.Cms */ public void Close() { - this.data.Close(); + Platform.Dispose(this.data); } } } diff --git a/crypto/src/cms/CMSEnvelopedData.cs b/crypto/src/cms/CMSEnvelopedData.cs
index 0731c307e..223d0ca73 100644 --- a/crypto/src/cms/CMSEnvelopedData.cs +++ b/crypto/src/cms/CMSEnvelopedData.cs
@@ -73,7 +73,7 @@ namespace Org.BouncyCastle.Cms */ public string EncryptionAlgOid { - get { return encAlg.ObjectID.Id; } + get { return encAlg.Algorithm.Id; } } /** diff --git a/crypto/src/cms/CMSEnvelopedDataGenerator.cs b/crypto/src/cms/CMSEnvelopedDataGenerator.cs
index 3b861cde5..d260e998a 100644 --- a/crypto/src/cms/CMSEnvelopedDataGenerator.cs +++ b/crypto/src/cms/CMSEnvelopedDataGenerator.cs
@@ -80,9 +80,9 @@ namespace Org.BouncyCastle.Cms content.Write(cOut); - cOut.Close(); + Platform.Dispose(cOut); - encContent = new BerOctetString(bOut.ToArray()); + encContent = new BerOctetString(bOut.ToArray()); } catch (SecurityUtilityException e) { diff --git a/crypto/src/cms/CMSEnvelopedDataParser.cs b/crypto/src/cms/CMSEnvelopedDataParser.cs
index 01a949d47..d5dfaf53d 100644 --- a/crypto/src/cms/CMSEnvelopedDataParser.cs +++ b/crypto/src/cms/CMSEnvelopedDataParser.cs
@@ -101,7 +101,7 @@ namespace Org.BouncyCastle.Cms */ public string EncryptionAlgOid { - get { return _encAlg.ObjectID.Id; } + get { return _encAlg.Algorithm.Id; } } /** diff --git a/crypto/src/cms/CMSEnvelopedDataStreamGenerator.cs b/crypto/src/cms/CMSEnvelopedDataStreamGenerator.cs
index a63ea7b7f..8e6d2729b 100644 --- a/crypto/src/cms/CMSEnvelopedDataStreamGenerator.cs +++ b/crypto/src/cms/CMSEnvelopedDataStreamGenerator.cs
@@ -166,7 +166,7 @@ namespace Org.BouncyCastle.Cms Stream octetOutputStream = CmsUtilities.CreateBerOctetOutputStream( eiGen.GetRawOutputStream(), 0, false, _bufferSize); - IBufferedCipher cipher = CipherUtilities.GetCipher(encAlgID.ObjectID); + IBufferedCipher cipher = CipherUtilities.GetCipher(encAlgID.Algorithm); cipher.Init(true, new ParametersWithRandom(cipherParameters, rand)); CipherStream cOut = new CipherStream(octetOutputStream, null, cipher); @@ -255,11 +255,37 @@ namespace Org.BouncyCastle.Cms _out.Write(bytes, off, len); } - public override void Close() +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + Platform.Dispose(_out); + + // TODO Parent context(s) should really be closed explicitly + + _eiGen.Close(); + + if (_outer.unprotectedAttributeGenerator != null) + { + Asn1.Cms.AttributeTable attrTable = _outer.unprotectedAttributeGenerator.GetAttributes(Platform.CreateHashtable()); + + Asn1Set unprotectedAttrs = new BerSet(attrTable.ToAsn1EncodableVector()); + + _envGen.AddObject(new DerTaggedObject(false, 1, unprotectedAttrs)); + } + + _envGen.Close(); + _cGen.Close(); + } + base.Dispose(disposing); + } +#else + public override void Close() { - _out.Close(); + Platform.Dispose(_out); - // TODO Parent context(s) should really be be closed explicitly + // TODO Parent context(s) should really be closed explicitly _eiGen.Close(); @@ -276,6 +302,7 @@ namespace Org.BouncyCastle.Cms _cGen.Close(); base.Close(); } +#endif } } } diff --git a/crypto/src/cms/CMSEnvelopedHelper.cs b/crypto/src/cms/CMSEnvelopedHelper.cs
index fe2b14cd9..77d2da47a 100644 --- a/crypto/src/cms/CMSEnvelopedHelper.cs +++ b/crypto/src/cms/CMSEnvelopedHelper.cs
@@ -160,7 +160,7 @@ namespace Org.BouncyCastle.Cms public CmsReadable GetReadable(KeyParameter sKey) { - string macAlg = this.algorithm.ObjectID.Id; + string macAlg = this.algorithm.Algorithm.Id; // Asn1Object sParams = this.algorithm.Parameters.ToAsn1Object(); try @@ -190,11 +190,11 @@ namespace Org.BouncyCastle.Cms // if (asn1Params != null && !(asn1Params is Asn1Null)) // { // cipherParameters = ParameterUtilities.GetCipherParameters( -// macAlg.ObjectID, cipherParameters, asn1Params); +// macAlg.Algorithm, cipherParameters, asn1Params); // } // else // { -// string alg = macAlg.ObjectID.Id; +// string alg = macAlg.Algorithm.Id; // if (alg.Equals(CmsEnvelopedDataGenerator.DesEde3Cbc) // || alg.Equals(CmsEnvelopedDataGenerator.IdeaCbc) // || alg.Equals(CmsEnvelopedDataGenerator.Cast5Cbc)) @@ -258,7 +258,7 @@ namespace Org.BouncyCastle.Cms { try { - this.cipher = CipherUtilities.GetCipher(this.algorithm.ObjectID); + this.cipher = CipherUtilities.GetCipher(this.algorithm.Algorithm); Asn1Encodable asn1Enc = this.algorithm.Parameters; Asn1Object asn1Params = asn1Enc == null ? null : asn1Enc.ToAsn1Object(); @@ -268,11 +268,11 @@ namespace Org.BouncyCastle.Cms if (asn1Params != null && !(asn1Params is Asn1Null)) { cipherParameters = ParameterUtilities.GetCipherParameters( - this.algorithm.ObjectID, cipherParameters, asn1Params); + this.algorithm.Algorithm, cipherParameters, asn1Params); } else { - string alg = this.algorithm.ObjectID.Id; + string alg = this.algorithm.Algorithm.Id; if (alg.Equals(CmsEnvelopedDataGenerator.DesEde3Cbc) || alg.Equals(CmsEnvelopedDataGenerator.IdeaCbc) || alg.Equals(CmsEnvelopedDataGenerator.Cast5Cbc)) diff --git a/crypto/src/cms/CMSPBEKey.cs b/crypto/src/cms/CMSPBEKey.cs
index cb1e54c36..e03307e57 100644 --- a/crypto/src/cms/CMSPBEKey.cs +++ b/crypto/src/cms/CMSPBEKey.cs
@@ -50,9 +50,9 @@ namespace Org.BouncyCastle.Cms char[] password, AlgorithmIdentifier keyDerivationAlgorithm) { - if (!keyDerivationAlgorithm.ObjectID.Equals(PkcsObjectIdentifiers.IdPbkdf2)) + if (!keyDerivationAlgorithm.Algorithm.Equals(PkcsObjectIdentifiers.IdPbkdf2)) throw new ArgumentException("Unsupported key derivation algorithm: " - + keyDerivationAlgorithm.ObjectID); + + keyDerivationAlgorithm.Algorithm); Pbkdf2Params kdfParams = Pbkdf2Params.GetInstance( keyDerivationAlgorithm.Parameters.ToAsn1Object()); diff --git a/crypto/src/cms/CMSProcessableFile.cs b/crypto/src/cms/CMSProcessableFile.cs
index 764d138f0..c74d2a846 100644 --- a/crypto/src/cms/CMSProcessableFile.cs +++ b/crypto/src/cms/CMSProcessableFile.cs
@@ -1,7 +1,8 @@ -#if !PORTABLE +#if !PORTABLE || DOTNET using System; using System.IO; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.IO; namespace Org.BouncyCastle.Cms @@ -37,7 +38,7 @@ namespace Org.BouncyCastle.Cms { Stream inStr = GetInputStream(); Streams.PipeAll(inStr, zOut); - inStr.Close(); + Platform.Dispose(inStr); } /// <returns>The file handle</returns> diff --git a/crypto/src/cms/CMSProcessableInputStream.cs b/crypto/src/cms/CMSProcessableInputStream.cs
index 6dff7c212..b2abd6f71 100644 --- a/crypto/src/cms/CMSProcessableInputStream.cs +++ b/crypto/src/cms/CMSProcessableInputStream.cs
@@ -1,6 +1,7 @@ using System; using System.IO; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.IO; namespace Org.BouncyCastle.Cms @@ -29,7 +30,7 @@ namespace Org.BouncyCastle.Cms CheckSingleUsage(); Streams.PipeAll(input, output); - input.Close(); + Platform.Dispose(input); } [Obsolete] diff --git a/crypto/src/cms/CMSSignedData.cs b/crypto/src/cms/CMSSignedData.cs
index 81c87a426..237c1528e 100644 --- a/crypto/src/cms/CMSSignedData.cs +++ b/crypto/src/cms/CMSSignedData.cs
@@ -172,7 +172,7 @@ namespace Org.BouncyCastle.Cms } else { - byte[] hash = (byte[]) hashes[info.DigestAlgorithm.ObjectID.Id]; + byte[] hash = (byte[])hashes[info.DigestAlgorithm.Algorithm.Id]; signerInfos.Add(new SignerInformation(info, contentType, null, new BaseDigestCalculator(hash))); } diff --git a/crypto/src/cms/CMSSignedDataGenerator.cs b/crypto/src/cms/CMSSignedDataGenerator.cs
index f4720597d..f63ed874e 100644 --- a/crypto/src/cms/CMSSignedDataGenerator.cs +++ b/crypto/src/cms/CMSSignedDataGenerator.cs
@@ -43,7 +43,7 @@ namespace Org.BouncyCastle.Cms { private readonly CmsSignedGenerator outer; - private readonly ISignatureCalculator sigCalc; + private readonly ISignatureFactory sigCalc; private readonly SignerIdentifier signerIdentifier; private readonly string digestOID; private readonly string encOID; @@ -66,7 +66,7 @@ namespace Org.BouncyCastle.Cms string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID); this.outer = outer; - this.sigCalc = new Asn1SignatureCalculator(signatureName, key); + this.sigCalc = new Asn1SignatureFactory(signatureName, key); this.signerIdentifier = signerIdentifier; this.digestOID = digestOID; this.encOID = encOID; @@ -77,7 +77,7 @@ namespace Org.BouncyCastle.Cms internal SignerInf( CmsSignedGenerator outer, - ISignatureCalculator sigCalc, + ISignatureFactory sigCalc, SignerIdentifier signerIdentifier, CmsAttributeTableGenerator sAttr, CmsAttributeTableGenerator unsAttr, @@ -173,7 +173,7 @@ namespace Org.BouncyCastle.Cms content.Write(sigStr); } - sigStr.Close(); + Platform.Dispose(sigStr); byte[] sigBytes = ((IBlockResult)calculator.GetResult()).Collect(); Asn1Set unsignedAttr = null; diff --git a/crypto/src/cms/CMSSignedDataParser.cs b/crypto/src/cms/CMSSignedDataParser.cs
index e5674a4cf..fb51ab119 100644 --- a/crypto/src/cms/CMSSignedDataParser.cs +++ b/crypto/src/cms/CMSSignedDataParser.cs
@@ -122,7 +122,7 @@ namespace Org.BouncyCastle.Cms try { - string digestOid = id.ObjectID.Id; + string digestOid = id.Algorithm.Id; string digestName = Helper.GetDigestAlgName(digestOid); if (!this._digests.Contains(digestName)) @@ -216,7 +216,7 @@ namespace Org.BouncyCastle.Cms { SignerInfo info = SignerInfo.GetInstance(o.ToAsn1Object()); string digestName = Helper.GetDigestAlgName( - info.DigestAlgorithm.ObjectID.Id); + info.DigestAlgorithm.Algorithm.Id); byte[] hash = (byte[]) hashes[digestName]; @@ -384,7 +384,7 @@ namespace Org.BouncyCastle.Cms // gen.AddSigners(parser.GetSignerInfos()); - contentOut.Close(); + Platform.Dispose(contentOut); return outStr; } @@ -434,12 +434,12 @@ namespace Org.BouncyCastle.Cms gen.AddSigners(parser.GetSignerInfos()); - contentOut.Close(); + Platform.Dispose(contentOut); - return outStr; + return outStr; } - private static Asn1Set GetAsn1Set( + private static Asn1Set GetAsn1Set( Asn1SetParser asn1SetParser) { return asn1SetParser == null diff --git a/crypto/src/cms/CMSSignedDataStreamGenerator.cs b/crypto/src/cms/CMSSignedDataStreamGenerator.cs
index 223fdb39d..d0ab7428a 100644 --- a/crypto/src/cms/CMSSignedDataStreamGenerator.cs +++ b/crypto/src/cms/CMSSignedDataStreamGenerator.cs
@@ -459,7 +459,7 @@ namespace Org.BouncyCastle.Cms // NB: Would need to call FixAlgID on the DigestAlgorithmID // For precalculated signers, just need to register the algorithm, not configure a digest - RegisterDigestOid(si.DigestAlgorithmID.ObjectID.Id); + RegisterDigestOid(si.DigestAlgorithmID.Algorithm.Id); } /** @@ -636,7 +636,7 @@ namespace Org.BouncyCastle.Cms { content.Write(signedOut); } - signedOut.Close(); + Platform.Dispose(signedOut); } // RFC3852, section 5.1: @@ -809,11 +809,28 @@ namespace Org.BouncyCastle.Cms _out.Write(bytes, off, len); } +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + DoClose(); + } + base.Dispose(disposing); + } +#else public override void Close() { - _out.Close(); + DoClose(); + base.Close(); + } +#endif - // TODO Parent context(s) should really be be closed explicitly + private void DoClose() + { + Platform.Dispose(_out); + + // TODO Parent context(s) should really be be closed explicitly _eiGen.Close(); @@ -898,8 +915,7 @@ namespace Org.BouncyCastle.Cms _sigGen.Close(); _sGen.Close(); - base.Close(); - } + } private static void WriteToGenerator( Asn1Generator ag, diff --git a/crypto/src/cms/CMSSignedHelper.cs b/crypto/src/cms/CMSSignedHelper.cs
index 23657ef86..5b6c93b6a 100644 --- a/crypto/src/cms/CMSSignedHelper.cs +++ b/crypto/src/cms/CMSSignedHelper.cs
@@ -348,7 +348,7 @@ namespace Org.BouncyCastle.Cms AlgorithmIdentifier algId) { if (algId.Parameters == null) - return new AlgorithmIdentifier(algId.ObjectID, DerNull.Instance); + return new AlgorithmIdentifier(algId.Algorithm, DerNull.Instance); return algId; } diff --git a/crypto/src/cms/CMSTypedStream.cs b/crypto/src/cms/CMSTypedStream.cs
index b7b390c4c..681583765 100644 --- a/crypto/src/cms/CMSTypedStream.cs +++ b/crypto/src/cms/CMSTypedStream.cs
@@ -2,6 +2,7 @@ using System; using System.IO; using Org.BouncyCastle.Asn1.Pkcs; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.IO; namespace Org.BouncyCastle.Cms @@ -52,7 +53,7 @@ namespace Org.BouncyCastle.Cms public void Drain() { Streams.Drain(_in); - _in.Close(); + Platform.Dispose(_in); } private class FullReaderStream : FilterStream diff --git a/crypto/src/cms/KEKRecipientInfoGenerator.cs b/crypto/src/cms/KEKRecipientInfoGenerator.cs
index a9bedade6..6f34fec43 100644 --- a/crypto/src/cms/KEKRecipientInfoGenerator.cs +++ b/crypto/src/cms/KEKRecipientInfoGenerator.cs
@@ -10,6 +10,7 @@ using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Cms { @@ -52,7 +53,7 @@ namespace Org.BouncyCastle.Cms { byte[] keyBytes = contentEncryptionKey.GetKey(); - IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionAlgorithm.ObjectID.Id); + IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionAlgorithm.Algorithm.Id); keyWrapper.Init(true, new ParametersWithRandom(keyEncryptionKey, random)); Asn1OctetString encryptedKey = new DerOctetString( keyWrapper.Wrap(keyBytes, 0, keyBytes.Length)); @@ -63,19 +64,19 @@ namespace Org.BouncyCastle.Cms private static AlgorithmIdentifier DetermineKeyEncAlg( string algorithm, KeyParameter key) { - if (algorithm.StartsWith("DES")) + if (Platform.StartsWith(algorithm, "DES")) { return new AlgorithmIdentifier( PkcsObjectIdentifiers.IdAlgCms3DesWrap, DerNull.Instance); } - else if (algorithm.StartsWith("RC2")) + else if (Platform.StartsWith(algorithm, "RC2")) { return new AlgorithmIdentifier( PkcsObjectIdentifiers.IdAlgCmsRC2Wrap, new DerInteger(58)); } - else if (algorithm.StartsWith("AES")) + else if (Platform.StartsWith(algorithm, "AES")) { int length = key.GetKey().Length * 8; DerObjectIdentifier wrapOid; @@ -99,12 +100,12 @@ namespace Org.BouncyCastle.Cms return new AlgorithmIdentifier(wrapOid); // parameters absent } - else if (algorithm.StartsWith("SEED")) + else if (Platform.StartsWith(algorithm, "SEED")) { // parameters absent return new AlgorithmIdentifier(KisaObjectIdentifiers.IdNpkiAppCmsSeedWrap); } - else if (algorithm.StartsWith("CAMELLIA")) + else if (Platform.StartsWith(algorithm, "CAMELLIA")) { int length = key.GetKey().Length * 8; DerObjectIdentifier wrapOid; diff --git a/crypto/src/cms/KEKRecipientInformation.cs b/crypto/src/cms/KEKRecipientInformation.cs
index f960197d6..871dc76d4 100644 --- a/crypto/src/cms/KEKRecipientInformation.cs +++ b/crypto/src/cms/KEKRecipientInformation.cs
@@ -40,7 +40,7 @@ namespace Org.BouncyCastle.Cms try { byte[] encryptedKey = info.EncryptedKey.GetOctets(); - IWrapper keyWrapper = WrapperUtilities.GetWrapper(keyEncAlg.ObjectID.Id); + IWrapper keyWrapper = WrapperUtilities.GetWrapper(keyEncAlg.Algorithm.Id); keyWrapper.Init(false, key); diff --git a/crypto/src/cms/KeyAgreeRecipientInfoGenerator.cs b/crypto/src/cms/KeyAgreeRecipientInfoGenerator.cs
index 4fafb7c6e..6bd2cea91 100644 --- a/crypto/src/cms/KeyAgreeRecipientInfoGenerator.cs +++ b/crypto/src/cms/KeyAgreeRecipientInfoGenerator.cs
@@ -164,7 +164,7 @@ namespace Org.BouncyCastle.Cms { SubjectPublicKeyInfo spki = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); return new OriginatorPublicKey( - new AlgorithmIdentifier(spki.AlgorithmID.ObjectID, DerNull.Instance), + new AlgorithmIdentifier(spki.AlgorithmID.Algorithm, DerNull.Instance), spki.PublicKeyData.GetBytes()); } } diff --git a/crypto/src/cms/KeyAgreeRecipientInformation.cs b/crypto/src/cms/KeyAgreeRecipientInformation.cs
index 8e006e545..73e57a76a 100644 --- a/crypto/src/cms/KeyAgreeRecipientInformation.cs +++ b/crypto/src/cms/KeyAgreeRecipientInformation.cs
@@ -130,7 +130,7 @@ namespace Org.BouncyCastle.Cms AsymmetricKeyParameter senderPublicKey, AsymmetricKeyParameter receiverPrivateKey) { - DerObjectIdentifier agreeAlgID = keyEncAlg.ObjectID; + DerObjectIdentifier agreeAlgID = keyEncAlg.Algorithm; ICipherParameters senderPublicParams = senderPublicKey; ICipherParameters receiverPrivateParams = receiverPrivateKey; diff --git a/crypto/src/cms/KeyTransRecipientInfoGenerator.cs b/crypto/src/cms/KeyTransRecipientInfoGenerator.cs
index 0992e6da6..a1d8fbfa8 100644 --- a/crypto/src/cms/KeyTransRecipientInfoGenerator.cs +++ b/crypto/src/cms/KeyTransRecipientInfoGenerator.cs
@@ -64,7 +64,7 @@ namespace Org.BouncyCastle.Cms byte[] keyBytes = contentEncryptionKey.GetKey(); AlgorithmIdentifier keyEncryptionAlgorithm = info.AlgorithmID; - IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionAlgorithm.ObjectID.Id); + IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionAlgorithm.Algorithm.Id); keyWrapper.Init(true, new ParametersWithRandom(recipientPublicKey, random)); byte[] encryptedKeyBytes = keyWrapper.Wrap(keyBytes, 0, keyBytes.Length); diff --git a/crypto/src/cms/KeyTransRecipientInformation.cs b/crypto/src/cms/KeyTransRecipientInformation.cs
index 24121cb2c..3b1ea7b5e 100644 --- a/crypto/src/cms/KeyTransRecipientInformation.cs +++ b/crypto/src/cms/KeyTransRecipientInformation.cs
@@ -68,7 +68,7 @@ namespace Org.BouncyCastle.Cms internal KeyParameter UnwrapKey(ICipherParameters key) { byte[] encryptedKey = info.EncryptedKey.GetOctets(); - string keyExchangeAlgorithm = GetExchangeEncryptionAlgorithmName(keyEncAlg.ObjectID); + string keyExchangeAlgorithm = GetExchangeEncryptionAlgorithmName(keyEncAlg.Algorithm); try { diff --git a/crypto/src/cms/PasswordRecipientInfoGenerator.cs b/crypto/src/cms/PasswordRecipientInfoGenerator.cs
index 0a0b27b53..9916edfc4 100644 --- a/crypto/src/cms/PasswordRecipientInfoGenerator.cs +++ b/crypto/src/cms/PasswordRecipientInfoGenerator.cs
@@ -7,6 +7,7 @@ using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Cms { @@ -46,7 +47,7 @@ namespace Org.BouncyCastle.Cms IWrapper keyWrapper = Helper.CreateWrapper(rfc3211WrapperName); // Note: In Java build, the IV is automatically generated in JCE layer - int ivLength = rfc3211WrapperName.StartsWith("DESEDE") ? 8 : 16; + int ivLength = Platform.StartsWith(rfc3211WrapperName, "DESEDE") ? 8 : 16; byte[] iv = new byte[ivLength]; random.NextBytes(iv); diff --git a/crypto/src/cms/RecipientInformation.cs b/crypto/src/cms/RecipientInformation.cs
index 8b0316be4..272b841f2 100644 --- a/crypto/src/cms/RecipientInformation.cs +++ b/crypto/src/cms/RecipientInformation.cs
@@ -33,8 +33,8 @@ namespace Org.BouncyCastle.Cms internal string GetContentAlgorithmName() { AlgorithmIdentifier algorithm = secureReadable.Algorithm; -// return CmsEnvelopedHelper.Instance.GetSymmetricCipherName(algorithm.ObjectID.Id); - return algorithm.ObjectID.Id; +// return CmsEnvelopedHelper.Instance.GetSymmetricCipherName(algorithm.Algorithm.Id); + return algorithm.Algorithm.Id; } public RecipientID RecipientID @@ -54,7 +54,7 @@ namespace Org.BouncyCastle.Cms */ public string KeyEncryptionAlgOid { - get { return keyEncAlg.ObjectID.Id; } + get { return keyEncAlg.Algorithm.Id; } } /** diff --git a/crypto/src/cms/SignerInfoGenerator.cs b/crypto/src/cms/SignerInfoGenerator.cs
index 62db40ad8..7b9318cc9 100644 --- a/crypto/src/cms/SignerInfoGenerator.cs +++ b/crypto/src/cms/SignerInfoGenerator.cs
@@ -17,21 +17,21 @@ namespace Org.BouncyCastle.Cms public class SignerInfoGenerator { internal X509Certificate certificate; - internal ISignatureCalculator contentSigner; + internal ISignatureFactory contentSigner; internal SignerIdentifier sigId; internal CmsAttributeTableGenerator signedGen; internal CmsAttributeTableGenerator unsignedGen; private bool isDirectSignature; - internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureCalculator contentSigner): this(sigId, contentSigner, false) + internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureFactory signerFactory): this(sigId, signerFactory, false) { } - internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureCalculator contentSigner, bool isDirectSignature) + internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureFactory signerFactory, bool isDirectSignature) { this.sigId = sigId; - this.contentSigner = contentSigner; + this.contentSigner = signerFactory; this.isDirectSignature = isDirectSignature; if (this.isDirectSignature) { @@ -45,7 +45,7 @@ namespace Org.BouncyCastle.Cms } } - internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureCalculator contentSigner, CmsAttributeTableGenerator signedGen, CmsAttributeTableGenerator unsignedGen) + internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureFactory contentSigner, CmsAttributeTableGenerator signedGen, CmsAttributeTableGenerator unsignedGen) { this.sigId = sigId; this.contentSigner = contentSigner; @@ -117,7 +117,7 @@ namespace Org.BouncyCastle.Cms * @return a SignerInfoGenerator * @throws OperatorCreationException if the generator cannot be built. */ - public SignerInfoGenerator Build(ISignatureCalculator contentSigner, X509Certificate certificate) + public SignerInfoGenerator Build(ISignatureFactory contentSigner, X509Certificate certificate) { SignerIdentifier sigId = new SignerIdentifier(new IssuerAndSerialNumber(certificate.IssuerDN, new DerInteger(certificate.SerialNumber))); @@ -132,19 +132,18 @@ namespace Org.BouncyCastle.Cms * Build a generator with the passed in subjectKeyIdentifier as the signerIdentifier. If used you should * try to follow the calculation described in RFC 5280 section 4.2.1.2. * - * @param contentSigner operator for generating the final signature in the SignerInfo with. + * @param signerFactory operator factory for generating the final signature in the SignerInfo with. * @param subjectKeyIdentifier key identifier to identify the public key for verifying the signature. * @return a SignerInfoGenerator - * @throws OperatorCreationException if the generator cannot be built. */ - public SignerInfoGenerator Build(ISignatureCalculator contentSigner, byte[] subjectKeyIdentifier) + public SignerInfoGenerator Build(ISignatureFactory signerFactory, byte[] subjectKeyIdentifier) { SignerIdentifier sigId = new SignerIdentifier(new DerOctetString(subjectKeyIdentifier)); - return CreateGenerator(contentSigner, sigId); + return CreateGenerator(signerFactory, sigId); } - private SignerInfoGenerator CreateGenerator(ISignatureCalculator contentSigner, SignerIdentifier sigId) + private SignerInfoGenerator CreateGenerator(ISignatureFactory contentSigner, SignerIdentifier sigId) { if (directSignature) { diff --git a/crypto/src/cms/SignerInformation.cs b/crypto/src/cms/SignerInformation.cs
index 581286a3f..dad128263 100644 --- a/crypto/src/cms/SignerInformation.cs +++ b/crypto/src/cms/SignerInformation.cs
@@ -117,7 +117,7 @@ namespace Org.BouncyCastle.Cms */ public string DigestAlgOid { - get { return digestAlgorithm.ObjectID.Id; } + get { return digestAlgorithm.Algorithm.Id; } } /** @@ -156,7 +156,7 @@ namespace Org.BouncyCastle.Cms */ public string EncryptionAlgOid { - get { return encryptionAlgorithm.ObjectID.Id; } + get { return encryptionAlgorithm.Algorithm.Id; } } /** @@ -272,7 +272,7 @@ namespace Org.BouncyCastle.Cms */ SignerInfo si = SignerInfo.GetInstance(asn1Obj.ToAsn1Object()); - string digestName = CmsSignedHelper.Instance.GetDigestAlgName(si.DigestAlgorithm.ObjectID.Id); + string digestName = CmsSignedHelper.Instance.GetDigestAlgName(si.DigestAlgorithm.Algorithm.Id); counterSignatures.Add(new SignerInformation(si, null, null, new CounterSignatureDigestCalculator(digestName, GetSignature()))); } @@ -298,7 +298,7 @@ namespace Org.BouncyCastle.Cms string digestName = Helper.GetDigestAlgName(this.DigestAlgOid); IDigest digest = Helper.GetDigestInstance(digestName); - DerObjectIdentifier sigAlgOid = this.encryptionAlgorithm.ObjectID; + DerObjectIdentifier sigAlgOid = this.encryptionAlgorithm.Algorithm; Asn1Encodable sigParams = this.encryptionAlgorithm.Parameters; ISigner sig; @@ -318,12 +318,12 @@ namespace Org.BouncyCastle.Cms Asn1.Pkcs.RsassaPssParameters pss = Asn1.Pkcs.RsassaPssParameters.GetInstance( sigParams.ToAsn1Object()); - if (!pss.HashAlgorithm.ObjectID.Equals(this.digestAlgorithm.ObjectID)) + if (!pss.HashAlgorithm.Algorithm.Equals(this.digestAlgorithm.Algorithm)) throw new CmsException("RSASSA-PSS signature parameters specified incorrect hash algorithm"); - if (!pss.MaskGenAlgorithm.ObjectID.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdMgf1)) + if (!pss.MaskGenAlgorithm.Algorithm.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdMgf1)) throw new CmsException("RSASSA-PSS signature parameters specified unknown MGF"); - IDigest pssDigest = DigestUtilities.GetDigest(pss.HashAlgorithm.ObjectID); + IDigest pssDigest = DigestUtilities.GetDigest(pss.HashAlgorithm.Algorithm); int saltLength = pss.SaltLength.Value.IntValue; byte trailerField = (byte) pss.TrailerField.Value.IntValue; @@ -532,7 +532,7 @@ namespace Org.BouncyCastle.Cms DigestInfo digInfo = DerDecode(decrypt); - if (!digInfo.AlgorithmID.ObjectID.Equals(digestAlgorithm.ObjectID)) + if (!digInfo.AlgorithmID.Algorithm.Equals(digestAlgorithm.Algorithm)) { return false; } diff --git a/crypto/src/crypto/CipherKeyGenerator.cs b/crypto/src/crypto/CipherKeyGenerator.cs
index 5d00d34dd..d8d9b29b5 100644 --- a/crypto/src/crypto/CipherKeyGenerator.cs +++ b/crypto/src/crypto/CipherKeyGenerator.cs
@@ -75,9 +75,9 @@ namespace Org.BouncyCastle.Crypto return engineGenerateKey(); } - protected virtual byte[] engineGenerateKey() + protected virtual byte[] engineGenerateKey() { - return random.GenerateSeed(strength); + return SecureRandom.GetNextBytes(random, strength); } } } diff --git a/crypto/src/crypto/IEntropySource.cs b/crypto/src/crypto/IEntropySource.cs new file mode 100644
index 000000000..62e3bc76c --- /dev/null +++ b/crypto/src/crypto/IEntropySource.cs
@@ -0,0 +1,29 @@ +using System; + +namespace Org.BouncyCastle.Crypto +{ + /// <summary> + /// Base interface describing an entropy source for a DRBG. + /// </summary> + public interface IEntropySource + { + /// <summary> + /// Return whether or not this entropy source is regarded as prediction resistant. + /// </summary> + /// <value><c>true</c> if this instance is prediction resistant; otherwise, <c>false</c>.</value> + bool IsPredictionResistant { get; } + + /// <summary> + /// Return a byte array of entropy. + /// </summary> + /// <returns>The entropy bytes.</returns> + byte[] GetEntropy(); + + /// <summary> + /// Return the number of bits of entropy this source can produce. + /// </summary> + /// <value>The size, in bits, of the return value of getEntropy.</value> + int EntropySize { get; } + } +} + diff --git a/crypto/src/crypto/IEntropySourceProvider.cs b/crypto/src/crypto/IEntropySourceProvider.cs new file mode 100644
index 000000000..756414171 --- /dev/null +++ b/crypto/src/crypto/IEntropySourceProvider.cs
@@ -0,0 +1,17 @@ +using System; + +namespace Org.BouncyCastle.Crypto +{ + /// <summary> + /// Base interface describing a provider of entropy sources. + /// </summary> + public interface IEntropySourceProvider + { + /// <summary> + /// Return an entropy source providing a block of entropy. + /// </summary> + /// <param name="bitsRequired">The size of the block of entropy required.</param> + /// <returns>An entropy source providing bitsRequired blocks of entropy.</returns> + IEntropySource Get(int bitsRequired); + } +} diff --git a/crypto/src/crypto/ISignatureCalculator.cs b/crypto/src/crypto/ISignatureFactory.cs
index bb733818d..cbca7d1a7 100644 --- a/crypto/src/crypto/ISignatureCalculator.cs +++ b/crypto/src/crypto/ISignatureFactory.cs
@@ -5,7 +5,7 @@ namespace Org.BouncyCastle.Crypto /// <summary> /// Base interface for operators that serve as stream-based signature calculators. /// </summary> - public interface ISignatureCalculator + public interface ISignatureFactory { /// <summary>The algorithm details object for this calculator.</summary> Object AlgorithmDetails { get ; } diff --git a/crypto/src/crypto/ISignatureVerifier.cs b/crypto/src/crypto/IVerifierFactory.cs
index 1f42a0256..9502b14a7 100644 --- a/crypto/src/crypto/ISignatureVerifier.cs +++ b/crypto/src/crypto/IVerifierFactory.cs
@@ -5,7 +5,7 @@ namespace Org.BouncyCastle.Crypto /// <summary> /// Base interface for operators that serve as stream-based signature verifiers. /// </summary> - public interface ISignatureVerifier + public interface IVerifierFactory { /// <summary>The algorithm details object for this verifier.</summary> Object AlgorithmDetails { get ; } diff --git a/crypto/src/crypto/ISignatureVerifierProvider.cs b/crypto/src/crypto/IVerifierFactoryProvider.cs
index 20180e22a..9cfcbb2c1 100644 --- a/crypto/src/crypto/ISignatureVerifierProvider.cs +++ b/crypto/src/crypto/IVerifierFactoryProvider.cs
@@ -5,14 +5,14 @@ namespace Org.BouncyCastle.Crypto /// <summary> /// Base interface for a provider to support the dynamic creation of signature verifiers. /// </summary> - public interface ISignatureVerifierProvider + public interface IVerifierFactoryProvider { /// <summary> /// Return a signature verfier for signature algorithm described in the passed in algorithm details object. /// </summary> /// <param name="algorithmDetails">The details of the signature algorithm verification is required for.</param> /// <returns>A new signature verifier.</returns> - ISignatureVerifier CreateSignatureVerifier (Object algorithmDetails); + IVerifierFactory CreateVerifierFactory (Object algorithmDetails); } } diff --git a/crypto/src/crypto/digests/GeneralDigest.cs b/crypto/src/crypto/digests/GeneralDigest.cs
index 54a09ae05..d40ad28bb 100644 --- a/crypto/src/crypto/digests/GeneralDigest.cs +++ b/crypto/src/crypto/digests/GeneralDigest.cs
@@ -55,38 +55,44 @@ namespace Org.BouncyCastle.Crypto.Digests int inOff, int length) { + length = System.Math.Max(0, length); + // // fill the current word // - while ((xBufOff != 0) && (length > 0)) + int i = 0; + if (xBufOff != 0) { - Update(input[inOff]); - inOff++; - length--; + while (i < length) + { + xBuf[xBufOff++] = input[inOff + i++]; + if (xBufOff == 4) + { + ProcessWord(xBuf, 0); + xBufOff = 0; + break; + } + } } // // process whole words. // - while (length > xBuf.Length) + int limit = ((length - i) & ~3) + i; + for (; i < limit; i += 4) { - ProcessWord(input, inOff); - - inOff += xBuf.Length; - length -= xBuf.Length; - byteCount += xBuf.Length; + ProcessWord(input, inOff + i); } // // load in the remainder. // - while (length > 0) + while (i < length) { - Update(input[inOff]); - - inOff++; - length--; + xBuf[xBufOff++] = input[inOff + i++]; } + + byteCount += length; } public void Finish() diff --git a/crypto/src/crypto/digests/NonMemoableDigest.cs b/crypto/src/crypto/digests/NonMemoableDigest.cs new file mode 100644
index 000000000..02c49b887 --- /dev/null +++ b/crypto/src/crypto/digests/NonMemoableDigest.cs
@@ -0,0 +1,62 @@ +using System; + +namespace Org.BouncyCastle.Crypto.Digests +{ + /** + * Wrapper removes exposure to the IMemoable interface on an IDigest implementation. + */ + public class NonMemoableDigest + : IDigest + { + protected readonly IDigest mBaseDigest; + + /** + * Base constructor. + * + * @param baseDigest underlying digest to use. + * @exception IllegalArgumentException if baseDigest is null + */ + public NonMemoableDigest(IDigest baseDigest) + { + if (baseDigest == null) + throw new ArgumentNullException("baseDigest"); + + this.mBaseDigest = baseDigest; + } + + public virtual string AlgorithmName + { + get { return mBaseDigest.AlgorithmName; } + } + + public virtual int GetDigestSize() + { + return mBaseDigest.GetDigestSize(); + } + + public virtual void Update(byte input) + { + mBaseDigest.Update(input); + } + + public virtual void BlockUpdate(byte[] input, int inOff, int len) + { + mBaseDigest.BlockUpdate(input, inOff, len); + } + + public virtual int DoFinal(byte[] output, int outOff) + { + return mBaseDigest.DoFinal(output, outOff); + } + + public virtual void Reset() + { + mBaseDigest.Reset(); + } + + public virtual int GetByteLength() + { + return mBaseDigest.GetByteLength(); + } + } +} diff --git a/crypto/src/crypto/digests/SkeinEngine.cs b/crypto/src/crypto/digests/SkeinEngine.cs
index 7e93138ac..cfedfadf3 100644 --- a/crypto/src/crypto/digests/SkeinEngine.cs +++ b/crypto/src/crypto/digests/SkeinEngine.cs
@@ -741,7 +741,7 @@ namespace Org.BouncyCastle.Crypto.Digests CheckInitialised(); if (outBytes.Length < (outOff + outputSizeBytes)) { - throw new DataLengthException("Output buffer is too short to hold output of " + outputSizeBytes + " bytes"); + throw new DataLengthException("Output buffer is too short to hold output"); } // Finalise message block diff --git a/crypto/src/crypto/ec/CustomNamedCurves.cs b/crypto/src/crypto/ec/CustomNamedCurves.cs
index 51bb1829a..8a0c50a47 100644 --- a/crypto/src/crypto/ec/CustomNamedCurves.cs +++ b/crypto/src/crypto/ec/CustomNamedCurves.cs
@@ -756,7 +756,7 @@ namespace Org.BouncyCastle.Crypto.EC private static void DefineCurve(string name, X9ECParametersHolder holder) { names.Add(name); - name = Platform.ToLowerInvariant(name); + name = Platform.ToUpperInvariant(name); nameToCurve.Add(name, holder); } @@ -765,7 +765,7 @@ namespace Org.BouncyCastle.Crypto.EC names.Add(name); oidToName.Add(oid, name); oidToCurve.Add(oid, holder); - name = Platform.ToLowerInvariant(name); + name = Platform.ToUpperInvariant(name); nameToOid.Add(name, oid); nameToCurve.Add(name, holder); } @@ -776,7 +776,7 @@ namespace Org.BouncyCastle.Crypto.EC if (curve == null) throw new InvalidOperationException(); - name = Platform.ToLowerInvariant(name); + name = Platform.ToUpperInvariant(name); nameToOid.Add(name, oid); nameToCurve.Add(name, curve); } @@ -841,7 +841,7 @@ namespace Org.BouncyCastle.Crypto.EC public static X9ECParameters GetByName(string name) { - X9ECParametersHolder holder = (X9ECParametersHolder)nameToCurve[Platform.ToLowerInvariant(name)]; + X9ECParametersHolder holder = (X9ECParametersHolder)nameToCurve[Platform.ToUpperInvariant(name)]; return holder == null ? null : holder.Parameters; } @@ -865,7 +865,7 @@ namespace Org.BouncyCastle.Crypto.EC */ public static DerObjectIdentifier GetOid(string name) { - return (DerObjectIdentifier)nameToOid[Platform.ToLowerInvariant(name)]; + return (DerObjectIdentifier)nameToOid[Platform.ToUpperInvariant(name)]; } /** diff --git a/crypto/src/crypto/encodings/OaepEncoding.cs b/crypto/src/crypto/encodings/OaepEncoding.cs
index a4d2f0e36..95814ef25 100644 --- a/crypto/src/crypto/encodings/OaepEncoding.cs +++ b/crypto/src/crypto/encodings/OaepEncoding.cs
@@ -161,7 +161,7 @@ namespace Org.BouncyCastle.Crypto.Encodings // // generate the seed. // - byte[] seed = random.GenerateSeed(defHash.Length); + byte[] seed = SecureRandom.GetNextBytes(random, defHash.Length); // // mask the message block. diff --git a/crypto/src/crypto/engines/AesEngine.cs b/crypto/src/crypto/engines/AesEngine.cs
index 164c43ee9..ba62af4da 100644 --- a/crypto/src/crypto/engines/AesEngine.cs +++ b/crypto/src/crypto/engines/AesEngine.cs
@@ -3,6 +3,7 @@ using System.Diagnostics; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -288,17 +289,14 @@ namespace Org.BouncyCastle.Crypto.Engines * AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits * This code is written assuming those are the only possible values */ - private uint[][] GenerateWorkingKey( - byte[] key, - bool forEncryption) + private uint[][] GenerateWorkingKey(byte[] key, bool forEncryption) { - int KC = key.Length / 4; // key length in words - int t; - - if ((KC != 4) && (KC != 6) && (KC != 8)) + int keyLen = key.Length; + if (keyLen < 16 || keyLen > 32 || (keyLen & 7) != 0) throw new ArgumentException("Key length not 128/192/256 bits."); - ROUNDS = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes + int KC = keyLen >> 2; + this.ROUNDS = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes uint[][] W = new uint[ROUNDS + 1][]; // 4 words in a block for (int i = 0; i <= ROUNDS; ++i) @@ -306,35 +304,109 @@ namespace Org.BouncyCastle.Crypto.Engines W[i] = new uint[4]; } - // - // copy the key into the round key array - // - - t = 0; - for (int i = 0; i < key.Length; t++) - { - W[t >> 2][t & 3] = Pack.LE_To_UInt32(key, i); - i+=4; - } - - // - // while not enough round key material calculated - // calculate new values - // - int k = (ROUNDS + 1) << 2; - for (int i = KC; (i < k); i++) + switch (KC) { - uint temp = W[(i-1)>>2][(i-1)&3]; - if ((i % KC) == 0) + case 4: { - temp = SubWord(Shift(temp, 8)) ^ rcon[(i / KC)-1]; - } - else if ((KC > 6) && ((i % KC) == 4)) + uint t0 = Pack.LE_To_UInt32(key, 0); W[0][0] = t0; + uint t1 = Pack.LE_To_UInt32(key, 4); W[0][1] = t1; + uint t2 = Pack.LE_To_UInt32(key, 8); W[0][2] = t2; + uint t3 = Pack.LE_To_UInt32(key, 12); W[0][3] = t3; + + for (int i = 1; i <= 10; ++i) + { + uint u = SubWord(Shift(t3, 8)) ^ rcon[i - 1]; + t0 ^= u; W[i][0] = t0; + t1 ^= t0; W[i][1] = t1; + t2 ^= t1; W[i][2] = t2; + t3 ^= t2; W[i][3] = t3; + } + + break; + } + case 6: { - temp = SubWord(temp); + uint t0 = Pack.LE_To_UInt32(key, 0); W[0][0] = t0; + uint t1 = Pack.LE_To_UInt32(key, 4); W[0][1] = t1; + uint t2 = Pack.LE_To_UInt32(key, 8); W[0][2] = t2; + uint t3 = Pack.LE_To_UInt32(key, 12); W[0][3] = t3; + uint t4 = Pack.LE_To_UInt32(key, 16); W[1][0] = t4; + uint t5 = Pack.LE_To_UInt32(key, 20); W[1][1] = t5; + + uint rcon = 1; + uint u = SubWord(Shift(t5, 8)) ^ rcon; rcon <<= 1; + t0 ^= u; W[1][2] = t0; + t1 ^= t0; W[1][3] = t1; + t2 ^= t1; W[2][0] = t2; + t3 ^= t2; W[2][1] = t3; + t4 ^= t3; W[2][2] = t4; + t5 ^= t4; W[2][3] = t5; + + for (int i = 3; i < 12; i += 3) + { + u = SubWord(Shift(t5, 8)) ^ rcon; rcon <<= 1; + t0 ^= u; W[i ][0] = t0; + t1 ^= t0; W[i ][1] = t1; + t2 ^= t1; W[i ][2] = t2; + t3 ^= t2; W[i ][3] = t3; + t4 ^= t3; W[i + 1][0] = t4; + t5 ^= t4; W[i + 1][1] = t5; + u = SubWord(Shift(t5, 8)) ^ rcon; rcon <<= 1; + t0 ^= u; W[i + 1][2] = t0; + t1 ^= t0; W[i + 1][3] = t1; + t2 ^= t1; W[i + 2][0] = t2; + t3 ^= t2; W[i + 2][1] = t3; + t4 ^= t3; W[i + 2][2] = t4; + t5 ^= t4; W[i + 2][3] = t5; + } + + u = SubWord(Shift(t5, 8)) ^ rcon; + t0 ^= u; W[12][0] = t0; + t1 ^= t0; W[12][1] = t1; + t2 ^= t1; W[12][2] = t2; + t3 ^= t2; W[12][3] = t3; + + break; } + case 8: + { + uint t0 = Pack.LE_To_UInt32(key, 0); W[0][0] = t0; + uint t1 = Pack.LE_To_UInt32(key, 4); W[0][1] = t1; + uint t2 = Pack.LE_To_UInt32(key, 8); W[0][2] = t2; + uint t3 = Pack.LE_To_UInt32(key, 12); W[0][3] = t3; + uint t4 = Pack.LE_To_UInt32(key, 16); W[1][0] = t4; + uint t5 = Pack.LE_To_UInt32(key, 20); W[1][1] = t5; + uint t6 = Pack.LE_To_UInt32(key, 24); W[1][2] = t6; + uint t7 = Pack.LE_To_UInt32(key, 28); W[1][3] = t7; + + uint u, rcon = 1; + + for (int i = 2; i < 14; i += 2) + { + u = SubWord(Shift(t7, 8)) ^ rcon; rcon <<= 1; + t0 ^= u; W[i ][0] = t0; + t1 ^= t0; W[i ][1] = t1; + t2 ^= t1; W[i ][2] = t2; + t3 ^= t2; W[i ][3] = t3; + u = SubWord(t3); + t4 ^= u; W[i + 1][0] = t4; + t5 ^= t4; W[i + 1][1] = t5; + t6 ^= t5; W[i + 1][2] = t6; + t7 ^= t6; W[i + 1][3] = t7; + } + + u = SubWord(Shift(t7, 8)) ^ rcon; + t0 ^= u; W[14][0] = t0; + t1 ^= t0; W[14][1] = t1; + t2 ^= t1; W[14][2] = t2; + t3 ^= t2; W[14][3] = t3; - W[i>>2][i&3] = W[(i - KC)>>2][(i-KC)&3] ^ temp; + break; + } + default: + { + throw new InvalidOperationException("Should never get here"); + } } if (!forEncryption) @@ -381,7 +453,8 @@ namespace Org.BouncyCastle.Crypto.Engines KeyParameter keyParameter = parameters as KeyParameter; if (keyParameter == null) - throw new ArgumentException("invalid parameter passed to AES init - " + parameters.GetType().Name); + throw new ArgumentException("invalid parameter passed to AES init - " + + Platform.GetTypeName(parameters)); WorkingKey = GenerateWorkingKey(keyParameter.GetKey(), forEncryption); diff --git a/crypto/src/crypto/engines/AesFastEngine.cs b/crypto/src/crypto/engines/AesFastEngine.cs
index 38ce1a946..3a9c3a89e 100644 --- a/crypto/src/crypto/engines/AesFastEngine.cs +++ b/crypto/src/crypto/engines/AesFastEngine.cs
@@ -3,6 +3,7 @@ using System.Diagnostics; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -624,16 +625,14 @@ namespace Org.BouncyCastle.Crypto.Engines * AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits * This code is written assuming those are the only possible values */ - private uint[][] GenerateWorkingKey( - byte[] key, - bool forEncryption) + private uint[][] GenerateWorkingKey(byte[] key, bool forEncryption) { - int KC = key.Length / 4; // key length in words - - if (((KC != 4) && (KC != 6) && (KC != 8)) || ((KC * 4) != key.Length)) + int keyLen = key.Length; + if (keyLen < 16 || keyLen > 32 || (keyLen & 7) != 0) throw new ArgumentException("Key length not 128/192/256 bits."); - ROUNDS = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes + int KC = keyLen >> 2; + this.ROUNDS = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes uint[][] W = new uint[ROUNDS + 1][]; // 4 words in a block for (int i = 0; i <= ROUNDS; ++i) @@ -641,32 +640,109 @@ namespace Org.BouncyCastle.Crypto.Engines W[i] = new uint[4]; } - // - // copy the key into the round key array - // - - int t = 0; - for (int i = 0; i < key.Length; t++) + switch (KC) + { + case 4: { - W[t >> 2][t & 3] = Pack.LE_To_UInt32(key, i); - i+=4; + uint t0 = Pack.LE_To_UInt32(key, 0); W[0][0] = t0; + uint t1 = Pack.LE_To_UInt32(key, 4); W[0][1] = t1; + uint t2 = Pack.LE_To_UInt32(key, 8); W[0][2] = t2; + uint t3 = Pack.LE_To_UInt32(key, 12); W[0][3] = t3; + + for (int i = 1; i <= 10; ++i) + { + uint u = SubWord(Shift(t3, 8)) ^ rcon[i - 1]; + t0 ^= u; W[i][0] = t0; + t1 ^= t0; W[i][1] = t1; + t2 ^= t1; W[i][2] = t2; + t3 ^= t2; W[i][3] = t3; + } + + break; } + case 6: + { + uint t0 = Pack.LE_To_UInt32(key, 0); W[0][0] = t0; + uint t1 = Pack.LE_To_UInt32(key, 4); W[0][1] = t1; + uint t2 = Pack.LE_To_UInt32(key, 8); W[0][2] = t2; + uint t3 = Pack.LE_To_UInt32(key, 12); W[0][3] = t3; + uint t4 = Pack.LE_To_UInt32(key, 16); W[1][0] = t4; + uint t5 = Pack.LE_To_UInt32(key, 20); W[1][1] = t5; + + uint rcon = 1; + uint u = SubWord(Shift(t5, 8)) ^ rcon; rcon <<= 1; + t0 ^= u; W[1][2] = t0; + t1 ^= t0; W[1][3] = t1; + t2 ^= t1; W[2][0] = t2; + t3 ^= t2; W[2][1] = t3; + t4 ^= t3; W[2][2] = t4; + t5 ^= t4; W[2][3] = t5; + + for (int i = 3; i < 12; i += 3) + { + u = SubWord(Shift(t5, 8)) ^ rcon; rcon <<= 1; + t0 ^= u; W[i ][0] = t0; + t1 ^= t0; W[i ][1] = t1; + t2 ^= t1; W[i ][2] = t2; + t3 ^= t2; W[i ][3] = t3; + t4 ^= t3; W[i + 1][0] = t4; + t5 ^= t4; W[i + 1][1] = t5; + u = SubWord(Shift(t5, 8)) ^ rcon; rcon <<= 1; + t0 ^= u; W[i + 1][2] = t0; + t1 ^= t0; W[i + 1][3] = t1; + t2 ^= t1; W[i + 2][0] = t2; + t3 ^= t2; W[i + 2][1] = t3; + t4 ^= t3; W[i + 2][2] = t4; + t5 ^= t4; W[i + 2][3] = t5; + } + + u = SubWord(Shift(t5, 8)) ^ rcon; + t0 ^= u; W[12][0] = t0; + t1 ^= t0; W[12][1] = t1; + t2 ^= t1; W[12][2] = t2; + t3 ^= t2; W[12][3] = t3; - // - // while not enough round key material calculated - // calculate new values - // - int k = (ROUNDS + 1) << 2; - for (int i = KC; (i < k); i++) + break; + } + case 8: { - uint temp = W[(i-1)>>2][(i-1)&3]; - if ((i % KC) == 0) { - temp = SubWord(Shift(temp, 8)) ^ rcon[(i / KC)-1]; - } else if ((KC > 6) && ((i % KC) == 4)) { - temp = SubWord(temp); + uint t0 = Pack.LE_To_UInt32(key, 0); W[0][0] = t0; + uint t1 = Pack.LE_To_UInt32(key, 4); W[0][1] = t1; + uint t2 = Pack.LE_To_UInt32(key, 8); W[0][2] = t2; + uint t3 = Pack.LE_To_UInt32(key, 12); W[0][3] = t3; + uint t4 = Pack.LE_To_UInt32(key, 16); W[1][0] = t4; + uint t5 = Pack.LE_To_UInt32(key, 20); W[1][1] = t5; + uint t6 = Pack.LE_To_UInt32(key, 24); W[1][2] = t6; + uint t7 = Pack.LE_To_UInt32(key, 28); W[1][3] = t7; + + uint u, rcon = 1; + + for (int i = 2; i < 14; i += 2) + { + u = SubWord(Shift(t7, 8)) ^ rcon; rcon <<= 1; + t0 ^= u; W[i ][0] = t0; + t1 ^= t0; W[i ][1] = t1; + t2 ^= t1; W[i ][2] = t2; + t3 ^= t2; W[i ][3] = t3; + u = SubWord(t3); + t4 ^= u; W[i + 1][0] = t4; + t5 ^= t4; W[i + 1][1] = t5; + t6 ^= t5; W[i + 1][2] = t6; + t7 ^= t6; W[i + 1][3] = t7; } - W[i>>2][i&3] = W[(i - KC)>>2][(i-KC)&3] ^ temp; + u = SubWord(Shift(t7, 8)) ^ rcon; + t0 ^= u; W[14][0] = t0; + t1 ^= t0; W[14][1] = t1; + t2 ^= t1; W[14][2] = t2; + t3 ^= t2; W[14][3] = t3; + + break; + } + default: + { + throw new InvalidOperationException("Should never get here"); + } } if (!forEncryption) @@ -713,7 +789,8 @@ namespace Org.BouncyCastle.Crypto.Engines KeyParameter keyParameter = parameters as KeyParameter; if (keyParameter == null) - throw new ArgumentException("invalid parameter passed to AES init - " + parameters.GetType().Name); + throw new ArgumentException("invalid parameter passed to AES init - " + + Platform.GetTypeName(parameters)); WorkingKey = GenerateWorkingKey(keyParameter.GetKey(), forEncryption); diff --git a/crypto/src/crypto/engines/AesLightEngine.cs b/crypto/src/crypto/engines/AesLightEngine.cs
index a42b34971..9cc9c34a0 100644 --- a/crypto/src/crypto/engines/AesLightEngine.cs +++ b/crypto/src/crypto/engines/AesLightEngine.cs
@@ -3,6 +3,7 @@ using System.Diagnostics; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -185,17 +186,14 @@ namespace Org.BouncyCastle.Crypto.Engines * AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits * This code is written assuming those are the only possible values */ - private uint[][] GenerateWorkingKey( - byte[] key, - bool forEncryption) + private uint[][] GenerateWorkingKey(byte[] key, bool forEncryption) { - int KC = key.Length / 4; // key length in words - int t; - - if ((KC != 4) && (KC != 6) && (KC != 8)) + int keyLen = key.Length; + if (keyLen < 16 || keyLen > 32 || (keyLen & 7) != 0) throw new ArgumentException("Key length not 128/192/256 bits."); - ROUNDS = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes + int KC = keyLen >> 2; + this.ROUNDS = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes uint[][] W = new uint[ROUNDS + 1][]; // 4 words in a block for (int i = 0; i <= ROUNDS; ++i) @@ -203,40 +201,114 @@ namespace Org.BouncyCastle.Crypto.Engines W[i] = new uint[4]; } - // - // copy the key into the round key array - // - - t = 0; - for (int i = 0; i < key.Length; t++) - { - W[t >> 2][t & 3] = Pack.LE_To_UInt32(key, i); - i+=4; - } - - // - // while not enough round key material calculated - // calculate new values - // - int k = (ROUNDS + 1) << 2; - for (int i = KC; (i < k); i++) + switch (KC) { - uint temp = W[(i-1)>>2][(i-1)&3]; - if ((i % KC) == 0) + case 4: { - temp = SubWord(Shift(temp, 8)) ^ rcon[(i / KC)-1]; - } - else if ((KC > 6) && ((i % KC) == 4)) + uint t0 = Pack.LE_To_UInt32(key, 0); W[0][0] = t0; + uint t1 = Pack.LE_To_UInt32(key, 4); W[0][1] = t1; + uint t2 = Pack.LE_To_UInt32(key, 8); W[0][2] = t2; + uint t3 = Pack.LE_To_UInt32(key, 12); W[0][3] = t3; + + for (int i = 1; i <= 10; ++i) + { + uint u = SubWord(Shift(t3, 8)) ^ rcon[i - 1]; + t0 ^= u; W[i][0] = t0; + t1 ^= t0; W[i][1] = t1; + t2 ^= t1; W[i][2] = t2; + t3 ^= t2; W[i][3] = t3; + } + + break; + } + case 6: { - temp = SubWord(temp); + uint t0 = Pack.LE_To_UInt32(key, 0); W[0][0] = t0; + uint t1 = Pack.LE_To_UInt32(key, 4); W[0][1] = t1; + uint t2 = Pack.LE_To_UInt32(key, 8); W[0][2] = t2; + uint t3 = Pack.LE_To_UInt32(key, 12); W[0][3] = t3; + uint t4 = Pack.LE_To_UInt32(key, 16); W[1][0] = t4; + uint t5 = Pack.LE_To_UInt32(key, 20); W[1][1] = t5; + + uint rcon = 1; + uint u = SubWord(Shift(t5, 8)) ^ rcon; rcon <<= 1; + t0 ^= u; W[1][2] = t0; + t1 ^= t0; W[1][3] = t1; + t2 ^= t1; W[2][0] = t2; + t3 ^= t2; W[2][1] = t3; + t4 ^= t3; W[2][2] = t4; + t5 ^= t4; W[2][3] = t5; + + for (int i = 3; i < 12; i += 3) + { + u = SubWord(Shift(t5, 8)) ^ rcon; rcon <<= 1; + t0 ^= u; W[i ][0] = t0; + t1 ^= t0; W[i ][1] = t1; + t2 ^= t1; W[i ][2] = t2; + t3 ^= t2; W[i ][3] = t3; + t4 ^= t3; W[i + 1][0] = t4; + t5 ^= t4; W[i + 1][1] = t5; + u = SubWord(Shift(t5, 8)) ^ rcon; rcon <<= 1; + t0 ^= u; W[i + 1][2] = t0; + t1 ^= t0; W[i + 1][3] = t1; + t2 ^= t1; W[i + 2][0] = t2; + t3 ^= t2; W[i + 2][1] = t3; + t4 ^= t3; W[i + 2][2] = t4; + t5 ^= t4; W[i + 2][3] = t5; + } + + u = SubWord(Shift(t5, 8)) ^ rcon; + t0 ^= u; W[12][0] = t0; + t1 ^= t0; W[12][1] = t1; + t2 ^= t1; W[12][2] = t2; + t3 ^= t2; W[12][3] = t3; + + break; } + case 8: + { + uint t0 = Pack.LE_To_UInt32(key, 0); W[0][0] = t0; + uint t1 = Pack.LE_To_UInt32(key, 4); W[0][1] = t1; + uint t2 = Pack.LE_To_UInt32(key, 8); W[0][2] = t2; + uint t3 = Pack.LE_To_UInt32(key, 12); W[0][3] = t3; + uint t4 = Pack.LE_To_UInt32(key, 16); W[1][0] = t4; + uint t5 = Pack.LE_To_UInt32(key, 20); W[1][1] = t5; + uint t6 = Pack.LE_To_UInt32(key, 24); W[1][2] = t6; + uint t7 = Pack.LE_To_UInt32(key, 28); W[1][3] = t7; + + uint u, rcon = 1; + + for (int i = 2; i < 14; i += 2) + { + u = SubWord(Shift(t7, 8)) ^ rcon; rcon <<= 1; + t0 ^= u; W[i ][0] = t0; + t1 ^= t0; W[i ][1] = t1; + t2 ^= t1; W[i ][2] = t2; + t3 ^= t2; W[i ][3] = t3; + u = SubWord(t3); + t4 ^= u; W[i + 1][0] = t4; + t5 ^= t4; W[i + 1][1] = t5; + t6 ^= t5; W[i + 1][2] = t6; + t7 ^= t6; W[i + 1][3] = t7; + } + + u = SubWord(Shift(t7, 8)) ^ rcon; + t0 ^= u; W[14][0] = t0; + t1 ^= t0; W[14][1] = t1; + t2 ^= t1; W[14][2] = t2; + t3 ^= t2; W[14][3] = t3; - W[i>>2][i&3] = W[(i - KC)>>2][(i-KC)&3] ^ temp; + break; + } + default: + { + throw new InvalidOperationException("Should never get here"); + } } - if (!forEncryption) + if (!forEncryption) { - for (int j = 1; j < ROUNDS; j++) + for (int j = 1; j < ROUNDS; j++) { uint[] w = W[j]; for (int i = 0; i < 4; i++) @@ -278,7 +350,8 @@ namespace Org.BouncyCastle.Crypto.Engines KeyParameter keyParameter = parameters as KeyParameter; if (keyParameter == null) - throw new ArgumentException("invalid parameter passed to AES init - " + parameters.GetType().Name); + throw new ArgumentException("invalid parameter passed to AES init - " + + Platform.GetTypeName(parameters)); WorkingKey = GenerateWorkingKey(keyParameter.GetKey(), forEncryption); diff --git a/crypto/src/crypto/engines/BlowfishEngine.cs b/crypto/src/crypto/engines/BlowfishEngine.cs
index 7b50e832f..e38f4e8f6 100644 --- a/crypto/src/crypto/engines/BlowfishEngine.cs +++ b/crypto/src/crypto/engines/BlowfishEngine.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -329,7 +330,7 @@ namespace Org.BouncyCastle.Crypto.Engines ICipherParameters parameters) { if (!(parameters is KeyParameter)) - throw new ArgumentException("invalid parameter passed to Blowfish init - " + parameters.GetType().ToString()); + throw new ArgumentException("invalid parameter passed to Blowfish init - " + Platform.GetTypeName(parameters)); this.encrypting = forEncryption; this.workingKey = ((KeyParameter)parameters).GetKey(); diff --git a/crypto/src/crypto/engines/Cast5Engine.cs b/crypto/src/crypto/engines/Cast5Engine.cs
index 1af30a335..53836db02 100644 --- a/crypto/src/crypto/engines/Cast5Engine.cs +++ b/crypto/src/crypto/engines/Cast5Engine.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -334,7 +335,7 @@ namespace Org.BouncyCastle.Crypto.Engines ICipherParameters parameters) { if (!(parameters is KeyParameter)) - throw new ArgumentException("Invalid parameter passed to "+ AlgorithmName +" init - " + parameters.GetType().ToString()); + throw new ArgumentException("Invalid parameter passed to "+ AlgorithmName +" init - " + Platform.GetTypeName(parameters)); _encrypting = forEncryption; _workingKey = ((KeyParameter)parameters).GetKey(); diff --git a/crypto/src/crypto/engines/DesEdeEngine.cs b/crypto/src/crypto/engines/DesEdeEngine.cs
index bc40b56a8..2fac24ac0 100644 --- a/crypto/src/crypto/engines/DesEdeEngine.cs +++ b/crypto/src/crypto/engines/DesEdeEngine.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -24,7 +25,7 @@ namespace Org.BouncyCastle.Crypto.Engines ICipherParameters parameters) { if (!(parameters is KeyParameter)) - throw new ArgumentException("invalid parameter passed to DESede init - " + parameters.GetType().ToString()); + throw new ArgumentException("invalid parameter passed to DESede init - " + Platform.GetTypeName(parameters)); byte[] keyMaster = ((KeyParameter)parameters).GetKey(); if (keyMaster.Length != 24 && keyMaster.Length != 16) diff --git a/crypto/src/crypto/engines/DesEngine.cs b/crypto/src/crypto/engines/DesEngine.cs
index a6d580bb6..cfd50681e 100644 --- a/crypto/src/crypto/engines/DesEngine.cs +++ b/crypto/src/crypto/engines/DesEngine.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -31,7 +32,7 @@ namespace Org.BouncyCastle.Crypto.Engines ICipherParameters parameters) { if (!(parameters is KeyParameter)) - throw new ArgumentException("invalid parameter passed to DES init - " + parameters.GetType().ToString()); + throw new ArgumentException("invalid parameter passed to DES init - " + Platform.GetTypeName(parameters)); workingKey = GenerateWorkingKey(forEncryption, ((KeyParameter)parameters).GetKey()); } diff --git a/crypto/src/crypto/engines/GOST28147Engine.cs b/crypto/src/crypto/engines/GOST28147Engine.cs
index e37ddaefd..71e6d9e44 100644 --- a/crypto/src/crypto/engines/GOST28147Engine.cs +++ b/crypto/src/crypto/engines/GOST28147Engine.cs
@@ -183,7 +183,8 @@ namespace Org.BouncyCastle.Crypto.Engines } else if (parameters != null) { - throw new ArgumentException("invalid parameter passed to Gost28147 init - " + parameters.GetType().Name); + throw new ArgumentException("invalid parameter passed to Gost28147 init - " + + Platform.GetTypeName(parameters)); } } diff --git a/crypto/src/crypto/engines/HC128Engine.cs b/crypto/src/crypto/engines/HC128Engine.cs
index 40c7a4e17..7bd1a48ed 100644 --- a/crypto/src/crypto/engines/HC128Engine.cs +++ b/crypto/src/crypto/engines/HC128Engine.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -180,7 +181,7 @@ namespace Org.BouncyCastle.Crypto.Engines else { throw new ArgumentException( - "Invalid parameter passed to HC128 init - " + parameters.GetType().Name, + "Invalid parameter passed to HC128 init - " + Platform.GetTypeName(parameters), "parameters"); } diff --git a/crypto/src/crypto/engines/HC256Engine.cs b/crypto/src/crypto/engines/HC256Engine.cs
index 6eb360711..b72258a19 100644 --- a/crypto/src/crypto/engines/HC256Engine.cs +++ b/crypto/src/crypto/engines/HC256Engine.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -164,7 +165,7 @@ namespace Org.BouncyCastle.Crypto.Engines else { throw new ArgumentException( - "Invalid parameter passed to HC256 init - " + parameters.GetType().Name, + "Invalid parameter passed to HC256 init - " + Platform.GetTypeName(parameters), "parameters"); } diff --git a/crypto/src/crypto/engines/ISAACEngine.cs b/crypto/src/crypto/engines/ISAACEngine.cs
index f25577130..b94ee6ed9 100644 --- a/crypto/src/crypto/engines/ISAACEngine.cs +++ b/crypto/src/crypto/engines/ISAACEngine.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -41,7 +42,7 @@ namespace Org.BouncyCastle.Crypto.Engines { if (!(parameters is KeyParameter)) throw new ArgumentException( - "invalid parameter passed to ISAAC Init - " + parameters.GetType().Name, + "invalid parameter passed to ISAAC Init - " + Platform.GetTypeName(parameters), "parameters"); /* diff --git a/crypto/src/crypto/engines/IdeaEngine.cs b/crypto/src/crypto/engines/IdeaEngine.cs
index 4909510ac..18a151c93 100644 --- a/crypto/src/crypto/engines/IdeaEngine.cs +++ b/crypto/src/crypto/engines/IdeaEngine.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -52,7 +53,7 @@ namespace Org.BouncyCastle.Crypto.Engines ICipherParameters parameters) { if (!(parameters is KeyParameter)) - throw new ArgumentException("invalid parameter passed to IDEA init - " + parameters.GetType().ToString()); + throw new ArgumentException("invalid parameter passed to IDEA init - " + Platform.GetTypeName(parameters)); workingKey = GenerateWorkingKey(forEncryption, ((KeyParameter)parameters).GetKey()); diff --git a/crypto/src/crypto/engines/IesEngine.cs b/crypto/src/crypto/engines/IesEngine.cs
index a2004a9d6..307cc7a80 100644 --- a/crypto/src/crypto/engines/IesEngine.cs +++ b/crypto/src/crypto/engines/IesEngine.cs
@@ -97,6 +97,10 @@ namespace Org.BouncyCastle.Crypto.Engines kdf.Init(kParam); + // Ensure that the length of the input is greater than the MAC in bytes + if (inLen < mac.GetMacSize()) + throw new InvalidCipherTextException("Length of input must be greater than the MAC"); + inLen -= mac.GetMacSize(); if (cipher == null) // stream mode diff --git a/crypto/src/crypto/engines/NoekeonEngine.cs b/crypto/src/crypto/engines/NoekeonEngine.cs
index dd78a4ea5..f64be50ba 100644 --- a/crypto/src/crypto/engines/NoekeonEngine.cs +++ b/crypto/src/crypto/engines/NoekeonEngine.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -70,7 +71,8 @@ namespace Org.BouncyCastle.Crypto.Engines ICipherParameters parameters) { if (!(parameters is KeyParameter)) - throw new ArgumentException("Invalid parameters passed to Noekeon init - " + parameters.GetType().Name, "parameters"); + throw new ArgumentException("Invalid parameters passed to Noekeon init - " + + Platform.GetTypeName(parameters), "parameters"); _forEncryption = forEncryption; _initialised = true; diff --git a/crypto/src/crypto/engines/RC2Engine.cs b/crypto/src/crypto/engines/RC2Engine.cs
index b56953de5..4aca1894f 100644 --- a/crypto/src/crypto/engines/RC2Engine.cs +++ b/crypto/src/crypto/engines/RC2Engine.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -135,7 +136,7 @@ namespace Org.BouncyCastle.Crypto.Engines } else { - throw new ArgumentException("invalid parameter passed to RC2 init - " + parameters.GetType().Name); + throw new ArgumentException("invalid parameter passed to RC2 init - " + Platform.GetTypeName(parameters)); } } diff --git a/crypto/src/crypto/engines/RC4Engine.cs b/crypto/src/crypto/engines/RC4Engine.cs
index fd84b7d23..a515bb04e 100644 --- a/crypto/src/crypto/engines/RC4Engine.cs +++ b/crypto/src/crypto/engines/RC4Engine.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -44,7 +45,7 @@ namespace Org.BouncyCastle.Crypto.Engines return; } - throw new ArgumentException("invalid parameter passed to RC4 init - " + parameters.GetType().ToString()); + throw new ArgumentException("invalid parameter passed to RC4 init - " + Platform.GetTypeName(parameters)); } public virtual string AlgorithmName diff --git a/crypto/src/crypto/engines/RC532Engine.cs b/crypto/src/crypto/engines/RC532Engine.cs
index 169a60b98..d1c29e624 100644 --- a/crypto/src/crypto/engines/RC532Engine.cs +++ b/crypto/src/crypto/engines/RC532Engine.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -91,7 +92,7 @@ namespace Org.BouncyCastle.Crypto.Engines } else { - throw new ArgumentException("invalid parameter passed to RC532 init - " + parameters.GetType().ToString()); + throw new ArgumentException("invalid parameter passed to RC532 init - " + Platform.GetTypeName(parameters)); } this.forEncryption = forEncryption; diff --git a/crypto/src/crypto/engines/RC564Engine.cs b/crypto/src/crypto/engines/RC564Engine.cs
index ddcce0fa8..097fd60ba 100644 --- a/crypto/src/crypto/engines/RC564Engine.cs +++ b/crypto/src/crypto/engines/RC564Engine.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -80,7 +81,7 @@ namespace Org.BouncyCastle.Crypto.Engines { if (!(typeof(RC5Parameters).IsInstanceOfType(parameters))) { - throw new ArgumentException("invalid parameter passed to RC564 init - " + parameters.GetType().ToString()); + throw new ArgumentException("invalid parameter passed to RC564 init - " + Platform.GetTypeName(parameters)); } RC5Parameters p = (RC5Parameters)parameters; diff --git a/crypto/src/crypto/engines/RC6Engine.cs b/crypto/src/crypto/engines/RC6Engine.cs
index 196bd8394..9aeb1e7cb 100644 --- a/crypto/src/crypto/engines/RC6Engine.cs +++ b/crypto/src/crypto/engines/RC6Engine.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -76,7 +77,7 @@ namespace Org.BouncyCastle.Crypto.Engines ICipherParameters parameters) { if (!(parameters is KeyParameter)) - throw new ArgumentException("invalid parameter passed to RC6 init - " + parameters.GetType().ToString()); + throw new ArgumentException("invalid parameter passed to RC6 init - " + Platform.GetTypeName(parameters)); this.forEncryption = forEncryption; diff --git a/crypto/src/crypto/engines/RSACoreEngine.cs b/crypto/src/crypto/engines/RSACoreEngine.cs
index 38326371f..fd44e3cc1 100644 --- a/crypto/src/crypto/engines/RSACoreEngine.cs +++ b/crypto/src/crypto/engines/RSACoreEngine.cs
@@ -124,7 +124,7 @@ namespace Org.BouncyCastle.Crypto.Engines // RsaPrivateCrtKeyParameters crtKey = (RsaPrivateCrtKeyParameters)key; - BigInteger p = crtKey.P;; + BigInteger p = crtKey.P; BigInteger q = crtKey.Q; BigInteger dP = crtKey.DP; BigInteger dQ = crtKey.DQ; diff --git a/crypto/src/crypto/engines/RijndaelEngine.cs b/crypto/src/crypto/engines/RijndaelEngine.cs
index 80f522353..7025cb5dc 100644 --- a/crypto/src/crypto/engines/RijndaelEngine.cs +++ b/crypto/src/crypto/engines/RijndaelEngine.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -582,7 +583,7 @@ namespace Org.BouncyCastle.Crypto.Engines return; } - throw new ArgumentException("invalid parameter passed to Rijndael init - " + parameters.GetType().ToString()); + throw new ArgumentException("invalid parameter passed to Rijndael init - " + Platform.GetTypeName(parameters)); } public virtual string AlgorithmName diff --git a/crypto/src/crypto/engines/SerpentEngine.cs b/crypto/src/crypto/engines/SerpentEngine.cs
index 255c204ab..76799f045 100644 --- a/crypto/src/crypto/engines/SerpentEngine.cs +++ b/crypto/src/crypto/engines/SerpentEngine.cs
@@ -1,117 +1,32 @@ using System; using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Crypto.Utilities; namespace Org.BouncyCastle.Crypto.Engines { /** - * Serpent is a 128-bit 32-round block cipher with variable key lengths, - * including 128, 192 and 256 bit keys conjectured to be at least as - * secure as three-key triple-DES. - * <p> - * Serpent was designed by Ross Anderson, Eli Biham and Lars Knudsen as a - * candidate algorithm for the NIST AES Quest.> - * </p> - * <p> - * For full details see the <a href="http://www.cl.cam.ac.uk/~rja14/serpent.html">The Serpent home page</a> - * </p> + * Serpent is a 128-bit 32-round block cipher with variable key lengths, + * including 128, 192 and 256 bit keys conjectured to be at least as + * secure as three-key triple-DES. + * <p> + * Serpent was designed by Ross Anderson, Eli Biham and Lars Knudsen as a + * candidate algorithm for the NIST AES Quest. + * </p> + * <p> + * For full details see <a href="http://www.cl.cam.ac.uk/~rja14/serpent.html">The Serpent home page</a> + * </p> */ - public class SerpentEngine - : IBlockCipher + public sealed class SerpentEngine + : SerpentEngineBase { - private const int BLOCK_SIZE = 16; - - static readonly int ROUNDS = 32; - static readonly int PHI = unchecked((int)0x9E3779B9); // (Sqrt(5) - 1) * 2**31 - - private bool encrypting; - private int[] wKey; - - private int X0, X1, X2, X3; // registers - - /** - * initialise a Serpent cipher. - * - * @param forEncryption whether or not we are for encryption. - * @param parameters the parameters required to set up the cipher. - * @exception ArgumentException if the parameters argument is - * inappropriate. - */ - public virtual void Init( - bool forEncryption, - ICipherParameters parameters) - { - if (!(parameters is KeyParameter)) - throw new ArgumentException("invalid parameter passed to Serpent init - " + parameters.GetType().ToString()); - - this.encrypting = forEncryption; - this.wKey = MakeWorkingKey(((KeyParameter)parameters).GetKey()); - } - - public virtual string AlgorithmName - { - get { return "Serpent"; } - } - - public virtual bool IsPartialBlockOkay - { - get { return false; } - } - - public virtual int GetBlockSize() - { - return BLOCK_SIZE; - } - - /** - * Process one block of input from the array in and write it to - * the out array. - * - * @param in the array containing the input data. - * @param inOff offset into the in array the data starts at. - * @param out the array the output data will be copied into. - * @param outOff the offset into the out array the output will start at. - * @exception DataLengthException if there isn't enough data in in, or - * space in out. - * @exception InvalidOperationException if the cipher isn't initialised. - * @return the number of bytes processed and produced. - */ - public virtual int ProcessBlock( - byte[] input, - int inOff, - byte[] output, - int outOff) - { - if (wKey == null) - throw new InvalidOperationException("Serpent not initialised"); - - Check.DataLength(input, inOff, BLOCK_SIZE, "input buffer too short"); - Check.OutputLength(output, outOff, BLOCK_SIZE, "output buffer too short"); - - if (encrypting) - { - EncryptBlock(input, inOff, output, outOff); - } - else - { - DecryptBlock(input, inOff, output, outOff); - } - - return BLOCK_SIZE; - } - - public virtual void Reset() - { - } - /** * Expand a user-supplied key material into a session key. * * @param key The user-key bytes (multiples of 4) to use. * @exception ArgumentException */ - private int[] MakeWorkingKey( - byte[] key) + protected override int[] MakeWorkingKey(byte[] key) { // // pad key to 256 bits @@ -120,14 +35,14 @@ namespace Org.BouncyCastle.Crypto.Engines int off = 0; int length = 0; - for (off = key.Length - 4; off > 0; off -= 4) + for (off = 0; (off + 4) < key.Length; off += 4) { - kPad[length++] = BytesToWord(key, off); + kPad[length++] = (int)Pack.LE_To_UInt32(key, off); } - if (off == 0) + if (off % 4 == 0) { - kPad[length++] = BytesToWord(key, 0); + kPad[length++] = (int)Pack.LE_To_UInt32(key, off); if (length < 8) { kPad[length] = 1; @@ -235,57 +150,20 @@ namespace Org.BouncyCastle.Crypto.Engines return w; } - private int RotateLeft( - int x, - int bits) - { - return ((x << bits) | (int) ((uint)x >> (32 - bits))); - } - - private int RotateRight( - int x, - int bits) - { - return ( (int)((uint)x >> bits) | (x << (32 - bits))); - } - - private int BytesToWord( - byte[] src, - int srcOff) - { - return (((src[srcOff] & 0xff) << 24) | ((src[srcOff + 1] & 0xff) << 16) | - ((src[srcOff + 2] & 0xff) << 8) | ((src[srcOff + 3] & 0xff))); - } - - private void WordToBytes( - int word, - byte[] dst, - int dstOff) - { - dst[dstOff + 3] = (byte)(word); - dst[dstOff + 2] = (byte)((uint)word >> 8); - dst[dstOff + 1] = (byte)((uint)word >> 16); - dst[dstOff] = (byte)((uint)word >> 24); - } - /** * Encrypt one block of plaintext. * - * @param in the array containing the input data. + * @param input the array containing the input data. * @param inOff offset into the in array the data starts at. - * @param out the array the output data will be copied into. + * @param output the array the output data will be copied into. * @param outOff the offset into the out array the output will start at. */ - private void EncryptBlock( - byte[] input, - int inOff, - byte[] outBytes, - int outOff) + protected override void EncryptBlock(byte[] input, int inOff, byte[] output, int outOff) { - X3 = BytesToWord(input, inOff); - X2 = BytesToWord(input, inOff + 4); - X1 = BytesToWord(input, inOff + 8); - X0 = BytesToWord(input, inOff + 12); + X0 = (int)Pack.LE_To_UInt32(input, inOff); + X1 = (int)Pack.LE_To_UInt32(input, inOff + 4); + X2 = (int)Pack.LE_To_UInt32(input, inOff + 8); + X3 = (int)Pack.LE_To_UInt32(input, inOff + 12); Sb0(wKey[0] ^ X0, wKey[1] ^ X1, wKey[2] ^ X2, wKey[3] ^ X3); LT(); Sb1(wKey[4] ^ X0, wKey[5] ^ X1, wKey[6] ^ X2, wKey[7] ^ X3); LT(); @@ -320,30 +198,26 @@ namespace Org.BouncyCastle.Crypto.Engines Sb6(wKey[120] ^ X0, wKey[121] ^ X1, wKey[122] ^ X2, wKey[123] ^ X3); LT(); Sb7(wKey[124] ^ X0, wKey[125] ^ X1, wKey[126] ^ X2, wKey[127] ^ X3); - WordToBytes(wKey[131] ^ X3, outBytes, outOff); - WordToBytes(wKey[130] ^ X2, outBytes, outOff + 4); - WordToBytes(wKey[129] ^ X1, outBytes, outOff + 8); - WordToBytes(wKey[128] ^ X0, outBytes, outOff + 12); + Pack.UInt32_To_LE((uint)(wKey[128] ^ X0), output, outOff); + Pack.UInt32_To_LE((uint)(wKey[129] ^ X1), output, outOff + 4); + Pack.UInt32_To_LE((uint)(wKey[130] ^ X2), output, outOff + 8); + Pack.UInt32_To_LE((uint)(wKey[131] ^ X3), output, outOff + 12); } /** * Decrypt one block of ciphertext. * - * @param in the array containing the input data. + * @param input the array containing the input data. * @param inOff offset into the in array the data starts at. - * @param out the array the output data will be copied into. + * @param output the array the output data will be copied into. * @param outOff the offset into the out array the output will start at. */ - private void DecryptBlock( - byte[] input, - int inOff, - byte[] outBytes, - int outOff) + protected override void DecryptBlock(byte[] input, int inOff, byte[] output, int outOff) { - X3 = wKey[131] ^ BytesToWord(input, inOff); - X2 = wKey[130] ^ BytesToWord(input, inOff + 4); - X1 = wKey[129] ^ BytesToWord(input, inOff + 8); - X0 = wKey[128] ^ BytesToWord(input, inOff + 12); + X0 = wKey[128] ^ (int)Pack.LE_To_UInt32(input, inOff); + X1 = wKey[129] ^ (int)Pack.LE_To_UInt32(input, inOff + 4); + X2 = wKey[130] ^ (int)Pack.LE_To_UInt32(input, inOff + 8); + X3 = wKey[131] ^ (int)Pack.LE_To_UInt32(input, inOff + 12); Ib7(X0, X1, X2, X3); X0 ^= wKey[124]; X1 ^= wKey[125]; X2 ^= wKey[126]; X3 ^= wKey[127]; @@ -409,369 +283,10 @@ namespace Org.BouncyCastle.Crypto.Engines X0 ^= wKey[4]; X1 ^= wKey[5]; X2 ^= wKey[6]; X3 ^= wKey[7]; InverseLT(); Ib0(X0, X1, X2, X3); - WordToBytes(X3 ^ wKey[3], outBytes, outOff); - WordToBytes(X2 ^ wKey[2], outBytes, outOff + 4); - WordToBytes(X1 ^ wKey[1], outBytes, outOff + 8); - WordToBytes(X0 ^ wKey[0], outBytes, outOff + 12); - } - - /* - * The sboxes below are based on the work of Brian Gladman and - * Sam Simpson, whose original notice appears below. - * <p> - * For further details see: - * http://fp.gladman.plus.com/cryptography_technology/serpent/ - * </p> - */ - - /* Partially optimised Serpent S Box bool functions derived */ - /* using a recursive descent analyser but without a full search */ - /* of all subtrees. This set of S boxes is the result of work */ - /* by Sam Simpson and Brian Gladman using the spare time on a */ - /* cluster of high capacity servers to search for S boxes with */ - /* this customised search engine. There are now an average of */ - /* 15.375 terms per S box. */ - /* */ - /* Copyright: Dr B. R Gladman (gladman@seven77.demon.co.uk) */ - /* and Sam Simpson (s.simpson@mia.co.uk) */ - /* 17th December 1998 */ - /* */ - /* We hereby give permission for information in this file to be */ - /* used freely subject only to acknowledgement of its origin. */ - - /** - * S0 - { 3, 8,15, 1,10, 6, 5,11,14,13, 4, 2, 7, 0, 9,12 } - 15 terms. - */ - private void Sb0(int a, int b, int c, int d) - { - int t1 = a ^ d; - int t3 = c ^ t1; - int t4 = b ^ t3; - X3 = (a & d) ^ t4; - int t7 = a ^ (b & t1); - X2 = t4 ^ (c | t7); - int t12 = X3 & (t3 ^ t7); - X1 = (~t3) ^ t12; - X0 = t12 ^ (~t7); - } - - /** - * InvSO - {13, 3,11, 0,10, 6, 5,12, 1,14, 4, 7,15, 9, 8, 2 } - 15 terms. - */ - private void Ib0(int a, int b, int c, int d) - { - int t1 = ~a; - int t2 = a ^ b; - int t4 = d ^ (t1 | t2); - int t5 = c ^ t4; - X2 = t2 ^ t5; - int t8 = t1 ^ (d & t2); - X1 = t4 ^ (X2 & t8); - X3 = (a & t4) ^ (t5 | X1); - X0 = X3 ^ (t5 ^ t8); - } - - /** - * S1 - {15,12, 2, 7, 9, 0, 5,10, 1,11,14, 8, 6,13, 3, 4 } - 14 terms. - */ - private void Sb1(int a, int b, int c, int d) - { - int t2 = b ^ (~a); - int t5 = c ^ (a | t2); - X2 = d ^ t5; - int t7 = b ^ (d | t2); - int t8 = t2 ^ X2; - X3 = t8 ^ (t5 & t7); - int t11 = t5 ^ t7; - X1 = X3 ^ t11; - X0 = t5 ^ (t8 & t11); - } - - /** - * InvS1 - { 5, 8, 2,14,15, 6,12, 3,11, 4, 7, 9, 1,13,10, 0 } - 14 steps. - */ - private void Ib1(int a, int b, int c, int d) - { - int t1 = b ^ d; - int t3 = a ^ (b & t1); - int t4 = t1 ^ t3; - X3 = c ^ t4; - int t7 = b ^ (t1 & t3); - int t8 = X3 | t7; - X1 = t3 ^ t8; - int t10 = ~X1; - int t11 = X3 ^ t7; - X0 = t10 ^ t11; - X2 = t4 ^ (t10 | t11); - } - - /** - * S2 - { 8, 6, 7, 9, 3,12,10,15,13, 1,14, 4, 0,11, 5, 2 } - 16 terms. - */ - private void Sb2(int a, int b, int c, int d) - { - int t1 = ~a; - int t2 = b ^ d; - int t3 = c & t1; - X0 = t2 ^ t3; - int t5 = c ^ t1; - int t6 = c ^ X0; - int t7 = b & t6; - X3 = t5 ^ t7; - X2 = a ^ ((d | t7) & (X0 | t5)); - X1 = (t2 ^ X3) ^ (X2 ^ (d | t1)); - } - - /** - * InvS2 - {12, 9,15, 4,11,14, 1, 2, 0, 3, 6,13, 5, 8,10, 7 } - 16 steps. - */ - private void Ib2(int a, int b, int c, int d) - { - int t1 = b ^ d; - int t2 = ~t1; - int t3 = a ^ c; - int t4 = c ^ t1; - int t5 = b & t4; - X0 = t3 ^ t5; - int t7 = a | t2; - int t8 = d ^ t7; - int t9 = t3 | t8; - X3 = t1 ^ t9; - int t11 = ~t4; - int t12 = X0 | X3; - X1 = t11 ^ t12; - X2 = (d & t11) ^ (t3 ^ t12); - } - - /** - * S3 - { 0,15,11, 8,12, 9, 6, 3,13, 1, 2, 4,10, 7, 5,14 } - 16 terms. - */ - private void Sb3(int a, int b, int c, int d) - { - int t1 = a ^ b; - int t2 = a & c; - int t3 = a | d; - int t4 = c ^ d; - int t5 = t1 & t3; - int t6 = t2 | t5; - X2 = t4 ^ t6; - int t8 = b ^ t3; - int t9 = t6 ^ t8; - int t10 = t4 & t9; - X0 = t1 ^ t10; - int t12 = X2 & X0; - X1 = t9 ^ t12; - X3 = (b | d) ^ (t4 ^ t12); - } - - /** - * InvS3 - { 0, 9,10, 7,11,14, 6,13, 3, 5,12, 2, 4, 8,15, 1 } - 15 terms - */ - private void Ib3(int a, int b, int c, int d) - { - int t1 = a | b; - int t2 = b ^ c; - int t3 = b & t2; - int t4 = a ^ t3; - int t5 = c ^ t4; - int t6 = d | t4; - X0 = t2 ^ t6; - int t8 = t2 | t6; - int t9 = d ^ t8; - X2 = t5 ^ t9; - int t11 = t1 ^ t9; - int t12 = X0 & t11; - X3 = t4 ^ t12; - X1 = X3 ^ (X0 ^ t11); - } - - /** - * S4 - { 1,15, 8, 3,12, 0,11, 6, 2, 5, 4,10, 9,14, 7,13 } - 15 terms. - */ - private void Sb4(int a, int b, int c, int d) - { - int t1 = a ^ d; - int t2 = d & t1; - int t3 = c ^ t2; - int t4 = b | t3; - X3 = t1 ^ t4; - int t6 = ~b; - int t7 = t1 | t6; - X0 = t3 ^ t7; - int t9 = a & X0; - int t10 = t1 ^ t6; - int t11 = t4 & t10; - X2 = t9 ^ t11; - X1 = (a ^ t3) ^ (t10 & X2); - } - - /** - * InvS4 - { 5, 0, 8, 3,10, 9, 7,14, 2,12,11, 6, 4,15,13, 1 } - 15 terms. - */ - private void Ib4(int a, int b, int c, int d) - { - int t1 = c | d; - int t2 = a & t1; - int t3 = b ^ t2; - int t4 = a & t3; - int t5 = c ^ t4; - X1 = d ^ t5; - int t7 = ~a; - int t8 = t5 & X1; - X3 = t3 ^ t8; - int t10 = X1 | t7; - int t11 = d ^ t10; - X0 = X3 ^ t11; - X2 = (t3 & t11) ^ (X1 ^ t7); - } - - /** - * S5 - {15, 5, 2,11, 4,10, 9,12, 0, 3,14, 8,13, 6, 7, 1 } - 16 terms. - */ - private void Sb5(int a, int b, int c, int d) - { - int t1 = ~a; - int t2 = a ^ b; - int t3 = a ^ d; - int t4 = c ^ t1; - int t5 = t2 | t3; - X0 = t4 ^ t5; - int t7 = d & X0; - int t8 = t2 ^ X0; - X1 = t7 ^ t8; - int t10 = t1 | X0; - int t11 = t2 | t7; - int t12 = t3 ^ t10; - X2 = t11 ^ t12; - X3 = (b ^ t7) ^ (X1 & t12); - } - - /** - * InvS5 - { 8,15, 2, 9, 4, 1,13,14,11, 6, 5, 3, 7,12,10, 0 } - 16 terms. - */ - private void Ib5(int a, int b, int c, int d) - { - int t1 = ~c; - int t2 = b & t1; - int t3 = d ^ t2; - int t4 = a & t3; - int t5 = b ^ t1; - X3 = t4 ^ t5; - int t7 = b | X3; - int t8 = a & t7; - X1 = t3 ^ t8; - int t10 = a | d; - int t11 = t1 ^ t7; - X0 = t10 ^ t11; - X2 = (b & t10) ^ (t4 | (a ^ c)); - } - - /** - * S6 - { 7, 2,12, 5, 8, 4, 6,11,14, 9, 1,15,13, 3,10, 0 } - 15 terms. - */ - private void Sb6(int a, int b, int c, int d) - { - int t1 = ~a; - int t2 = a ^ d; - int t3 = b ^ t2; - int t4 = t1 | t2; - int t5 = c ^ t4; - X1 = b ^ t5; - int t7 = t2 | X1; - int t8 = d ^ t7; - int t9 = t5 & t8; - X2 = t3 ^ t9; - int t11 = t5 ^ t8; - X0 = X2 ^ t11; - X3 = (~t5) ^ (t3 & t11); - } - - /** - * InvS6 - {15,10, 1,13, 5, 3, 6, 0, 4, 9,14, 7, 2,12, 8,11 } - 15 terms. - */ - private void Ib6(int a, int b, int c, int d) - { - int t1 = ~a; - int t2 = a ^ b; - int t3 = c ^ t2; - int t4 = c | t1; - int t5 = d ^ t4; - X1 = t3 ^ t5; - int t7 = t3 & t5; - int t8 = t2 ^ t7; - int t9 = b | t8; - X3 = t5 ^ t9; - int t11 = b | X3; - X0 = t8 ^ t11; - X2 = (d & t1) ^ (t3 ^ t11); - } - - /** - * S7 - { 1,13,15, 0,14, 8, 2,11, 7, 4,12,10, 9, 3, 5, 6 } - 16 terms. - */ - private void Sb7(int a, int b, int c, int d) - { - int t1 = b ^ c; - int t2 = c & t1; - int t3 = d ^ t2; - int t4 = a ^ t3; - int t5 = d | t1; - int t6 = t4 & t5; - X1 = b ^ t6; - int t8 = t3 | X1; - int t9 = a & t4; - X3 = t1 ^ t9; - int t11 = t4 ^ t8; - int t12 = X3 & t11; - X2 = t3 ^ t12; - X0 = (~t11) ^ (X3 & X2); - } - - /** - * InvS7 - { 3, 0, 6,13, 9,14,15, 8, 5,12,11, 7,10, 1, 4, 2 } - 17 terms. - */ - private void Ib7(int a, int b, int c, int d) - { - int t3 = c | (a & b); - int t4 = d & (a | b); - X3 = t3 ^ t4; - int t6 = ~d; - int t7 = b ^ t4; - int t9 = t7 | (X3 ^ t6); - X1 = a ^ t9; - X0 = (c ^ t7) ^ (d | X1); - X2 = (t3 ^ X1) ^ (X0 ^ (a & X3)); - } - - /** - * Apply the linear transformation to the register set. - */ - private void LT() - { - int x0 = RotateLeft(X0, 13); - int x2 = RotateLeft(X2, 3); - int x1 = X1 ^ x0 ^ x2 ; - int x3 = X3 ^ x2 ^ x0 << 3; - - X1 = RotateLeft(x1, 1); - X3 = RotateLeft(x3, 7); - X0 = RotateLeft(x0 ^ X1 ^ X3, 5); - X2 = RotateLeft(x2 ^ X3 ^ (X1 << 7), 22); - } - - /** - * Apply the inverse of the linear transformation to the register set. - */ - private void InverseLT() - { - int x2 = RotateRight(X2, 22) ^ X3 ^ (X1 << 7); - int x0 = RotateRight(X0, 5) ^ X1 ^ X3; - int x3 = RotateRight(X3, 7); - int x1 = RotateRight(X1, 1); - X3 = x3 ^ x2 ^ x0 << 3; - X1 = x1 ^ x0 ^ x2; - X2 = RotateRight(x2, 3); - X0 = RotateRight(x0, 13); + Pack.UInt32_To_LE((uint)(X0 ^ wKey[0]), output, outOff); + Pack.UInt32_To_LE((uint)(X1 ^ wKey[1]), output, outOff + 4); + Pack.UInt32_To_LE((uint)(X2 ^ wKey[2]), output, outOff + 8); + Pack.UInt32_To_LE((uint)(X3 ^ wKey[3]), output, outOff + 12); } } } diff --git a/crypto/src/crypto/engines/SerpentEngineBase.cs b/crypto/src/crypto/engines/SerpentEngineBase.cs new file mode 100644
index 000000000..a5d91b3be --- /dev/null +++ b/crypto/src/crypto/engines/SerpentEngineBase.cs
@@ -0,0 +1,468 @@ +using System; + +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Utilities; + +namespace Org.BouncyCastle.Crypto.Engines +{ + public abstract class SerpentEngineBase + : IBlockCipher + { + protected static readonly int BlockSize = 16; + + internal const int ROUNDS = 32; + internal const int PHI = unchecked((int)0x9E3779B9); // (sqrt(5) - 1) * 2**31 + + protected bool encrypting; + protected int[] wKey; + + protected int X0, X1, X2, X3; // registers + + protected SerpentEngineBase() + { + } + + /** + * initialise a Serpent cipher. + * + * @param encrypting whether or not we are for encryption. + * @param params the parameters required to set up the cipher. + * @throws IllegalArgumentException if the params argument is + * inappropriate. + */ + public virtual void Init(bool encrypting, ICipherParameters parameters) + { + if (!(parameters is KeyParameter)) + throw new ArgumentException("invalid parameter passed to " + AlgorithmName + " init - " + Platform.GetTypeName(parameters)); + + this.encrypting = encrypting; + this.wKey = MakeWorkingKey(((KeyParameter)parameters).GetKey()); + } + + public virtual string AlgorithmName + { + get { return "Serpent"; } + } + + public virtual bool IsPartialBlockOkay + { + get { return false; } + } + + public virtual int GetBlockSize() + { + return BlockSize; + } + + /** + * Process one block of input from the array in and write it to + * the out array. + * + * @param in the array containing the input data. + * @param inOff offset into the in array the data starts at. + * @param out the array the output data will be copied into. + * @param outOff the offset into the out array the output will start at. + * @return the number of bytes processed and produced. + * @throws DataLengthException if there isn't enough data in in, or + * space in out. + * @throws IllegalStateException if the cipher isn't initialised. + */ + public int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) + { + if (wKey == null) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + + Check.DataLength(input, inOff, BlockSize, "input buffer too short"); + Check.OutputLength(output, outOff, BlockSize, "output buffer too short"); + + if (encrypting) + { + EncryptBlock(input, inOff, output, outOff); + } + else + { + DecryptBlock(input, inOff, output, outOff); + } + + return BlockSize; + } + + public virtual void Reset() + { + } + + protected static int RotateLeft(int x, int bits) + { + return ((x << bits) | (int) ((uint)x >> (32 - bits))); + } + + private static int RotateRight(int x, int bits) + { + return ( (int)((uint)x >> bits) | (x << (32 - bits))); + } + + /** + * The sboxes below are based on the work of Brian Gladman and + * Sam Simpson, whose original notice appears below. + * <p> + * For further details see: + * http://fp.gladman.plus.com/cryptography_technology/serpent/ + */ + + /* Partially optimised Serpent S Box boolean functions derived */ + /* using a recursive descent analyser but without a full search */ + /* of all subtrees. This set of S boxes is the result of work */ + /* by Sam Simpson and Brian Gladman using the spare time on a */ + /* cluster of high capacity servers to search for S boxes with */ + /* this customised search engine. There are now an average of */ + /* 15.375 terms per S box. */ + /* */ + /* Copyright: Dr B. R Gladman (gladman@seven77.demon.co.uk) */ + /* and Sam Simpson (s.simpson@mia.co.uk) */ + /* 17th December 1998 */ + /* */ + /* We hereby give permission for information in this file to be */ + /* used freely subject only to acknowledgement of its origin. */ + + /** + * S0 - { 3, 8,15, 1,10, 6, 5,11,14,13, 4, 2, 7, 0, 9,12 } - 15 terms. + */ + protected void Sb0(int a, int b, int c, int d) + { + int t1 = a ^ d; + int t3 = c ^ t1; + int t4 = b ^ t3; + X3 = (a & d) ^ t4; + int t7 = a ^ (b & t1); + X2 = t4 ^ (c | t7); + int t12 = X3 & (t3 ^ t7); + X1 = (~t3) ^ t12; + X0 = t12 ^ (~t7); + } + + /** + * InvSO - {13, 3,11, 0,10, 6, 5,12, 1,14, 4, 7,15, 9, 8, 2 } - 15 terms. + */ + protected void Ib0(int a, int b, int c, int d) + { + int t1 = ~a; + int t2 = a ^ b; + int t4 = d ^ (t1 | t2); + int t5 = c ^ t4; + X2 = t2 ^ t5; + int t8 = t1 ^ (d & t2); + X1 = t4 ^ (X2 & t8); + X3 = (a & t4) ^ (t5 | X1); + X0 = X3 ^ (t5 ^ t8); + } + + /** + * S1 - {15,12, 2, 7, 9, 0, 5,10, 1,11,14, 8, 6,13, 3, 4 } - 14 terms. + */ + protected void Sb1(int a, int b, int c, int d) + { + int t2 = b ^ (~a); + int t5 = c ^ (a | t2); + X2 = d ^ t5; + int t7 = b ^ (d | t2); + int t8 = t2 ^ X2; + X3 = t8 ^ (t5 & t7); + int t11 = t5 ^ t7; + X1 = X3 ^ t11; + X0 = t5 ^ (t8 & t11); + } + + /** + * InvS1 - { 5, 8, 2,14,15, 6,12, 3,11, 4, 7, 9, 1,13,10, 0 } - 14 steps. + */ + protected void Ib1(int a, int b, int c, int d) + { + int t1 = b ^ d; + int t3 = a ^ (b & t1); + int t4 = t1 ^ t3; + X3 = c ^ t4; + int t7 = b ^ (t1 & t3); + int t8 = X3 | t7; + X1 = t3 ^ t8; + int t10 = ~X1; + int t11 = X3 ^ t7; + X0 = t10 ^ t11; + X2 = t4 ^ (t10 | t11); + } + + /** + * S2 - { 8, 6, 7, 9, 3,12,10,15,13, 1,14, 4, 0,11, 5, 2 } - 16 terms. + */ + protected void Sb2(int a, int b, int c, int d) + { + int t1 = ~a; + int t2 = b ^ d; + int t3 = c & t1; + X0 = t2 ^ t3; + int t5 = c ^ t1; + int t6 = c ^ X0; + int t7 = b & t6; + X3 = t5 ^ t7; + X2 = a ^ ((d | t7) & (X0 | t5)); + X1 = (t2 ^ X3) ^ (X2 ^ (d | t1)); + } + + /** + * InvS2 - {12, 9,15, 4,11,14, 1, 2, 0, 3, 6,13, 5, 8,10, 7 } - 16 steps. + */ + protected void Ib2(int a, int b, int c, int d) + { + int t1 = b ^ d; + int t2 = ~t1; + int t3 = a ^ c; + int t4 = c ^ t1; + int t5 = b & t4; + X0 = t3 ^ t5; + int t7 = a | t2; + int t8 = d ^ t7; + int t9 = t3 | t8; + X3 = t1 ^ t9; + int t11 = ~t4; + int t12 = X0 | X3; + X1 = t11 ^ t12; + X2 = (d & t11) ^ (t3 ^ t12); + } + + /** + * S3 - { 0,15,11, 8,12, 9, 6, 3,13, 1, 2, 4,10, 7, 5,14 } - 16 terms. + */ + protected void Sb3(int a, int b, int c, int d) + { + int t1 = a ^ b; + int t2 = a & c; + int t3 = a | d; + int t4 = c ^ d; + int t5 = t1 & t3; + int t6 = t2 | t5; + X2 = t4 ^ t6; + int t8 = b ^ t3; + int t9 = t6 ^ t8; + int t10 = t4 & t9; + X0 = t1 ^ t10; + int t12 = X2 & X0; + X1 = t9 ^ t12; + X3 = (b | d) ^ (t4 ^ t12); + } + + /** + * InvS3 - { 0, 9,10, 7,11,14, 6,13, 3, 5,12, 2, 4, 8,15, 1 } - 15 terms + */ + protected void Ib3(int a, int b, int c, int d) + { + int t1 = a | b; + int t2 = b ^ c; + int t3 = b & t2; + int t4 = a ^ t3; + int t5 = c ^ t4; + int t6 = d | t4; + X0 = t2 ^ t6; + int t8 = t2 | t6; + int t9 = d ^ t8; + X2 = t5 ^ t9; + int t11 = t1 ^ t9; + int t12 = X0 & t11; + X3 = t4 ^ t12; + X1 = X3 ^ (X0 ^ t11); + } + + /** + * S4 - { 1,15, 8, 3,12, 0,11, 6, 2, 5, 4,10, 9,14, 7,13 } - 15 terms. + */ + protected void Sb4(int a, int b, int c, int d) + { + int t1 = a ^ d; + int t2 = d & t1; + int t3 = c ^ t2; + int t4 = b | t3; + X3 = t1 ^ t4; + int t6 = ~b; + int t7 = t1 | t6; + X0 = t3 ^ t7; + int t9 = a & X0; + int t10 = t1 ^ t6; + int t11 = t4 & t10; + X2 = t9 ^ t11; + X1 = (a ^ t3) ^ (t10 & X2); + } + + /** + * InvS4 - { 5, 0, 8, 3,10, 9, 7,14, 2,12,11, 6, 4,15,13, 1 } - 15 terms. + */ + protected void Ib4(int a, int b, int c, int d) + { + int t1 = c | d; + int t2 = a & t1; + int t3 = b ^ t2; + int t4 = a & t3; + int t5 = c ^ t4; + X1 = d ^ t5; + int t7 = ~a; + int t8 = t5 & X1; + X3 = t3 ^ t8; + int t10 = X1 | t7; + int t11 = d ^ t10; + X0 = X3 ^ t11; + X2 = (t3 & t11) ^ (X1 ^ t7); + } + + /** + * S5 - {15, 5, 2,11, 4,10, 9,12, 0, 3,14, 8,13, 6, 7, 1 } - 16 terms. + */ + protected void Sb5(int a, int b, int c, int d) + { + int t1 = ~a; + int t2 = a ^ b; + int t3 = a ^ d; + int t4 = c ^ t1; + int t5 = t2 | t3; + X0 = t4 ^ t5; + int t7 = d & X0; + int t8 = t2 ^ X0; + X1 = t7 ^ t8; + int t10 = t1 | X0; + int t11 = t2 | t7; + int t12 = t3 ^ t10; + X2 = t11 ^ t12; + X3 = (b ^ t7) ^ (X1 & t12); + } + + /** + * InvS5 - { 8,15, 2, 9, 4, 1,13,14,11, 6, 5, 3, 7,12,10, 0 } - 16 terms. + */ + protected void Ib5(int a, int b, int c, int d) + { + int t1 = ~c; + int t2 = b & t1; + int t3 = d ^ t2; + int t4 = a & t3; + int t5 = b ^ t1; + X3 = t4 ^ t5; + int t7 = b | X3; + int t8 = a & t7; + X1 = t3 ^ t8; + int t10 = a | d; + int t11 = t1 ^ t7; + X0 = t10 ^ t11; + X2 = (b & t10) ^ (t4 | (a ^ c)); + } + + /** + * S6 - { 7, 2,12, 5, 8, 4, 6,11,14, 9, 1,15,13, 3,10, 0 } - 15 terms. + */ + protected void Sb6(int a, int b, int c, int d) + { + int t1 = ~a; + int t2 = a ^ d; + int t3 = b ^ t2; + int t4 = t1 | t2; + int t5 = c ^ t4; + X1 = b ^ t5; + int t7 = t2 | X1; + int t8 = d ^ t7; + int t9 = t5 & t8; + X2 = t3 ^ t9; + int t11 = t5 ^ t8; + X0 = X2 ^ t11; + X3 = (~t5) ^ (t3 & t11); + } + + /** + * InvS6 - {15,10, 1,13, 5, 3, 6, 0, 4, 9,14, 7, 2,12, 8,11 } - 15 terms. + */ + protected void Ib6(int a, int b, int c, int d) + { + int t1 = ~a; + int t2 = a ^ b; + int t3 = c ^ t2; + int t4 = c | t1; + int t5 = d ^ t4; + X1 = t3 ^ t5; + int t7 = t3 & t5; + int t8 = t2 ^ t7; + int t9 = b | t8; + X3 = t5 ^ t9; + int t11 = b | X3; + X0 = t8 ^ t11; + X2 = (d & t1) ^ (t3 ^ t11); + } + + /** + * S7 - { 1,13,15, 0,14, 8, 2,11, 7, 4,12,10, 9, 3, 5, 6 } - 16 terms. + */ + protected void Sb7(int a, int b, int c, int d) + { + int t1 = b ^ c; + int t2 = c & t1; + int t3 = d ^ t2; + int t4 = a ^ t3; + int t5 = d | t1; + int t6 = t4 & t5; + X1 = b ^ t6; + int t8 = t3 | X1; + int t9 = a & t4; + X3 = t1 ^ t9; + int t11 = t4 ^ t8; + int t12 = X3 & t11; + X2 = t3 ^ t12; + X0 = (~t11) ^ (X3 & X2); + } + + /** + * InvS7 - { 3, 0, 6,13, 9,14,15, 8, 5,12,11, 7,10, 1, 4, 2 } - 17 terms. + */ + protected void Ib7(int a, int b, int c, int d) + { + int t3 = c | (a & b); + int t4 = d & (a | b); + X3 = t3 ^ t4; + int t6 = ~d; + int t7 = b ^ t4; + int t9 = t7 | (X3 ^ t6); + X1 = a ^ t9; + X0 = (c ^ t7) ^ (d | X1); + X2 = (t3 ^ X1) ^ (X0 ^ (a & X3)); + } + + /** + * Apply the linear transformation to the register set. + */ + protected void LT() + { + int x0 = RotateLeft(X0, 13); + int x2 = RotateLeft(X2, 3); + int x1 = X1 ^ x0 ^ x2; + int x3 = X3 ^ x2 ^ x0 << 3; + + X1 = RotateLeft(x1, 1); + X3 = RotateLeft(x3, 7); + X0 = RotateLeft(x0 ^ X1 ^ X3, 5); + X2 = RotateLeft(x2 ^ X3 ^ (X1 << 7), 22); + } + + /** + * Apply the inverse of the linear transformation to the register set. + */ + protected void InverseLT() + { + int x2 = RotateRight(X2, 22) ^ X3 ^ (X1 << 7); + int x0 = RotateRight(X0, 5) ^ X1 ^ X3; + int x3 = RotateRight(X3, 7); + int x1 = RotateRight(X1, 1); + X3 = x3 ^ x2 ^ x0 << 3; + X1 = x1 ^ x0 ^ x2; + X2 = RotateRight(x2, 3); + X0 = RotateRight(x0, 13); + } + + protected abstract int[] MakeWorkingKey(byte[] key); + + protected abstract void EncryptBlock(byte[] input, int inOff, byte[] output, int outOff); + + protected abstract void DecryptBlock(byte[] input, int inOff, byte[] output, int outOff); + } +} diff --git a/crypto/src/crypto/engines/SkipjackEngine.cs b/crypto/src/crypto/engines/SkipjackEngine.cs
index a45dc9b24..c90646cc4 100644 --- a/crypto/src/crypto/engines/SkipjackEngine.cs +++ b/crypto/src/crypto/engines/SkipjackEngine.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -48,7 +49,7 @@ namespace Org.BouncyCastle.Crypto.Engines ICipherParameters parameters) { if (!(parameters is KeyParameter)) - throw new ArgumentException("invalid parameter passed to SKIPJACK init - " + parameters.GetType().ToString()); + throw new ArgumentException("invalid parameter passed to SKIPJACK init - " + Platform.GetTypeName(parameters)); byte[] keyBytes = ((KeyParameter)parameters).GetKey(); diff --git a/crypto/src/crypto/engines/TEAEngine.cs b/crypto/src/crypto/engines/TEAEngine.cs
index 2e1a7002b..7b700145e 100644 --- a/crypto/src/crypto/engines/TEAEngine.cs +++ b/crypto/src/crypto/engines/TEAEngine.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -66,7 +67,7 @@ namespace Org.BouncyCastle.Crypto.Engines if (!(parameters is KeyParameter)) { throw new ArgumentException("invalid parameter passed to TEA init - " - + parameters.GetType().FullName); + + Platform.GetTypeName(parameters)); } _forEncryption = forEncryption; diff --git a/crypto/src/crypto/engines/ThreefishEngine.cs b/crypto/src/crypto/engines/ThreefishEngine.cs
index 33ff3a421..eade3cc72 100644 --- a/crypto/src/crypto/engines/ThreefishEngine.cs +++ b/crypto/src/crypto/engines/ThreefishEngine.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Encoders; namespace Org.BouncyCastle.Crypto.Engines @@ -174,7 +175,7 @@ namespace Org.BouncyCastle.Crypto.Engines else { throw new ArgumentException("Invalid parameter passed to Threefish init - " - + parameters.GetType().Name); + + Platform.GetTypeName(parameters)); } ulong[] keyWords = null; diff --git a/crypto/src/crypto/engines/TnepresEngine.cs b/crypto/src/crypto/engines/TnepresEngine.cs new file mode 100644
index 000000000..ce687d1e5 --- /dev/null +++ b/crypto/src/crypto/engines/TnepresEngine.cs
@@ -0,0 +1,299 @@ +using System; + +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Crypto.Utilities; + +namespace Org.BouncyCastle.Crypto.Engines +{ + /** + * Tnepres is a 128-bit 32-round block cipher with variable key lengths, + * including 128, 192 and 256 bit keys conjectured to be at least as + * secure as three-key triple-DES. + * <p> + * Tnepres is based on Serpent which was designed by Ross Anderson, Eli Biham and Lars Knudsen as a + * candidate algorithm for the NIST AES Quest. Unfortunately there was an endianness issue + * with test vectors in the AES submission and the resulting confusion lead to the Tnepres cipher + * as well, which is a byte swapped version of Serpent. + * </p> + * <p> + * For full details see <a href="http://www.cl.cam.ac.uk/~rja14/serpent.html">The Serpent home page</a> + * </p> + */ + public sealed class TnepresEngine + : SerpentEngineBase + { + public override string AlgorithmName + { + get { return "Tnepres"; } + } + + /** + * Expand a user-supplied key material into a session key. + * + * @param key The user-key bytes (multiples of 4) to use. + * @exception ArgumentException + */ + protected override int[] MakeWorkingKey(byte[] key) + { + // + // pad key to 256 bits + // + int[] kPad = new int[16]; + int off = 0; + int length = 0; + + for (off = key.Length - 4; off > 0; off -= 4) + { + kPad[length++] = (int)Pack.BE_To_UInt32(key, off); + } + + if (off == 0) + { + kPad[length++] = (int)Pack.BE_To_UInt32(key, 0); + if (length < 8) + { + kPad[length] = 1; + } + } + else + { + throw new ArgumentException("key must be a multiple of 4 bytes"); + } + + // + // expand the padded key up to 33 x 128 bits of key material + // + int amount = (ROUNDS + 1) * 4; + int[] w = new int[amount]; + + // + // compute w0 to w7 from w-8 to w-1 + // + for (int i = 8; i < 16; i++) + { + kPad[i] = RotateLeft(kPad[i - 8] ^ kPad[i - 5] ^ kPad[i - 3] ^ kPad[i - 1] ^ PHI ^ (i - 8), 11); + } + + Array.Copy(kPad, 8, w, 0, 8); + + // + // compute w8 to w136 + // + for (int i = 8; i < amount; i++) + { + w[i] = RotateLeft(w[i - 8] ^ w[i - 5] ^ w[i - 3] ^ w[i - 1] ^ PHI ^ i, 11); + } + + // + // create the working keys by processing w with the Sbox and IP + // + Sb3(w[0], w[1], w[2], w[3]); + w[0] = X0; w[1] = X1; w[2] = X2; w[3] = X3; + Sb2(w[4], w[5], w[6], w[7]); + w[4] = X0; w[5] = X1; w[6] = X2; w[7] = X3; + Sb1(w[8], w[9], w[10], w[11]); + w[8] = X0; w[9] = X1; w[10] = X2; w[11] = X3; + Sb0(w[12], w[13], w[14], w[15]); + w[12] = X0; w[13] = X1; w[14] = X2; w[15] = X3; + Sb7(w[16], w[17], w[18], w[19]); + w[16] = X0; w[17] = X1; w[18] = X2; w[19] = X3; + Sb6(w[20], w[21], w[22], w[23]); + w[20] = X0; w[21] = X1; w[22] = X2; w[23] = X3; + Sb5(w[24], w[25], w[26], w[27]); + w[24] = X0; w[25] = X1; w[26] = X2; w[27] = X3; + Sb4(w[28], w[29], w[30], w[31]); + w[28] = X0; w[29] = X1; w[30] = X2; w[31] = X3; + Sb3(w[32], w[33], w[34], w[35]); + w[32] = X0; w[33] = X1; w[34] = X2; w[35] = X3; + Sb2(w[36], w[37], w[38], w[39]); + w[36] = X0; w[37] = X1; w[38] = X2; w[39] = X3; + Sb1(w[40], w[41], w[42], w[43]); + w[40] = X0; w[41] = X1; w[42] = X2; w[43] = X3; + Sb0(w[44], w[45], w[46], w[47]); + w[44] = X0; w[45] = X1; w[46] = X2; w[47] = X3; + Sb7(w[48], w[49], w[50], w[51]); + w[48] = X0; w[49] = X1; w[50] = X2; w[51] = X3; + Sb6(w[52], w[53], w[54], w[55]); + w[52] = X0; w[53] = X1; w[54] = X2; w[55] = X3; + Sb5(w[56], w[57], w[58], w[59]); + w[56] = X0; w[57] = X1; w[58] = X2; w[59] = X3; + Sb4(w[60], w[61], w[62], w[63]); + w[60] = X0; w[61] = X1; w[62] = X2; w[63] = X3; + Sb3(w[64], w[65], w[66], w[67]); + w[64] = X0; w[65] = X1; w[66] = X2; w[67] = X3; + Sb2(w[68], w[69], w[70], w[71]); + w[68] = X0; w[69] = X1; w[70] = X2; w[71] = X3; + Sb1(w[72], w[73], w[74], w[75]); + w[72] = X0; w[73] = X1; w[74] = X2; w[75] = X3; + Sb0(w[76], w[77], w[78], w[79]); + w[76] = X0; w[77] = X1; w[78] = X2; w[79] = X3; + Sb7(w[80], w[81], w[82], w[83]); + w[80] = X0; w[81] = X1; w[82] = X2; w[83] = X3; + Sb6(w[84], w[85], w[86], w[87]); + w[84] = X0; w[85] = X1; w[86] = X2; w[87] = X3; + Sb5(w[88], w[89], w[90], w[91]); + w[88] = X0; w[89] = X1; w[90] = X2; w[91] = X3; + Sb4(w[92], w[93], w[94], w[95]); + w[92] = X0; w[93] = X1; w[94] = X2; w[95] = X3; + Sb3(w[96], w[97], w[98], w[99]); + w[96] = X0; w[97] = X1; w[98] = X2; w[99] = X3; + Sb2(w[100], w[101], w[102], w[103]); + w[100] = X0; w[101] = X1; w[102] = X2; w[103] = X3; + Sb1(w[104], w[105], w[106], w[107]); + w[104] = X0; w[105] = X1; w[106] = X2; w[107] = X3; + Sb0(w[108], w[109], w[110], w[111]); + w[108] = X0; w[109] = X1; w[110] = X2; w[111] = X3; + Sb7(w[112], w[113], w[114], w[115]); + w[112] = X0; w[113] = X1; w[114] = X2; w[115] = X3; + Sb6(w[116], w[117], w[118], w[119]); + w[116] = X0; w[117] = X1; w[118] = X2; w[119] = X3; + Sb5(w[120], w[121], w[122], w[123]); + w[120] = X0; w[121] = X1; w[122] = X2; w[123] = X3; + Sb4(w[124], w[125], w[126], w[127]); + w[124] = X0; w[125] = X1; w[126] = X2; w[127] = X3; + Sb3(w[128], w[129], w[130], w[131]); + w[128] = X0; w[129] = X1; w[130] = X2; w[131] = X3; + + return w; + } + + /** + * Encrypt one block of plaintext. + * + * @param input the array containing the input data. + * @param inOff offset into the in array the data starts at. + * @param output the array the output data will be copied into. + * @param outOff the offset into the out array the output will start at. + */ + protected override void EncryptBlock(byte[] input, int inOff, byte[] output, int outOff) + { + X3 = (int)Pack.BE_To_UInt32(input, inOff); + X2 = (int)Pack.BE_To_UInt32(input, inOff + 4); + X1 = (int)Pack.BE_To_UInt32(input, inOff + 8); + X0 = (int)Pack.BE_To_UInt32(input, inOff + 12); + + Sb0(wKey[0] ^ X0, wKey[1] ^ X1, wKey[2] ^ X2, wKey[3] ^ X3); LT(); + Sb1(wKey[4] ^ X0, wKey[5] ^ X1, wKey[6] ^ X2, wKey[7] ^ X3); LT(); + Sb2(wKey[8] ^ X0, wKey[9] ^ X1, wKey[10] ^ X2, wKey[11] ^ X3); LT(); + Sb3(wKey[12] ^ X0, wKey[13] ^ X1, wKey[14] ^ X2, wKey[15] ^ X3); LT(); + Sb4(wKey[16] ^ X0, wKey[17] ^ X1, wKey[18] ^ X2, wKey[19] ^ X3); LT(); + Sb5(wKey[20] ^ X0, wKey[21] ^ X1, wKey[22] ^ X2, wKey[23] ^ X3); LT(); + Sb6(wKey[24] ^ X0, wKey[25] ^ X1, wKey[26] ^ X2, wKey[27] ^ X3); LT(); + Sb7(wKey[28] ^ X0, wKey[29] ^ X1, wKey[30] ^ X2, wKey[31] ^ X3); LT(); + Sb0(wKey[32] ^ X0, wKey[33] ^ X1, wKey[34] ^ X2, wKey[35] ^ X3); LT(); + Sb1(wKey[36] ^ X0, wKey[37] ^ X1, wKey[38] ^ X2, wKey[39] ^ X3); LT(); + Sb2(wKey[40] ^ X0, wKey[41] ^ X1, wKey[42] ^ X2, wKey[43] ^ X3); LT(); + Sb3(wKey[44] ^ X0, wKey[45] ^ X1, wKey[46] ^ X2, wKey[47] ^ X3); LT(); + Sb4(wKey[48] ^ X0, wKey[49] ^ X1, wKey[50] ^ X2, wKey[51] ^ X3); LT(); + Sb5(wKey[52] ^ X0, wKey[53] ^ X1, wKey[54] ^ X2, wKey[55] ^ X3); LT(); + Sb6(wKey[56] ^ X0, wKey[57] ^ X1, wKey[58] ^ X2, wKey[59] ^ X3); LT(); + Sb7(wKey[60] ^ X0, wKey[61] ^ X1, wKey[62] ^ X2, wKey[63] ^ X3); LT(); + Sb0(wKey[64] ^ X0, wKey[65] ^ X1, wKey[66] ^ X2, wKey[67] ^ X3); LT(); + Sb1(wKey[68] ^ X0, wKey[69] ^ X1, wKey[70] ^ X2, wKey[71] ^ X3); LT(); + Sb2(wKey[72] ^ X0, wKey[73] ^ X1, wKey[74] ^ X2, wKey[75] ^ X3); LT(); + Sb3(wKey[76] ^ X0, wKey[77] ^ X1, wKey[78] ^ X2, wKey[79] ^ X3); LT(); + Sb4(wKey[80] ^ X0, wKey[81] ^ X1, wKey[82] ^ X2, wKey[83] ^ X3); LT(); + Sb5(wKey[84] ^ X0, wKey[85] ^ X1, wKey[86] ^ X2, wKey[87] ^ X3); LT(); + Sb6(wKey[88] ^ X0, wKey[89] ^ X1, wKey[90] ^ X2, wKey[91] ^ X3); LT(); + Sb7(wKey[92] ^ X0, wKey[93] ^ X1, wKey[94] ^ X2, wKey[95] ^ X3); LT(); + Sb0(wKey[96] ^ X0, wKey[97] ^ X1, wKey[98] ^ X2, wKey[99] ^ X3); LT(); + Sb1(wKey[100] ^ X0, wKey[101] ^ X1, wKey[102] ^ X2, wKey[103] ^ X3); LT(); + Sb2(wKey[104] ^ X0, wKey[105] ^ X1, wKey[106] ^ X2, wKey[107] ^ X3); LT(); + Sb3(wKey[108] ^ X0, wKey[109] ^ X1, wKey[110] ^ X2, wKey[111] ^ X3); LT(); + Sb4(wKey[112] ^ X0, wKey[113] ^ X1, wKey[114] ^ X2, wKey[115] ^ X3); LT(); + Sb5(wKey[116] ^ X0, wKey[117] ^ X1, wKey[118] ^ X2, wKey[119] ^ X3); LT(); + Sb6(wKey[120] ^ X0, wKey[121] ^ X1, wKey[122] ^ X2, wKey[123] ^ X3); LT(); + Sb7(wKey[124] ^ X0, wKey[125] ^ X1, wKey[126] ^ X2, wKey[127] ^ X3); + + Pack.UInt32_To_BE((uint)(wKey[131] ^ X3), output, outOff); + Pack.UInt32_To_BE((uint)(wKey[130] ^ X2), output, outOff + 4); + Pack.UInt32_To_BE((uint)(wKey[129] ^ X1), output, outOff + 8); + Pack.UInt32_To_BE((uint)(wKey[128] ^ X0), output, outOff + 12); + } + + /** + * Decrypt one block of ciphertext. + * + * @param input the array containing the input data. + * @param inOff offset into the in array the data starts at. + * @param output the array the output data will be copied into. + * @param outOff the offset into the out array the output will start at. + */ + protected override void DecryptBlock(byte[] input, int inOff, byte[] output, int outOff) + { + X3 = wKey[131] ^ (int)Pack.BE_To_UInt32(input, inOff); + X2 = wKey[130] ^ (int)Pack.BE_To_UInt32(input, inOff + 4); + X1 = wKey[129] ^ (int)Pack.BE_To_UInt32(input, inOff + 8); + X0 = wKey[128] ^ (int)Pack.BE_To_UInt32(input, inOff + 12); + + Ib7(X0, X1, X2, X3); + X0 ^= wKey[124]; X1 ^= wKey[125]; X2 ^= wKey[126]; X3 ^= wKey[127]; + InverseLT(); Ib6(X0, X1, X2, X3); + X0 ^= wKey[120]; X1 ^= wKey[121]; X2 ^= wKey[122]; X3 ^= wKey[123]; + InverseLT(); Ib5(X0, X1, X2, X3); + X0 ^= wKey[116]; X1 ^= wKey[117]; X2 ^= wKey[118]; X3 ^= wKey[119]; + InverseLT(); Ib4(X0, X1, X2, X3); + X0 ^= wKey[112]; X1 ^= wKey[113]; X2 ^= wKey[114]; X3 ^= wKey[115]; + InverseLT(); Ib3(X0, X1, X2, X3); + X0 ^= wKey[108]; X1 ^= wKey[109]; X2 ^= wKey[110]; X3 ^= wKey[111]; + InverseLT(); Ib2(X0, X1, X2, X3); + X0 ^= wKey[104]; X1 ^= wKey[105]; X2 ^= wKey[106]; X3 ^= wKey[107]; + InverseLT(); Ib1(X0, X1, X2, X3); + X0 ^= wKey[100]; X1 ^= wKey[101]; X2 ^= wKey[102]; X3 ^= wKey[103]; + InverseLT(); Ib0(X0, X1, X2, X3); + X0 ^= wKey[96]; X1 ^= wKey[97]; X2 ^= wKey[98]; X3 ^= wKey[99]; + InverseLT(); Ib7(X0, X1, X2, X3); + X0 ^= wKey[92]; X1 ^= wKey[93]; X2 ^= wKey[94]; X3 ^= wKey[95]; + InverseLT(); Ib6(X0, X1, X2, X3); + X0 ^= wKey[88]; X1 ^= wKey[89]; X2 ^= wKey[90]; X3 ^= wKey[91]; + InverseLT(); Ib5(X0, X1, X2, X3); + X0 ^= wKey[84]; X1 ^= wKey[85]; X2 ^= wKey[86]; X3 ^= wKey[87]; + InverseLT(); Ib4(X0, X1, X2, X3); + X0 ^= wKey[80]; X1 ^= wKey[81]; X2 ^= wKey[82]; X3 ^= wKey[83]; + InverseLT(); Ib3(X0, X1, X2, X3); + X0 ^= wKey[76]; X1 ^= wKey[77]; X2 ^= wKey[78]; X3 ^= wKey[79]; + InverseLT(); Ib2(X0, X1, X2, X3); + X0 ^= wKey[72]; X1 ^= wKey[73]; X2 ^= wKey[74]; X3 ^= wKey[75]; + InverseLT(); Ib1(X0, X1, X2, X3); + X0 ^= wKey[68]; X1 ^= wKey[69]; X2 ^= wKey[70]; X3 ^= wKey[71]; + InverseLT(); Ib0(X0, X1, X2, X3); + X0 ^= wKey[64]; X1 ^= wKey[65]; X2 ^= wKey[66]; X3 ^= wKey[67]; + InverseLT(); Ib7(X0, X1, X2, X3); + X0 ^= wKey[60]; X1 ^= wKey[61]; X2 ^= wKey[62]; X3 ^= wKey[63]; + InverseLT(); Ib6(X0, X1, X2, X3); + X0 ^= wKey[56]; X1 ^= wKey[57]; X2 ^= wKey[58]; X3 ^= wKey[59]; + InverseLT(); Ib5(X0, X1, X2, X3); + X0 ^= wKey[52]; X1 ^= wKey[53]; X2 ^= wKey[54]; X3 ^= wKey[55]; + InverseLT(); Ib4(X0, X1, X2, X3); + X0 ^= wKey[48]; X1 ^= wKey[49]; X2 ^= wKey[50]; X3 ^= wKey[51]; + InverseLT(); Ib3(X0, X1, X2, X3); + X0 ^= wKey[44]; X1 ^= wKey[45]; X2 ^= wKey[46]; X3 ^= wKey[47]; + InverseLT(); Ib2(X0, X1, X2, X3); + X0 ^= wKey[40]; X1 ^= wKey[41]; X2 ^= wKey[42]; X3 ^= wKey[43]; + InverseLT(); Ib1(X0, X1, X2, X3); + X0 ^= wKey[36]; X1 ^= wKey[37]; X2 ^= wKey[38]; X3 ^= wKey[39]; + InverseLT(); Ib0(X0, X1, X2, X3); + X0 ^= wKey[32]; X1 ^= wKey[33]; X2 ^= wKey[34]; X3 ^= wKey[35]; + InverseLT(); Ib7(X0, X1, X2, X3); + X0 ^= wKey[28]; X1 ^= wKey[29]; X2 ^= wKey[30]; X3 ^= wKey[31]; + InverseLT(); Ib6(X0, X1, X2, X3); + X0 ^= wKey[24]; X1 ^= wKey[25]; X2 ^= wKey[26]; X3 ^= wKey[27]; + InverseLT(); Ib5(X0, X1, X2, X3); + X0 ^= wKey[20]; X1 ^= wKey[21]; X2 ^= wKey[22]; X3 ^= wKey[23]; + InverseLT(); Ib4(X0, X1, X2, X3); + X0 ^= wKey[16]; X1 ^= wKey[17]; X2 ^= wKey[18]; X3 ^= wKey[19]; + InverseLT(); Ib3(X0, X1, X2, X3); + X0 ^= wKey[12]; X1 ^= wKey[13]; X2 ^= wKey[14]; X3 ^= wKey[15]; + InverseLT(); Ib2(X0, X1, X2, X3); + X0 ^= wKey[8]; X1 ^= wKey[9]; X2 ^= wKey[10]; X3 ^= wKey[11]; + InverseLT(); Ib1(X0, X1, X2, X3); + X0 ^= wKey[4]; X1 ^= wKey[5]; X2 ^= wKey[6]; X3 ^= wKey[7]; + InverseLT(); Ib0(X0, X1, X2, X3); + + Pack.UInt32_To_BE((uint)(X3 ^ wKey[3]), output, outOff); + Pack.UInt32_To_BE((uint)(X2 ^ wKey[2]), output, outOff + 4); + Pack.UInt32_To_BE((uint)(X1 ^ wKey[1]), output, outOff + 8); + Pack.UInt32_To_BE((uint)(X0 ^ wKey[0]), output, outOff + 12); + } + } +} diff --git a/crypto/src/crypto/engines/TwofishEngine.cs b/crypto/src/crypto/engines/TwofishEngine.cs
index 04a579ced..71c246594 100644 --- a/crypto/src/crypto/engines/TwofishEngine.cs +++ b/crypto/src/crypto/engines/TwofishEngine.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -267,7 +268,7 @@ namespace Org.BouncyCastle.Crypto.Engines ICipherParameters parameters) { if (!(parameters is KeyParameter)) - throw new ArgumentException("invalid parameter passed to Twofish init - " + parameters.GetType().ToString()); + throw new ArgumentException("invalid parameter passed to Twofish init - " + Platform.GetTypeName(parameters)); this.encrypting = forEncryption; this.workingKey = ((KeyParameter)parameters).GetKey(); diff --git a/crypto/src/crypto/engines/XTEAEngine.cs b/crypto/src/crypto/engines/XTEAEngine.cs
index 40d81fbe6..5fcfa4a57 100644 --- a/crypto/src/crypto/engines/XTEAEngine.cs +++ b/crypto/src/crypto/engines/XTEAEngine.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { @@ -64,7 +65,7 @@ namespace Org.BouncyCastle.Crypto.Engines if (!(parameters is KeyParameter)) { throw new ArgumentException("invalid parameter passed to TEA init - " - + parameters.GetType().FullName); + + Platform.GetTypeName(parameters)); } _forEncryption = forEncryption; diff --git a/crypto/src/crypto/generators/DHParametersHelper.cs b/crypto/src/crypto/generators/DHParametersHelper.cs
index bf2de2add..385690430 100644 --- a/crypto/src/crypto/generators/DHParametersHelper.cs +++ b/crypto/src/crypto/generators/DHParametersHelper.cs
@@ -44,10 +44,10 @@ namespace Org.BouncyCastle.Crypto.Generators p = q.ShiftLeft(1).Add(BigInteger.One); - if (!p.IsProbablePrime(certainty)) + if (!p.IsProbablePrime(certainty, true)) continue; - if (certainty > 2 && !q.IsProbablePrime(certainty - 2)) + if (certainty > 2 && !q.IsProbablePrime(certainty, true)) continue; break; @@ -92,15 +92,15 @@ namespace Org.BouncyCastle.Crypto.Generators if (q.BitLength != qLength) continue; - if (!q.RabinMillerTest(2, random)) + if (!q.RabinMillerTest(2, random, true)) continue; p = q.ShiftLeft(1).Add(BigInteger.One); - if (!p.RabinMillerTest(certainty, random)) + if (!p.RabinMillerTest(certainty, random, true)) continue; - if (certainty > 2 && !q.RabinMillerTest(certainty - 2, random)) + if (certainty > 2 && !q.RabinMillerTest(certainty - 2, random, true)) continue; /* diff --git a/crypto/src/crypto/generators/DesEdeKeyGenerator.cs b/crypto/src/crypto/generators/DesEdeKeyGenerator.cs
index 5902643fd..904cc71f1 100644 --- a/crypto/src/crypto/generators/DesEdeKeyGenerator.cs +++ b/crypto/src/crypto/generators/DesEdeKeyGenerator.cs
@@ -52,14 +52,14 @@ namespace Org.BouncyCastle.Crypto.Generators protected override byte[] engineGenerateKey() { - byte[] newKey; + byte[] newKey = new byte[strength]; - do + do { - newKey = random.GenerateSeed(strength); + random.NextBytes(newKey); DesEdeParameters.SetOddParity(newKey); } - while (DesEdeParameters.IsWeakKey(newKey, 0, newKey.Length)); + while (DesEdeParameters.IsWeakKey(newKey, 0, newKey.Length) || !DesEdeParameters.IsRealEdeKey(newKey, 0)); return newKey; } diff --git a/crypto/src/crypto/generators/DesKeyGenerator.cs b/crypto/src/crypto/generators/DesKeyGenerator.cs
index 154e3471a..4c2051d89 100644 --- a/crypto/src/crypto/generators/DesKeyGenerator.cs +++ b/crypto/src/crypto/generators/DesKeyGenerator.cs
@@ -42,12 +42,12 @@ namespace Org.BouncyCastle.Crypto.Generators protected override byte[] engineGenerateKey() { - byte[] newKey; + byte[] newKey = new byte[DesParameters.DesKeyLength]; - do + do { - newKey = random.GenerateSeed(DesParameters.DesKeyLength); - DesParameters.SetOddParity(newKey); + random.NextBytes(newKey); + DesParameters.SetOddParity(newKey); } while (DesParameters.IsWeakKey(newKey, 0)); diff --git a/crypto/src/crypto/generators/NaccacheSternKeyPairGenerator.cs b/crypto/src/crypto/generators/NaccacheSternKeyPairGenerator.cs
index afc566d87..618ca9a1c 100644 --- a/crypto/src/crypto/generators/NaccacheSternKeyPairGenerator.cs +++ b/crypto/src/crypto/generators/NaccacheSternKeyPairGenerator.cs
@@ -98,7 +98,7 @@ namespace Org.BouncyCastle.Crypto.Generators p = _p.Multiply(_2au).Add(BigInteger.One); - if (!p.IsProbablePrime(certainty)) + if (!p.IsProbablePrime(certainty, true)) continue; for (;;) @@ -110,7 +110,7 @@ namespace Org.BouncyCastle.Crypto.Generators q = _q.Multiply(_2bv).Add(BigInteger.One); - if (q.IsProbablePrime(certainty)) + if (q.IsProbablePrime(certainty, true)) break; } diff --git a/crypto/src/crypto/generators/RsaKeyPairGenerator.cs b/crypto/src/crypto/generators/RsaKeyPairGenerator.cs
index 2613b902b..449976550 100644 --- a/crypto/src/crypto/generators/RsaKeyPairGenerator.cs +++ b/crypto/src/crypto/generators/RsaKeyPairGenerator.cs
@@ -150,7 +150,7 @@ namespace Org.BouncyCastle.Crypto.Generators if (p.Mod(e).Equals(One)) continue; - if (!p.IsProbablePrime(parameters.Certainty)) + if (!p.IsProbablePrime(parameters.Certainty, true)) continue; if (!eIsKnownOddPrime && !e.Gcd(p.Subtract(One)).Equals(One)) diff --git a/crypto/src/crypto/io/CipherStream.cs b/crypto/src/crypto/io/CipherStream.cs
index b6920854d..bfce386a7 100644 --- a/crypto/src/crypto/io/CipherStream.cs +++ b/crypto/src/crypto/io/CipherStream.cs
@@ -3,6 +3,7 @@ using System.Diagnostics; using System.IO; using Org.BouncyCastle.Crypto; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.IO { @@ -201,7 +202,23 @@ namespace Org.BouncyCastle.Crypto.IO set { throw new NotSupportedException(); } } - public override void Close() +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (outCipher != null) + { + byte[] data = outCipher.DoFinal(); + stream.Write(data, 0, data.Length); + stream.Flush(); + } + Platform.Dispose(stream); + } + base.Dispose(disposing); + } +#else + public override void Close() { if (outCipher != null) { @@ -209,10 +226,12 @@ namespace Org.BouncyCastle.Crypto.IO stream.Write(data, 0, data.Length); stream.Flush(); } - stream.Close(); + Platform.Dispose(stream); + base.Close(); } +#endif - public override void Flush() + public override void Flush() { // Note: outCipher.DoFinal is only called during Close() stream.Flush(); diff --git a/crypto/src/crypto/io/DigestStream.cs b/crypto/src/crypto/io/DigestStream.cs
index c819a409a..dce875792 100644 --- a/crypto/src/crypto/io/DigestStream.cs +++ b/crypto/src/crypto/io/DigestStream.cs
@@ -1,6 +1,8 @@ using System; using System.IO; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Crypto.IO { public class DigestStream @@ -110,12 +112,24 @@ namespace Org.BouncyCastle.Crypto.IO set { stream.Position = value; } } +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + Platform.Dispose(stream); + } + base.Dispose(disposing); + } +#else public override void Close() { - stream.Close(); + Platform.Dispose(stream); + base.Close(); } +#endif - public override void Flush() + public override void Flush() { stream.Flush(); } diff --git a/crypto/src/crypto/io/MacStream.cs b/crypto/src/crypto/io/MacStream.cs
index 51cf1832e..d9b8323b5 100644 --- a/crypto/src/crypto/io/MacStream.cs +++ b/crypto/src/crypto/io/MacStream.cs
@@ -1,6 +1,8 @@ using System; using System.IO; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Crypto.IO { public class MacStream @@ -109,12 +111,24 @@ namespace Org.BouncyCastle.Crypto.IO set { stream.Position = value; } } - public override void Close() - { - stream.Close(); - } - - public override void Flush() +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + Platform.Dispose(stream); + } + base.Dispose(disposing); + } +#else + public override void Close() + { + Platform.Dispose(stream); + base.Close(); + } +#endif + + public override void Flush() { stream.Flush(); } diff --git a/crypto/src/crypto/io/SignerStream.cs b/crypto/src/crypto/io/SignerStream.cs
index 49dfb38c6..1e37c8d34 100644 --- a/crypto/src/crypto/io/SignerStream.cs +++ b/crypto/src/crypto/io/SignerStream.cs
@@ -1,6 +1,8 @@ using System; using System.IO; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Crypto.IO { public class SignerStream @@ -110,12 +112,24 @@ namespace Org.BouncyCastle.Crypto.IO set { stream.Position = value; } } - public override void Close() - { - stream.Close(); - } - - public override void Flush() +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + Platform.Dispose(stream); + } + base.Dispose(disposing); + } +#else + public override void Close() + { + Platform.Dispose(stream); + base.Close(); + } +#endif + + public override void Flush() { stream.Flush(); } diff --git a/crypto/src/crypto/macs/GOST28147Mac.cs b/crypto/src/crypto/macs/GOST28147Mac.cs
index 9a8f1b730..cc6b723d6 100644 --- a/crypto/src/crypto/macs/GOST28147Mac.cs +++ b/crypto/src/crypto/macs/GOST28147Mac.cs
@@ -2,6 +2,7 @@ using System; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Macs { @@ -83,7 +84,7 @@ namespace Org.BouncyCastle.Crypto.Macs else { throw new ArgumentException("invalid parameter passed to Gost28147 init - " - + parameters.GetType().Name); + + Platform.GetTypeName(parameters)); } } diff --git a/crypto/src/crypto/macs/SkeinMac.cs b/crypto/src/crypto/macs/SkeinMac.cs
index 1d61a41ca..07eff24f4 100644 --- a/crypto/src/crypto/macs/SkeinMac.cs +++ b/crypto/src/crypto/macs/SkeinMac.cs
@@ -3,6 +3,7 @@ using System; using Org.BouncyCastle.Crypto.Digests; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Macs { @@ -79,7 +80,7 @@ namespace Org.BouncyCastle.Crypto.Macs else { throw new ArgumentException("Invalid parameter passed to Skein MAC init - " - + parameters.GetType().Name); + + Platform.GetTypeName(parameters)); } if (skeinParameters.GetKey() == null) { diff --git a/crypto/src/crypto/modes/GCMBlockCipher.cs b/crypto/src/crypto/modes/GCMBlockCipher.cs
index 8e6120eef..ecebc3de9 100644 --- a/crypto/src/crypto/modes/GCMBlockCipher.cs +++ b/crypto/src/crypto/modes/GCMBlockCipher.cs
@@ -513,10 +513,11 @@ namespace Org.BouncyCastle.Crypto.Modes private byte[] GetNextCounterBlock() { - for (int i = 15; i >= 12; --i) - { - if (++counter[i] != 0) break; - } + uint c = 1; + c += counter[15]; counter[15] = (byte)c; c >>= 8; + c += counter[14]; counter[14] = (byte)c; c >>= 8; + c += counter[13]; counter[13] = (byte)c; c >>= 8; + c += counter[12]; counter[12] = (byte)c; byte[] tmp = new byte[BlockSize]; // TODO Sure would be nice if ciphers could operate on int[] diff --git a/crypto/src/crypto/modes/SicBlockCipher.cs b/crypto/src/crypto/modes/SicBlockCipher.cs
index 239f99478..0bea4a455 100644 --- a/crypto/src/crypto/modes/SicBlockCipher.cs +++ b/crypto/src/crypto/modes/SicBlockCipher.cs
@@ -56,16 +56,18 @@ namespace Org.BouncyCastle.Crypto.Modes if (blockSize < IV.Length) throw new ArgumentException("CTR/SIC mode requires IV no greater than: " + blockSize + " bytes."); - if (blockSize - IV.Length > 8) - throw new ArgumentException("CTR/SIC mode requires IV of at least: " + (blockSize - 8) + " bytes."); - Reset(); + int maxCounterSize = System.Math.Min(8, blockSize / 2); + if (blockSize - IV.Length > maxCounterSize) + throw new ArgumentException("CTR/SIC mode requires IV of at least: " + (blockSize - maxCounterSize) + " bytes."); // if null it's an IV changed only. if (ivParam.Parameters != null) { cipher.Init(true, ivParam.Parameters); } + + Reset(); } public virtual string AlgorithmName diff --git a/crypto/src/crypto/operators/Asn1Signature.cs b/crypto/src/crypto/operators/Asn1Signature.cs
index 9e66b6f0c..e023c1d18 100644 --- a/crypto/src/crypto/operators/Asn1Signature.cs +++ b/crypto/src/crypto/operators/Asn1Signature.cs
@@ -170,13 +170,13 @@ namespace Org.BouncyCastle.Crypto.Operators if (parameters != null && !derNull.Equals(parameters)) { - if (sigAlgId.ObjectID.Equals(PkcsObjectIdentifiers.IdRsassaPss)) + if (sigAlgId.Algorithm.Equals(PkcsObjectIdentifiers.IdRsassaPss)) { RsassaPssParameters rsaParams = RsassaPssParameters.GetInstance(parameters); - return GetDigestAlgName(rsaParams.HashAlgorithm.ObjectID) + "withRSAandMGF1"; + return GetDigestAlgName(rsaParams.HashAlgorithm.Algorithm) + "withRSAandMGF1"; } - if (sigAlgId.ObjectID.Equals(X9ObjectIdentifiers.ECDsaWithSha2)) + if (sigAlgId.Algorithm.Equals(X9ObjectIdentifiers.ECDsaWithSha2)) { Asn1Sequence ecDsaParams = Asn1Sequence.GetInstance(parameters); @@ -184,7 +184,7 @@ namespace Org.BouncyCastle.Crypto.Operators } } - return sigAlgId.ObjectID.Id; + return sigAlgId.Algorithm.Id; } private static RsassaPssParameters CreatePssParams( @@ -303,11 +303,7 @@ namespace Org.BouncyCastle.Crypto.Operators set { throw new NotImplementedException (); } } - public override void Close() - { - } - - public override void Flush() + public override void Flush() { } @@ -326,10 +322,10 @@ namespace Org.BouncyCastle.Crypto.Operators } /// <summary> - /// Calculator class for signature generation in ASN.1 based profiles that use an AlgorithmIdentifier to preserve + /// Calculator factory class for signature generation in ASN.1 based profiles that use an AlgorithmIdentifier to preserve /// signature algorithm details. /// </summary> - public class Asn1SignatureCalculator: ISignatureCalculator + public class Asn1SignatureFactory: ISignatureFactory { private readonly AlgorithmIdentifier algID; private readonly string algorithm; @@ -341,7 +337,7 @@ namespace Org.BouncyCastle.Crypto.Operators /// </summary> /// <param name="algorithm">The name of the signature algorithm to use.</param> /// <param name="privateKey">The private key to be used in the signing operation.</param> - public Asn1SignatureCalculator (string algorithm, AsymmetricKeyParameter privateKey): this(algorithm, privateKey, null) + public Asn1SignatureFactory (string algorithm, AsymmetricKeyParameter privateKey): this(algorithm, privateKey, null) { } @@ -351,7 +347,7 @@ namespace Org.BouncyCastle.Crypto.Operators /// <param name="algorithm">The name of the signature algorithm to use.</param> /// <param name="privateKey">The private key to be used in the signing operation.</param> /// <param name="random">The source of randomness to be used in signature calculation.</param> - public Asn1SignatureCalculator (string algorithm, AsymmetricKeyParameter privateKey, SecureRandom random) + public Asn1SignatureFactory (string algorithm, AsymmetricKeyParameter privateKey, SecureRandom random) { DerObjectIdentifier sigOid = X509Utilities.GetAlgorithmOid (algorithm); @@ -441,7 +437,7 @@ namespace Org.BouncyCastle.Crypto.Operators /// Verifier class for signature verification in ASN.1 based profiles that use an AlgorithmIdentifier to preserve /// signature algorithm details. /// </summary> - public class Asn1SignatureVerifier: ISignatureVerifier + public class Asn1VerifierFactory: IVerifierFactory { private readonly AlgorithmIdentifier algID; private readonly AsymmetricKeyParameter publicKey; @@ -451,7 +447,7 @@ namespace Org.BouncyCastle.Crypto.Operators /// </summary> /// <param name="algorithm">The name of the signature algorithm to use.</param> /// <param name="publicKey">The public key to be used in the verification operation.</param> - public Asn1SignatureVerifier (String algorithm, AsymmetricKeyParameter publicKey) + public Asn1VerifierFactory (String algorithm, AsymmetricKeyParameter publicKey) { DerObjectIdentifier sigOid = X509Utilities.GetAlgorithmOid (algorithm); @@ -459,7 +455,7 @@ namespace Org.BouncyCastle.Crypto.Operators this.algID = X509Utilities.GetSigAlgID (sigOid, algorithm); } - public Asn1SignatureVerifier (AlgorithmIdentifier algorithm, AsymmetricKeyParameter publicKey) + public Asn1VerifierFactory (AlgorithmIdentifier algorithm, AsymmetricKeyParameter publicKey) { this.publicKey = publicKey; this.algID = algorithm; @@ -529,7 +525,7 @@ namespace Org.BouncyCastle.Crypto.Operators /// <summary> /// Provider class which supports dynamic creation of signature verifiers. /// </summary> - public class Asn1SignatureVerifierProvider: ISignatureVerifierProvider + public class Asn1VerifierFactoryProvider: IVerifierFactoryProvider { private readonly AsymmetricKeyParameter publicKey; @@ -537,14 +533,14 @@ namespace Org.BouncyCastle.Crypto.Operators /// Base constructor - specify the public key to be used in verification. /// </summary> /// <param name="publicKey">The public key to be used in creating verifiers provided by this object.</param> - public Asn1SignatureVerifierProvider(AsymmetricKeyParameter publicKey) + public Asn1VerifierFactoryProvider(AsymmetricKeyParameter publicKey) { this.publicKey = publicKey; } - public ISignatureVerifier CreateSignatureVerifier(Object algorithmDetails) + public IVerifierFactory CreateVerifierFactory(Object algorithmDetails) { - return new Asn1SignatureVerifier ((AlgorithmIdentifier)algorithmDetails, publicKey); + return new Asn1VerifierFactory ((AlgorithmIdentifier)algorithmDetails, publicKey); } /// <summary> diff --git a/crypto/src/crypto/parameters/DesEdeParameters.cs b/crypto/src/crypto/parameters/DesEdeParameters.cs
index 420aaecea..6be56fb2c 100644 --- a/crypto/src/crypto/parameters/DesEdeParameters.cs +++ b/crypto/src/crypto/parameters/DesEdeParameters.cs
@@ -91,5 +91,50 @@ namespace Org.BouncyCastle.Crypto.Parameters { return IsWeakKey(key, 0, key.Length); } + + /** + * return true if the passed in key is a real 2/3 part DES-EDE key. + * + * @param key bytes making up the key + * @param offset offset into the byte array the key starts at + */ + public static bool IsRealEdeKey(byte[] key, int offset) + { + return key.Length == 16 ? IsReal2Key(key, offset) : IsReal3Key(key, offset); + } + + /** + * return true if the passed in key is a real 2 part DES-EDE key. + * + * @param key bytes making up the key + * @param offset offset into the byte array the key starts at + */ + public static bool IsReal2Key(byte[] key, int offset) + { + bool isValid = false; + for (int i = offset; i != offset + 8; i++) + { + isValid |= (key[i] != key[i + 8]); + } + return isValid; + } + + /** + * return true if the passed in key is a real 3 part DES-EDE key. + * + * @param key bytes making up the key + * @param offset offset into the byte array the key starts at + */ + public static bool IsReal3Key(byte[] key, int offset) + { + bool diff12 = false, diff13 = false, diff23 = false; + for (int i = offset; i != offset + 8; i++) + { + diff12 |= (key[i] != key[i + 8]); + diff13 |= (key[i] != key[i + 16]); + diff23 |= (key[i + 8] != key[i + 16]); + } + return diff12 && diff13 && diff23; + } } } diff --git a/crypto/src/crypto/parameters/DesParameters.cs b/crypto/src/crypto/parameters/DesParameters.cs
index ee37cd861..a1f67e2b1 100644 --- a/crypto/src/crypto/parameters/DesParameters.cs +++ b/crypto/src/crypto/parameters/DesParameters.cs
@@ -103,28 +103,37 @@ namespace Org.BouncyCastle.Crypto.Parameters return IsWeakKey(key, 0); } - /** + public static byte SetOddParity(byte b) + { + uint parity = b ^ 1U; + parity ^= (parity >> 4); + parity ^= (parity >> 2); + parity ^= (parity >> 1); + parity &= 1U; + + return (byte)(b ^ parity); + } + + /** * DES Keys use the LSB as the odd parity bit. This can * be used to check for corrupt keys. * * @param bytes the byte array to set the parity on. */ - public static void SetOddParity( - byte[] bytes) + public static void SetOddParity(byte[] bytes) { for (int i = 0; i < bytes.Length; i++) { - int b = bytes[i]; - bytes[i] = (byte)((b & 0xfe) | - ((((b >> 1) ^ - (b >> 2) ^ - (b >> 3) ^ - (b >> 4) ^ - (b >> 5) ^ - (b >> 6) ^ - (b >> 7)) ^ 0x01) & 0x01)); + bytes[i] = SetOddParity(bytes[i]); } } - } + public static void SetOddParity(byte[] bytes, int off, int len) + { + for (int i = 0; i < len; i++) + { + bytes[off + i] = SetOddParity(bytes[off + i]); + } + } + } } diff --git a/crypto/src/crypto/parameters/ParametersWithRandom.cs b/crypto/src/crypto/parameters/ParametersWithRandom.cs
index a05e77409..276dc2666 100644 --- a/crypto/src/crypto/parameters/ParametersWithRandom.cs +++ b/crypto/src/crypto/parameters/ParametersWithRandom.cs
@@ -15,7 +15,7 @@ namespace Org.BouncyCastle.Crypto.Parameters SecureRandom random) { if (parameters == null) - throw new ArgumentNullException("random"); + throw new ArgumentNullException("parameters"); if (random == null) throw new ArgumentNullException("random"); diff --git a/crypto/src/crypto/parameters/SkeinParameters.cs b/crypto/src/crypto/parameters/SkeinParameters.cs
index 9e621c09d..cc57ef5ff 100644 --- a/crypto/src/crypto/parameters/SkeinParameters.cs +++ b/crypto/src/crypto/parameters/SkeinParameters.cs
@@ -240,7 +240,7 @@ namespace Org.BouncyCastle.Crypto.Parameters outBytes.Write(emailAddress); outBytes.Write(" "); outBytes.Write(distinguisher); - outBytes.Close(); + Platform.Dispose(outBytes); return Set(PARAM_TYPE_PERSONALISATION, bout.ToArray()); } catch (IOException e) diff --git a/crypto/src/crypto/prng/BasicEntropySourceProvider.cs b/crypto/src/crypto/prng/BasicEntropySourceProvider.cs new file mode 100644
index 000000000..31a8461f0 --- /dev/null +++ b/crypto/src/crypto/prng/BasicEntropySourceProvider.cs
@@ -0,0 +1,71 @@ +using System; + +using Org.BouncyCastle.Security; + +namespace Org.BouncyCastle.Crypto.Prng +{ + /** + * An EntropySourceProvider where entropy generation is based on a SecureRandom output using SecureRandom.generateSeed(). + */ + public class BasicEntropySourceProvider + : IEntropySourceProvider + { + private readonly SecureRandom mSecureRandom; + private readonly bool mPredictionResistant; + + /** + * Create a entropy source provider based on the passed in SecureRandom. + * + * @param secureRandom the SecureRandom to base EntropySource construction on. + * @param isPredictionResistant boolean indicating if the SecureRandom is based on prediction resistant entropy or not (true if it is). + */ + public BasicEntropySourceProvider(SecureRandom secureRandom, bool isPredictionResistant) + { + mSecureRandom = secureRandom; + mPredictionResistant = isPredictionResistant; + } + + /** + * Return an entropy source that will create bitsRequired bits of entropy on + * each invocation of getEntropy(). + * + * @param bitsRequired size (in bits) of entropy to be created by the provided source. + * @return an EntropySource that generates bitsRequired bits of entropy on each call to its getEntropy() method. + */ + public IEntropySource Get(int bitsRequired) + { + return new BasicEntropySource(mSecureRandom, mPredictionResistant, bitsRequired); + } + + private class BasicEntropySource + : IEntropySource + { + private readonly SecureRandom mSecureRandom; + private readonly bool mPredictionResistant; + private readonly int mEntropySize; + + internal BasicEntropySource(SecureRandom secureRandom, bool predictionResistant, int entropySize) + { + this.mSecureRandom = secureRandom; + this.mPredictionResistant = predictionResistant; + this.mEntropySize = entropySize; + } + + bool IEntropySource.IsPredictionResistant + { + get { return mPredictionResistant; } + } + + byte[] IEntropySource.GetEntropy() + { + // TODO[FIPS] Not all SecureRandom implementations are considered valid entropy sources + return SecureRandom.GetNextBytes(mSecureRandom, (mEntropySize + 7) / 8); + } + + int IEntropySource.EntropySize + { + get { return mEntropySize; } + } + } + } +} diff --git a/crypto/src/crypto/prng/CryptoApiEntropySourceProvider.cs b/crypto/src/crypto/prng/CryptoApiEntropySourceProvider.cs new file mode 100644
index 000000000..68579aaf4 --- /dev/null +++ b/crypto/src/crypto/prng/CryptoApiEntropySourceProvider.cs
@@ -0,0 +1,70 @@ +#if !(NETCF_1_0 || PORTABLE) +using System; +using System.Security.Cryptography; + +namespace Org.BouncyCastle.Crypto.Prng +{ + public class CryptoApiEntropySourceProvider + : IEntropySourceProvider + { + private readonly RandomNumberGenerator mRng; + private readonly bool mPredictionResistant; + + public CryptoApiEntropySourceProvider() + : this(new RNGCryptoServiceProvider(), true) + { + } + + public CryptoApiEntropySourceProvider(RandomNumberGenerator rng, bool isPredictionResistant) + { + if (rng == null) + throw new ArgumentNullException("rng"); + + mRng = rng; + mPredictionResistant = isPredictionResistant; + } + + public IEntropySource Get(int bitsRequired) + { + return new CryptoApiEntropySource(mRng, mPredictionResistant, bitsRequired); + } + + private class CryptoApiEntropySource + : IEntropySource + { + private readonly RandomNumberGenerator mRng; + private readonly bool mPredictionResistant; + private readonly int mEntropySize; + + internal CryptoApiEntropySource(RandomNumberGenerator rng, bool predictionResistant, int entropySize) + { + this.mRng = rng; + this.mPredictionResistant = predictionResistant; + this.mEntropySize = entropySize; + } + + #region IEntropySource Members + + bool IEntropySource.IsPredictionResistant + { + get { return mPredictionResistant; } + } + + byte[] IEntropySource.GetEntropy() + { + byte[] result = new byte[(mEntropySize + 7) / 8]; + mRng.GetBytes(result); + return result; + } + + int IEntropySource.EntropySize + { + get { return mEntropySize; } + } + + #endregion + } + } +} + +#endif diff --git a/crypto/src/crypto/prng/DigestRandomGenerator.cs b/crypto/src/crypto/prng/DigestRandomGenerator.cs
index cbd2ef060..f5a29952a 100644 --- a/crypto/src/crypto/prng/DigestRandomGenerator.cs +++ b/crypto/src/crypto/prng/DigestRandomGenerator.cs
@@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Crypto.Digests; +using Org.BouncyCastle.Crypto.Utilities; namespace Org.BouncyCastle.Crypto.Prng { @@ -108,15 +109,12 @@ namespace Org.BouncyCastle.Crypto.Prng private void DigestAddCounter(long seedVal) { - ulong seed = (ulong)seedVal; - for (int i = 0; i != 8; i++) - { - digest.Update((byte)seed); - seed >>= 8; - } + byte[] bytes = new byte[8]; + Pack.UInt64_To_LE((ulong)seedVal, bytes); + digest.BlockUpdate(bytes, 0, bytes.Length); } - private void DigestUpdate(byte[] inSeed) + private void DigestUpdate(byte[] inSeed) { digest.BlockUpdate(inSeed, 0, inSeed.Length); } diff --git a/crypto/src/crypto/prng/EntropyUtilities.cs b/crypto/src/crypto/prng/EntropyUtilities.cs new file mode 100644
index 000000000..58c8703f4 --- /dev/null +++ b/crypto/src/crypto/prng/EntropyUtilities.cs
@@ -0,0 +1,30 @@ +using System; + +using Org.BouncyCastle.Security; + +namespace Org.BouncyCastle.Crypto.Prng +{ + public abstract class EntropyUtilities + { + /** + * Generate numBytes worth of entropy from the passed in entropy source. + * + * @param entropySource the entropy source to request the data from. + * @param numBytes the number of bytes of entropy requested. + * @return a byte array populated with the random data. + */ + public static byte[] GenerateSeed(IEntropySource entropySource, int numBytes) + { + byte[] bytes = new byte[numBytes]; + int count = 0; + while (count < numBytes) + { + byte[] entropy = entropySource.GetEntropy(); + int toCopy = System.Math.Min(bytes.Length, numBytes - count); + Array.Copy(entropy, 0, bytes, count, toCopy); + count += toCopy; + } + return bytes; + } + } +} diff --git a/crypto/src/crypto/prng/IDrbgProvider.cs b/crypto/src/crypto/prng/IDrbgProvider.cs new file mode 100644
index 000000000..5ebf5fd8d --- /dev/null +++ b/crypto/src/crypto/prng/IDrbgProvider.cs
@@ -0,0 +1,11 @@ +using System; + +using Org.BouncyCastle.Crypto.Prng.Drbg; + +namespace Org.BouncyCastle.Crypto.Prng +{ + internal interface IDrbgProvider + { + ISP80090Drbg Get(IEntropySource entropySource); + } +} diff --git a/crypto/src/crypto/prng/SP800SecureRandom.cs b/crypto/src/crypto/prng/SP800SecureRandom.cs new file mode 100644
index 000000000..5c5bda399 --- /dev/null +++ b/crypto/src/crypto/prng/SP800SecureRandom.cs
@@ -0,0 +1,80 @@ +using System; + +using Org.BouncyCastle.Crypto.Prng.Drbg; +using Org.BouncyCastle.Security; + +namespace Org.BouncyCastle.Crypto.Prng +{ + public class SP800SecureRandom + : SecureRandom + { + private readonly IDrbgProvider mDrbgProvider; + private readonly bool mPredictionResistant; + private readonly SecureRandom mRandomSource; + private readonly IEntropySource mEntropySource; + + private ISP80090Drbg mDrbg; + + internal SP800SecureRandom(SecureRandom randomSource, IEntropySource entropySource, IDrbgProvider drbgProvider, bool predictionResistant) + : base((IRandomGenerator)null) + { + this.mRandomSource = randomSource; + this.mEntropySource = entropySource; + this.mDrbgProvider = drbgProvider; + this.mPredictionResistant = predictionResistant; + } + + public override void SetSeed(byte[] seed) + { + lock (this) + { + if (mRandomSource != null) + { + this.mRandomSource.SetSeed(seed); + } + } + } + + public override void SetSeed(long seed) + { + lock (this) + { + // this will happen when SecureRandom() is created + if (mRandomSource != null) + { + this.mRandomSource.SetSeed(seed); + } + } + } + + public override void NextBytes(byte[] bytes) + { + lock (this) + { + if (mDrbg == null) + { + mDrbg = mDrbgProvider.Get(mEntropySource); + } + + // check if a reseed is required... + if (mDrbg.Generate(bytes, null, mPredictionResistant) < 0) + { + mDrbg.Reseed(null); + mDrbg.Generate(bytes, null, mPredictionResistant); + } + } + } + + public override void NextBytes(byte[] buf, int off, int len) + { + byte[] bytes = new byte[len]; + NextBytes(bytes); + Array.Copy(bytes, 0, buf, off, len); + } + + public override byte[] GenerateSeed(int numBytes) + { + return EntropyUtilities.GenerateSeed(mEntropySource, numBytes); + } + } +} diff --git a/crypto/src/crypto/prng/SP800SecureRandomBuilder.cs b/crypto/src/crypto/prng/SP800SecureRandomBuilder.cs new file mode 100644
index 000000000..7199f1ae7 --- /dev/null +++ b/crypto/src/crypto/prng/SP800SecureRandomBuilder.cs
@@ -0,0 +1,208 @@ +using System; + +using Org.BouncyCastle.Crypto.Prng.Drbg; +using Org.BouncyCastle.Security; + +namespace Org.BouncyCastle.Crypto.Prng +{ + /** + * Builder class for making SecureRandom objects based on SP 800-90A Deterministic Random Bit Generators (DRBG). + */ + public class SP800SecureRandomBuilder + { + private readonly SecureRandom mRandom; + private readonly IEntropySourceProvider mEntropySourceProvider; + + private byte[] mPersonalizationString = null; + private int mSecurityStrength = 256; + private int mEntropyBitsRequired = 256; + + /** + * Basic constructor, creates a builder using an EntropySourceProvider based on the default SecureRandom with + * predictionResistant set to false. + * <p> + * Any SecureRandom created from a builder constructed like this will make use of input passed to SecureRandom.setSeed() if + * the default SecureRandom does for its generateSeed() call. + * </p> + */ + public SP800SecureRandomBuilder() + : this(new SecureRandom(), false) + { + } + + /** + * Construct a builder with an EntropySourceProvider based on the passed in SecureRandom and the passed in value + * for prediction resistance. + * <p> + * Any SecureRandom created from a builder constructed like this will make use of input passed to SecureRandom.setSeed() if + * the passed in SecureRandom does for its generateSeed() call. + * </p> + * @param entropySource + * @param predictionResistant + */ + public SP800SecureRandomBuilder(SecureRandom entropySource, bool predictionResistant) + { + this.mRandom = entropySource; + this.mEntropySourceProvider = new BasicEntropySourceProvider(entropySource, predictionResistant); + } + + /** + * Create a builder which makes creates the SecureRandom objects from a specified entropy source provider. + * <p> + * <b>Note:</b> If this constructor is used any calls to setSeed() in the resulting SecureRandom will be ignored. + * </p> + * @param entropySourceProvider a provider of EntropySource objects. + */ + public SP800SecureRandomBuilder(IEntropySourceProvider entropySourceProvider) + { + this.mRandom = null; + this.mEntropySourceProvider = entropySourceProvider; + } + + /** + * Set the personalization string for DRBG SecureRandoms created by this builder + * @param personalizationString the personalisation string for the underlying DRBG. + * @return the current builder. + */ + public SP800SecureRandomBuilder SetPersonalizationString(byte[] personalizationString) + { + this.mPersonalizationString = personalizationString; + return this; + } + + /** + * Set the security strength required for DRBGs used in building SecureRandom objects. + * + * @param securityStrength the security strength (in bits) + * @return the current builder. + */ + public SP800SecureRandomBuilder SetSecurityStrength(int securityStrength) + { + this.mSecurityStrength = securityStrength; + return this; + } + + /** + * Set the amount of entropy bits required for seeding and reseeding DRBGs used in building SecureRandom objects. + * + * @param entropyBitsRequired the number of bits of entropy to be requested from the entropy source on each seed/reseed. + * @return the current builder. + */ + public SP800SecureRandomBuilder SetEntropyBitsRequired(int entropyBitsRequired) + { + this.mEntropyBitsRequired = entropyBitsRequired; + return this; + } + + /** + * Build a SecureRandom based on a SP 800-90A Hash DRBG. + * + * @param digest digest algorithm to use in the DRBG underneath the SecureRandom. + * @param nonce nonce value to use in DRBG construction. + * @param predictionResistant specify whether the underlying DRBG in the resulting SecureRandom should reseed on each request for bytes. + * @return a SecureRandom supported by a Hash DRBG. + */ + public SP800SecureRandom BuildHash(IDigest digest, byte[] nonce, bool predictionResistant) + { + return new SP800SecureRandom(mRandom, mEntropySourceProvider.Get(mEntropyBitsRequired), + new HashDrbgProvider(digest, nonce, mPersonalizationString, mSecurityStrength), predictionResistant); + } + + /** + * Build a SecureRandom based on a SP 800-90A CTR DRBG. + * + * @param cipher the block cipher to base the DRBG on. + * @param keySizeInBits key size in bits to be used with the block cipher. + * @param nonce nonce value to use in DRBG construction. + * @param predictionResistant specify whether the underlying DRBG in the resulting SecureRandom should reseed on each request for bytes. + * @return a SecureRandom supported by a CTR DRBG. + */ + public SP800SecureRandom BuildCtr(IBlockCipher cipher, int keySizeInBits, byte[] nonce, bool predictionResistant) + { + return new SP800SecureRandom(mRandom, mEntropySourceProvider.Get(mEntropyBitsRequired), + new CtrDrbgProvider(cipher, keySizeInBits, nonce, mPersonalizationString, mSecurityStrength), predictionResistant); + } + + /** + * Build a SecureRandom based on a SP 800-90A HMAC DRBG. + * + * @param hMac HMAC algorithm to use in the DRBG underneath the SecureRandom. + * @param nonce nonce value to use in DRBG construction. + * @param predictionResistant specify whether the underlying DRBG in the resulting SecureRandom should reseed on each request for bytes. + * @return a SecureRandom supported by a HMAC DRBG. + */ + public SP800SecureRandom BuildHMac(IMac hMac, byte[] nonce, bool predictionResistant) + { + return new SP800SecureRandom(mRandom, mEntropySourceProvider.Get(mEntropyBitsRequired), + new HMacDrbgProvider(hMac, nonce, mPersonalizationString, mSecurityStrength), predictionResistant); + } + + private class HashDrbgProvider + : IDrbgProvider + { + private readonly IDigest mDigest; + private readonly byte[] mNonce; + private readonly byte[] mPersonalizationString; + private readonly int mSecurityStrength; + + public HashDrbgProvider(IDigest digest, byte[] nonce, byte[] personalizationString, int securityStrength) + { + this.mDigest = digest; + this.mNonce = nonce; + this.mPersonalizationString = personalizationString; + this.mSecurityStrength = securityStrength; + } + + public ISP80090Drbg Get(IEntropySource entropySource) + { + return new HashSP800Drbg(mDigest, mSecurityStrength, entropySource, mPersonalizationString, mNonce); + } + } + + private class HMacDrbgProvider + : IDrbgProvider + { + private readonly IMac mHMac; + private readonly byte[] mNonce; + private readonly byte[] mPersonalizationString; + private readonly int mSecurityStrength; + + public HMacDrbgProvider(IMac hMac, byte[] nonce, byte[] personalizationString, int securityStrength) + { + this.mHMac = hMac; + this.mNonce = nonce; + this.mPersonalizationString = personalizationString; + this.mSecurityStrength = securityStrength; + } + + public ISP80090Drbg Get(IEntropySource entropySource) + { + return new HMacSP800Drbg(mHMac, mSecurityStrength, entropySource, mPersonalizationString, mNonce); + } + } + + private class CtrDrbgProvider + : IDrbgProvider + { + private readonly IBlockCipher mBlockCipher; + private readonly int mKeySizeInBits; + private readonly byte[] mNonce; + private readonly byte[] mPersonalizationString; + private readonly int mSecurityStrength; + + public CtrDrbgProvider(IBlockCipher blockCipher, int keySizeInBits, byte[] nonce, byte[] personalizationString, int securityStrength) + { + this.mBlockCipher = blockCipher; + this.mKeySizeInBits = keySizeInBits; + this.mNonce = nonce; + this.mPersonalizationString = personalizationString; + this.mSecurityStrength = securityStrength; + } + + public ISP80090Drbg Get(IEntropySource entropySource) + { + return new CtrSP800Drbg(mBlockCipher, mKeySizeInBits, mSecurityStrength, entropySource, mPersonalizationString, mNonce); + } + } + } +} diff --git a/crypto/src/crypto/prng/ThreadedSeedGenerator.cs b/crypto/src/crypto/prng/ThreadedSeedGenerator.cs
index f6a6b3c54..0a38e5f5a 100644 --- a/crypto/src/crypto/prng/ThreadedSeedGenerator.cs +++ b/crypto/src/crypto/prng/ThreadedSeedGenerator.cs
@@ -1,39 +1,43 @@ using System; using System.Threading; +#if NO_THREADS +using System.Threading.Tasks; +#endif + namespace Org.BouncyCastle.Crypto.Prng { - /** - * A thread based seed generator - one source of randomness. - * <p> - * Based on an idea from Marcus Lippert. - * </p> - */ - public class ThreadedSeedGenerator - { - private class SeedGenerator - { + /** + * A thread based seed generator - one source of randomness. + * <p> + * Based on an idea from Marcus Lippert. + * </p> + */ + public class ThreadedSeedGenerator + { + private class SeedGenerator + { #if NETCF_1_0 // No volatile keyword, but all fields implicitly volatile anyway private int counter = 0; private bool stop = false; #else - private volatile int counter = 0; - private volatile bool stop = false; + private volatile int counter = 0; + private volatile bool stop = false; #endif - private void Run(object ignored) - { - while (!this.stop) - { - this.counter++; - } - } + private void Run(object ignored) + { + while (!this.stop) + { + this.counter++; + } + } - public byte[] GenerateSeed( - int numBytes, - bool fast) - { + public byte[] GenerateSeed( + int numBytes, + bool fast) + { #if SILVERLIGHT || PORTABLE return DoGenerateSeed(numBytes, fast); #else @@ -51,71 +55,75 @@ namespace Org.BouncyCastle.Crypto.Prng } private byte[] DoGenerateSeed( - int numBytes, - bool fast) + int numBytes, + bool fast) { this.counter = 0; - this.stop = false; + this.stop = false; - byte[] result = new byte[numBytes]; - int last = 0; - int end = fast ? numBytes : numBytes * 8; + byte[] result = new byte[numBytes]; + int last = 0; + int end = fast ? numBytes : numBytes * 8; - ThreadPool.QueueUserWorkItem(new WaitCallback(Run)); +#if NO_THREADS + Task.Factory.StartNew(() => Run(null), TaskCreationOptions.None); +#else + ThreadPool.QueueUserWorkItem(new WaitCallback(Run)); +#endif - for (int i = 0; i < end; i++) - { - while (this.counter == last) - { - try - { + for (int i = 0; i < end; i++) + { + while (this.counter == last) + { + try + { #if PORTABLE new AutoResetEvent(false).WaitOne(1); #else - Thread.Sleep(1); + Thread.Sleep(1); #endif - } - catch (Exception) - { - // ignore - } - } + } + catch (Exception) + { + // ignore + } + } - last = this.counter; + last = this.counter; - if (fast) - { - result[i] = (byte) last; - } - else - { - int bytepos = i / 8; - result[bytepos] = (byte) ((result[bytepos] << 1) | (last & 1)); - } - } + if (fast) + { + result[i] = (byte)last; + } + else + { + int bytepos = i / 8; + result[bytepos] = (byte)((result[bytepos] << 1) | (last & 1)); + } + } - this.stop = true; + this.stop = true; - return result; - } - } + return result; + } + } - /** - * Generate seed bytes. Set fast to false for best quality. - * <p> - * If fast is set to true, the code should be round about 8 times faster when - * generating a long sequence of random bytes. 20 bytes of random values using - * the fast mode take less than half a second on a Nokia e70. If fast is set to false, - * it takes round about 2500 ms. - * </p> - * @param numBytes the number of bytes to generate - * @param fast true if fast mode should be used - */ - public byte[] GenerateSeed( - int numBytes, - bool fast) - { - return new SeedGenerator().GenerateSeed(numBytes, fast); - } - } + /** + * Generate seed bytes. Set fast to false for best quality. + * <p> + * If fast is set to true, the code should be round about 8 times faster when + * generating a long sequence of random bytes. 20 bytes of random values using + * the fast mode take less than half a second on a Nokia e70. If fast is set to false, + * it takes round about 2500 ms. + * </p> + * @param numBytes the number of bytes to generate + * @param fast true if fast mode should be used + */ + public byte[] GenerateSeed( + int numBytes, + bool fast) + { + return new SeedGenerator().GenerateSeed(numBytes, fast); + } + } } diff --git a/crypto/src/crypto/prng/X931Rng.cs b/crypto/src/crypto/prng/X931Rng.cs new file mode 100644
index 000000000..2bd8e0c6b --- /dev/null +++ b/crypto/src/crypto/prng/X931Rng.cs
@@ -0,0 +1,146 @@ +using System; + +namespace Org.BouncyCastle.Crypto.Prng +{ + internal class X931Rng + { + private const long BLOCK64_RESEED_MAX = 1L << (16 - 1); + private const long BLOCK128_RESEED_MAX = 1L << (24 - 1); + private const int BLOCK64_MAX_BITS_REQUEST = 1 << (13 - 1); + private const int BLOCK128_MAX_BITS_REQUEST = 1 << (19 - 1); + + private readonly IBlockCipher mEngine; + private readonly IEntropySource mEntropySource; + + private readonly byte[] mDT; + private readonly byte[] mI; + private readonly byte[] mR; + + private byte[] mV; + + private long mReseedCounter = 1; + + /** + * + * @param engine + * @param entropySource + */ + internal X931Rng(IBlockCipher engine, byte[] dateTimeVector, IEntropySource entropySource) + { + this.mEngine = engine; + this.mEntropySource = entropySource; + + this.mDT = new byte[engine.GetBlockSize()]; + + Array.Copy(dateTimeVector, 0, mDT, 0, mDT.Length); + + this.mI = new byte[engine.GetBlockSize()]; + this.mR = new byte[engine.GetBlockSize()]; + } + + /** + * Populate a passed in array with random data. + * + * @param output output array for generated bits. + * @param predictionResistant true if a reseed should be forced, false otherwise. + * + * @return number of bits generated, -1 if a reseed required. + */ + internal int Generate(byte[] output, bool predictionResistant) + { + if (mR.Length == 8) // 64 bit block size + { + if (mReseedCounter > BLOCK64_RESEED_MAX) + return -1; + + if (IsTooLarge(output, BLOCK64_MAX_BITS_REQUEST / 8)) + throw new ArgumentException("Number of bits per request limited to " + BLOCK64_MAX_BITS_REQUEST, "output"); + } + else + { + if (mReseedCounter > BLOCK128_RESEED_MAX) + return -1; + + if (IsTooLarge(output, BLOCK128_MAX_BITS_REQUEST / 8)) + throw new ArgumentException("Number of bits per request limited to " + BLOCK128_MAX_BITS_REQUEST, "output"); + } + + if (predictionResistant || mV == null) + { + mV = mEntropySource.GetEntropy(); + if (mV.Length != mEngine.GetBlockSize()) + throw new InvalidOperationException("Insufficient entropy returned"); + } + + int m = output.Length / mR.Length; + + for (int i = 0; i < m; i++) + { + mEngine.ProcessBlock(mDT, 0, mI, 0); + Process(mR, mI, mV); + Process(mV, mR, mI); + + Array.Copy(mR, 0, output, i * mR.Length, mR.Length); + + Increment(mDT); + } + + int bytesToCopy = (output.Length - m * mR.Length); + + if (bytesToCopy > 0) + { + mEngine.ProcessBlock(mDT, 0, mI, 0); + Process(mR, mI, mV); + Process(mV, mR, mI); + + Array.Copy(mR, 0, output, m * mR.Length, bytesToCopy); + + Increment(mDT); + } + + mReseedCounter++; + + return output.Length; + } + + /** + * Reseed the RNG. + */ + internal void Reseed() + { + mV = mEntropySource.GetEntropy(); + if (mV.Length != mEngine.GetBlockSize()) + throw new InvalidOperationException("Insufficient entropy returned"); + mReseedCounter = 1; + } + + internal IEntropySource EntropySource + { + get { return mEntropySource; } + } + + private void Process(byte[] res, byte[] a, byte[] b) + { + for (int i = 0; i != res.Length; i++) + { + res[i] = (byte)(a[i] ^ b[i]); + } + + mEngine.ProcessBlock(res, 0, res, 0); + } + + private void Increment(byte[] val) + { + for (int i = val.Length - 1; i >= 0; i--) + { + if (++val[i] != 0) + break; + } + } + + private static bool IsTooLarge(byte[] bytes, int maxBytes) + { + return bytes != null && bytes.Length > maxBytes; + } + } +} diff --git a/crypto/src/crypto/prng/X931SecureRandom.cs b/crypto/src/crypto/prng/X931SecureRandom.cs new file mode 100644
index 000000000..d2e4849c5 --- /dev/null +++ b/crypto/src/crypto/prng/X931SecureRandom.cs
@@ -0,0 +1,70 @@ +using System; + +using Org.BouncyCastle.Security; + +namespace Org.BouncyCastle.Crypto.Prng +{ + public class X931SecureRandom + : SecureRandom + { + private readonly bool mPredictionResistant; + private readonly SecureRandom mRandomSource; + private readonly X931Rng mDrbg; + + internal X931SecureRandom(SecureRandom randomSource, X931Rng drbg, bool predictionResistant) + : base((IRandomGenerator)null) + { + this.mRandomSource = randomSource; + this.mDrbg = drbg; + this.mPredictionResistant = predictionResistant; + } + + public override void SetSeed(byte[] seed) + { + lock (this) + { + if (mRandomSource != null) + { + this.mRandomSource.SetSeed(seed); + } + } + } + + public override void SetSeed(long seed) + { + lock (this) + { + // this will happen when SecureRandom() is created + if (mRandomSource != null) + { + this.mRandomSource.SetSeed(seed); + } + } + } + + public override void NextBytes(byte[] bytes) + { + lock (this) + { + // check if a reseed is required... + if (mDrbg.Generate(bytes, mPredictionResistant) < 0) + { + mDrbg.Reseed(); + mDrbg.Generate(bytes, mPredictionResistant); + } + } + } + + public override void NextBytes(byte[] buf, int off, int len) + { + byte[] bytes = new byte[len]; + NextBytes(bytes); + Array.Copy(bytes, 0, buf, off, len); + } + + public override byte[] GenerateSeed(int numBytes) + { + return EntropyUtilities.GenerateSeed(mDrbg.EntropySource, numBytes); + } + } +} diff --git a/crypto/src/crypto/prng/X931SecureRandomBuilder.cs b/crypto/src/crypto/prng/X931SecureRandomBuilder.cs new file mode 100644
index 000000000..31e94312e --- /dev/null +++ b/crypto/src/crypto/prng/X931SecureRandomBuilder.cs
@@ -0,0 +1,87 @@ +using System; + +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Crypto.Utilities; +using Org.BouncyCastle.Security; +using Org.BouncyCastle.Utilities.Date; + +namespace Org.BouncyCastle.Crypto.Prng +{ + public class X931SecureRandomBuilder + { + private readonly SecureRandom mRandom; // JDK 1.1 complains on final. + + private IEntropySourceProvider mEntropySourceProvider; + private byte[] mDateTimeVector; + + /** + * Basic constructor, creates a builder using an EntropySourceProvider based on the default SecureRandom with + * predictionResistant set to false. + * <p> + * Any SecureRandom created from a builder constructed like this will make use of input passed to SecureRandom.setSeed() if + * the default SecureRandom does for its generateSeed() call. + * </p> + */ + public X931SecureRandomBuilder() + : this(new SecureRandom(), false) + { + } + + /** + * Construct a builder with an EntropySourceProvider based on the passed in SecureRandom and the passed in value + * for prediction resistance. + * <p> + * Any SecureRandom created from a builder constructed like this will make use of input passed to SecureRandom.setSeed() if + * the passed in SecureRandom does for its generateSeed() call. + * </p> + * @param entropySource + * @param predictionResistant + */ + public X931SecureRandomBuilder(SecureRandom entropySource, bool predictionResistant) + { + this.mRandom = entropySource; + this.mEntropySourceProvider = new BasicEntropySourceProvider(mRandom, predictionResistant); + } + + /** + * Create a builder which makes creates the SecureRandom objects from a specified entropy source provider. + * <p> + * <b>Note:</b> If this constructor is used any calls to setSeed() in the resulting SecureRandom will be ignored. + * </p> + * @param entropySourceProvider a provider of EntropySource objects. + */ + public X931SecureRandomBuilder(IEntropySourceProvider entropySourceProvider) + { + this.mRandom = null; + this.mEntropySourceProvider = entropySourceProvider; + } + + public X931SecureRandomBuilder SetDateTimeVector(byte[] dateTimeVector) + { + this.mDateTimeVector = dateTimeVector; + return this; + } + + /** + * Construct a X9.31 secure random generator using the passed in engine and key. If predictionResistant is true the + * generator will be reseeded on each request. + * + * @param engine a block cipher to use as the operator. + * @param key the block cipher key to initialise engine with. + * @param predictionResistant true if engine to be reseeded on each use, false otherwise. + * @return a SecureRandom. + */ + public X931SecureRandom Build(IBlockCipher engine, KeyParameter key, bool predictionResistant) + { + if (mDateTimeVector == null) + { + mDateTimeVector = new byte[engine.GetBlockSize()]; + Pack.UInt64_To_BE((ulong)DateTimeUtilities.CurrentUnixMs(), mDateTimeVector, 0); + } + + engine.Init(true, key); + + return new X931SecureRandom(mRandom, new X931Rng(engine, mDateTimeVector, mEntropySourceProvider.Get(engine.GetBlockSize() * 8)), predictionResistant); + } + } +} diff --git a/crypto/src/crypto/prng/drbg/CtrSP800Drbg.cs b/crypto/src/crypto/prng/drbg/CtrSP800Drbg.cs new file mode 100644
index 000000000..eca1821d3 --- /dev/null +++ b/crypto/src/crypto/prng/drbg/CtrSP800Drbg.cs
@@ -0,0 +1,466 @@ +using System; + +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Utilities; +using Org.BouncyCastle.Utilities.Encoders; + +namespace Org.BouncyCastle.Crypto.Prng.Drbg +{ + /** + * A SP800-90A CTR DRBG. + */ + public class CtrSP800Drbg + : ISP80090Drbg + { + private static readonly long TDEA_RESEED_MAX = 1L << (32 - 1); + private static readonly long AES_RESEED_MAX = 1L << (48 - 1); + private static readonly int TDEA_MAX_BITS_REQUEST = 1 << (13 - 1); + private static readonly int AES_MAX_BITS_REQUEST = 1 << (19 - 1); + + private readonly IEntropySource mEntropySource; + private readonly IBlockCipher mEngine; + private readonly int mKeySizeInBits; + private readonly int mSeedLength; + private readonly int mSecurityStrength; + + // internal state + private byte[] mKey; + private byte[] mV; + private long mReseedCounter = 0; + private bool mIsTdea = false; + + /** + * Construct a SP800-90A CTR DRBG. + * <p> + * Minimum entropy requirement is the security strength requested. + * </p> + * @param engine underlying block cipher to use to support DRBG + * @param keySizeInBits size of the key to use with the block cipher. + * @param securityStrength security strength required (in bits) + * @param entropySource source of entropy to use for seeding/reseeding. + * @param personalizationString personalization string to distinguish this DRBG (may be null). + * @param nonce nonce to further distinguish this DRBG (may be null). + */ + public CtrSP800Drbg(IBlockCipher engine, int keySizeInBits, int securityStrength, IEntropySource entropySource, + byte[] personalizationString, byte[] nonce) + { + if (securityStrength > 256) + throw new ArgumentException("Requested security strength is not supported by the derivation function"); + if (GetMaxSecurityStrength(engine, keySizeInBits) < securityStrength) + throw new ArgumentException("Requested security strength is not supported by block cipher and key size"); + if (entropySource.EntropySize < securityStrength) + throw new ArgumentException("Not enough entropy for security strength required"); + + mEntropySource = entropySource; + mEngine = engine; + + mKeySizeInBits = keySizeInBits; + mSecurityStrength = securityStrength; + mSeedLength = keySizeInBits + engine.GetBlockSize() * 8; + mIsTdea = IsTdea(engine); + + byte[] entropy = GetEntropy(); // Get_entropy_input + + CTR_DRBG_Instantiate_algorithm(entropy, nonce, personalizationString); + } + + private void CTR_DRBG_Instantiate_algorithm(byte[] entropy, byte[] nonce, byte[] personalisationString) + { + byte[] seedMaterial = Arrays.ConcatenateAll(entropy, nonce, personalisationString); + byte[] seed = Block_Cipher_df(seedMaterial, mSeedLength); + + int outlen = mEngine.GetBlockSize(); + + mKey = new byte[(mKeySizeInBits + 7) / 8]; + mV = new byte[outlen]; + + // mKey & mV are modified by this call + CTR_DRBG_Update(seed, mKey, mV); + + mReseedCounter = 1; + } + + private void CTR_DRBG_Update(byte[] seed, byte[] key, byte[] v) + { + byte[] temp = new byte[seed.Length]; + byte[] outputBlock = new byte[mEngine.GetBlockSize()]; + + int i = 0; + int outLen = mEngine.GetBlockSize(); + + mEngine.Init(true, new KeyParameter(ExpandKey(key))); + while (i*outLen < seed.Length) + { + AddOneTo(v); + mEngine.ProcessBlock(v, 0, outputBlock, 0); + + int bytesToCopy = ((temp.Length - i * outLen) > outLen) + ? outLen : (temp.Length - i * outLen); + + Array.Copy(outputBlock, 0, temp, i * outLen, bytesToCopy); + ++i; + } + + XOR(temp, seed, temp, 0); + + Array.Copy(temp, 0, key, 0, key.Length); + Array.Copy(temp, key.Length, v, 0, v.Length); + } + + private void CTR_DRBG_Reseed_algorithm(byte[] additionalInput) + { + byte[] seedMaterial = Arrays.Concatenate(GetEntropy(), additionalInput); + + seedMaterial = Block_Cipher_df(seedMaterial, mSeedLength); + + CTR_DRBG_Update(seedMaterial, mKey, mV); + + mReseedCounter = 1; + } + + private void XOR(byte[] output, byte[] a, byte[] b, int bOff) + { + for (int i = 0; i < output.Length; i++) + { + output[i] = (byte)(a[i] ^ b[bOff + i]); + } + } + + private void AddOneTo(byte[] longer) + { + uint carry = 1; + int i = longer.Length; + while (--i >= 0) + { + carry += longer[i]; + longer[i] = (byte)carry; + carry >>= 8; + } + } + + private byte[] GetEntropy() + { + byte[] entropy = mEntropySource.GetEntropy(); + if (entropy.Length < (mSecurityStrength + 7) / 8) + throw new InvalidOperationException("Insufficient entropy provided by entropy source"); + return entropy; + } + + // -- Internal state migration --- + + private static readonly byte[] K_BITS = Hex.Decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"); + + // 1. If (number_of_bits_to_return > max_number_of_bits), then return an + // ERROR_FLAG. + // 2. L = len (input_string)/8. + // 3. N = number_of_bits_to_return/8. + // Comment: L is the bitstring represention of + // the integer resulting from len (input_string)/8. + // L shall be represented as a 32-bit integer. + // + // Comment : N is the bitstring represention of + // the integer resulting from + // number_of_bits_to_return/8. N shall be + // represented as a 32-bit integer. + // + // 4. S = L || N || input_string || 0x80. + // 5. While (len (S) mod outlen) + // Comment : Pad S with zeros, if necessary. + // 0, S = S || 0x00. + // + // Comment : Compute the starting value. + // 6. temp = the Null string. + // 7. i = 0. + // 8. K = Leftmost keylen bits of 0x00010203...1D1E1F. + // 9. While len (temp) < keylen + outlen, do + // + // IV = i || 0outlen - len (i). + // + // 9.1 + // + // temp = temp || BCC (K, (IV || S)). + // + // 9.2 + // + // i = i + 1. + // + // 9.3 + // + // Comment : i shall be represented as a 32-bit + // integer, i.e., len (i) = 32. + // + // Comment: The 32-bit integer represenation of + // i is padded with zeros to outlen bits. + // + // Comment: Compute the requested number of + // bits. + // + // 10. K = Leftmost keylen bits of temp. + // + // 11. X = Next outlen bits of temp. + // + // 12. temp = the Null string. + // + // 13. While len (temp) < number_of_bits_to_return, do + // + // 13.1 X = Block_Encrypt (K, X). + // + // 13.2 temp = temp || X. + // + // 14. requested_bits = Leftmost number_of_bits_to_return of temp. + // + // 15. Return SUCCESS and requested_bits. + private byte[] Block_Cipher_df(byte[] inputString, int bitLength) + { + int outLen = mEngine.GetBlockSize(); + int L = inputString.Length; // already in bytes + int N = bitLength / 8; + // 4 S = L || N || inputstring || 0x80 + int sLen = 4 + 4 + L + 1; + int blockLen = ((sLen + outLen - 1) / outLen) * outLen; + byte[] S = new byte[blockLen]; + copyIntToByteArray(S, L, 0); + copyIntToByteArray(S, N, 4); + Array.Copy(inputString, 0, S, 8, L); + S[8 + L] = (byte)0x80; + // S already padded with zeros + + byte[] temp = new byte[mKeySizeInBits / 8 + outLen]; + byte[] bccOut = new byte[outLen]; + + byte[] IV = new byte[outLen]; + + int i = 0; + byte[] K = new byte[mKeySizeInBits / 8]; + Array.Copy(K_BITS, 0, K, 0, K.Length); + + while (i*outLen*8 < mKeySizeInBits + outLen *8) + { + copyIntToByteArray(IV, i, 0); + BCC(bccOut, K, IV, S); + + int bytesToCopy = ((temp.Length - i * outLen) > outLen) + ? outLen + : (temp.Length - i * outLen); + + Array.Copy(bccOut, 0, temp, i * outLen, bytesToCopy); + ++i; + } + + byte[] X = new byte[outLen]; + Array.Copy(temp, 0, K, 0, K.Length); + Array.Copy(temp, K.Length, X, 0, X.Length); + + temp = new byte[bitLength / 2]; + + i = 0; + mEngine.Init(true, new KeyParameter(ExpandKey(K))); + + while (i * outLen < temp.Length) + { + mEngine.ProcessBlock(X, 0, X, 0); + + int bytesToCopy = ((temp.Length - i * outLen) > outLen) + ? outLen + : (temp.Length - i * outLen); + + Array.Copy(X, 0, temp, i * outLen, bytesToCopy); + i++; + } + + return temp; + } + + /* + * 1. chaining_value = 0^outlen + * . Comment: Set the first chaining value to outlen zeros. + * 2. n = len (data)/outlen. + * 3. Starting with the leftmost bits of data, split the data into n blocks of outlen bits + * each, forming block(1) to block(n). + * 4. For i = 1 to n do + * 4.1 input_block = chaining_value ^ block(i) . + * 4.2 chaining_value = Block_Encrypt (Key, input_block). + * 5. output_block = chaining_value. + * 6. Return output_block. + */ + private void BCC(byte[] bccOut, byte[] k, byte[] iV, byte[] data) + { + int outlen = mEngine.GetBlockSize(); + byte[] chainingValue = new byte[outlen]; // initial values = 0 + int n = data.Length / outlen; + + byte[] inputBlock = new byte[outlen]; + + mEngine.Init(true, new KeyParameter(ExpandKey(k))); + + mEngine.ProcessBlock(iV, 0, chainingValue, 0); + + for (int i = 0; i < n; i++) + { + XOR(inputBlock, chainingValue, data, i*outlen); + mEngine.ProcessBlock(inputBlock, 0, chainingValue, 0); + } + + Array.Copy(chainingValue, 0, bccOut, 0, bccOut.Length); + } + + private void copyIntToByteArray(byte[] buf, int value, int offSet) + { + buf[offSet + 0] = ((byte)(value >> 24)); + buf[offSet + 1] = ((byte)(value >> 16)); + buf[offSet + 2] = ((byte)(value >> 8)); + buf[offSet + 3] = ((byte)(value)); + } + + /** + * Return the block size (in bits) of the DRBG. + * + * @return the number of bits produced on each internal round of the DRBG. + */ + public int BlockSize + { + get { return mV.Length * 8; } + } + + /** + * Populate a passed in array with random data. + * + * @param output output array for generated bits. + * @param additionalInput additional input to be added to the DRBG in this step. + * @param predictionResistant true if a reseed should be forced, false otherwise. + * + * @return number of bits generated, -1 if a reseed required. + */ + public int Generate(byte[] output, byte[] additionalInput, bool predictionResistant) + { + if (mIsTdea) + { + if (mReseedCounter > TDEA_RESEED_MAX) + return -1; + + if (DrbgUtilities.IsTooLarge(output, TDEA_MAX_BITS_REQUEST / 8)) + throw new ArgumentException("Number of bits per request limited to " + TDEA_MAX_BITS_REQUEST, "output"); + } + else + { + if (mReseedCounter > AES_RESEED_MAX) + return -1; + + if (DrbgUtilities.IsTooLarge(output, AES_MAX_BITS_REQUEST / 8)) + throw new ArgumentException("Number of bits per request limited to " + AES_MAX_BITS_REQUEST, "output"); + } + + if (predictionResistant) + { + CTR_DRBG_Reseed_algorithm(additionalInput); + additionalInput = null; + } + + if (additionalInput != null) + { + additionalInput = Block_Cipher_df(additionalInput, mSeedLength); + CTR_DRBG_Update(additionalInput, mKey, mV); + } + else + { + additionalInput = new byte[mSeedLength]; + } + + byte[] tmp = new byte[mV.Length]; + + mEngine.Init(true, new KeyParameter(ExpandKey(mKey))); + + for (int i = 0; i <= output.Length / tmp.Length; i++) + { + int bytesToCopy = ((output.Length - i * tmp.Length) > tmp.Length) + ? tmp.Length + : (output.Length - i * mV.Length); + + if (bytesToCopy != 0) + { + AddOneTo(mV); + + mEngine.ProcessBlock(mV, 0, tmp, 0); + + Array.Copy(tmp, 0, output, i * tmp.Length, bytesToCopy); + } + } + + CTR_DRBG_Update(additionalInput, mKey, mV); + + mReseedCounter++; + + return output.Length * 8; + } + + /** + * Reseed the DRBG. + * + * @param additionalInput additional input to be added to the DRBG in this step. + */ + public void Reseed(byte[] additionalInput) + { + CTR_DRBG_Reseed_algorithm(additionalInput); + } + + private bool IsTdea(IBlockCipher cipher) + { + return cipher.AlgorithmName.Equals("DESede") || cipher.AlgorithmName.Equals("TDEA"); + } + + private int GetMaxSecurityStrength(IBlockCipher cipher, int keySizeInBits) + { + if (IsTdea(cipher) && keySizeInBits == 168) + { + return 112; + } + if (cipher.AlgorithmName.Equals("AES")) + { + return keySizeInBits; + } + + return -1; + } + + private byte[] ExpandKey(byte[] key) + { + if (mIsTdea) + { + // expand key to 192 bits. + byte[] tmp = new byte[24]; + + PadKey(key, 0, tmp, 0); + PadKey(key, 7, tmp, 8); + PadKey(key, 14, tmp, 16); + + return tmp; + } + else + { + return key; + } + } + + /** + * Pad out a key for TDEA, setting odd parity for each byte. + * + * @param keyMaster + * @param keyOff + * @param tmp + * @param tmpOff + */ + private void PadKey(byte[] keyMaster, int keyOff, byte[] tmp, int tmpOff) + { + tmp[tmpOff + 0] = (byte)(keyMaster[keyOff + 0] & 0xfe); + tmp[tmpOff + 1] = (byte)((keyMaster[keyOff + 0] << 7) | ((keyMaster[keyOff + 1] & 0xfc) >> 1)); + tmp[tmpOff + 2] = (byte)((keyMaster[keyOff + 1] << 6) | ((keyMaster[keyOff + 2] & 0xf8) >> 2)); + tmp[tmpOff + 3] = (byte)((keyMaster[keyOff + 2] << 5) | ((keyMaster[keyOff + 3] & 0xf0) >> 3)); + tmp[tmpOff + 4] = (byte)((keyMaster[keyOff + 3] << 4) | ((keyMaster[keyOff + 4] & 0xe0) >> 4)); + tmp[tmpOff + 5] = (byte)((keyMaster[keyOff + 4] << 3) | ((keyMaster[keyOff + 5] & 0xc0) >> 5)); + tmp[tmpOff + 6] = (byte)((keyMaster[keyOff + 5] << 2) | ((keyMaster[keyOff + 6] & 0x80) >> 6)); + tmp[tmpOff + 7] = (byte)(keyMaster[keyOff + 6] << 1); + + DesParameters.SetOddParity(tmp, tmpOff, 8); + } + } +} diff --git a/crypto/src/crypto/prng/drbg/DrbgUtilities.cs b/crypto/src/crypto/prng/drbg/DrbgUtilities.cs new file mode 100644
index 000000000..d9a1c439c --- /dev/null +++ b/crypto/src/crypto/prng/drbg/DrbgUtilities.cs
@@ -0,0 +1,103 @@ +using System; +using System.Collections; + +using Org.BouncyCastle.Utilities; + +namespace Org.BouncyCastle.Crypto.Prng.Drbg +{ + internal class DrbgUtilities + { + private static readonly IDictionary maxSecurityStrengths = Platform.CreateHashtable(); + + static DrbgUtilities() + { + maxSecurityStrengths.Add("SHA-1", 128); + + maxSecurityStrengths.Add("SHA-224", 192); + maxSecurityStrengths.Add("SHA-256", 256); + maxSecurityStrengths.Add("SHA-384", 256); + maxSecurityStrengths.Add("SHA-512", 256); + + maxSecurityStrengths.Add("SHA-512/224", 192); + maxSecurityStrengths.Add("SHA-512/256", 256); + } + + internal static int GetMaxSecurityStrength(IDigest d) + { + return (int)maxSecurityStrengths[d.AlgorithmName]; + } + + internal static int GetMaxSecurityStrength(IMac m) + { + string name = m.AlgorithmName; + + return (int)maxSecurityStrengths[name.Substring(0, name.IndexOf("/"))]; + } + + /** + * Used by both Dual EC and Hash. + */ + internal static byte[] HashDF(IDigest digest, byte[] seedMaterial, int seedLength) + { + // 1. temp = the Null string. + // 2. . + // 3. counter = an 8-bit binary value representing the integer "1". + // 4. For i = 1 to len do + // Comment : In step 4.1, no_of_bits_to_return + // is used as a 32-bit string. + // 4.1 temp = temp || Hash (counter || no_of_bits_to_return || + // input_string). + // 4.2 counter = counter + 1. + // 5. requested_bits = Leftmost (no_of_bits_to_return) of temp. + // 6. Return SUCCESS and requested_bits. + byte[] temp = new byte[(seedLength + 7) / 8]; + + int len = temp.Length / digest.GetDigestSize(); + int counter = 1; + + byte[] dig = new byte[digest.GetDigestSize()]; + + for (int i = 0; i <= len; i++) + { + digest.Update((byte)counter); + + digest.Update((byte)(seedLength >> 24)); + digest.Update((byte)(seedLength >> 16)); + digest.Update((byte)(seedLength >> 8)); + digest.Update((byte)seedLength); + + digest.BlockUpdate(seedMaterial, 0, seedMaterial.Length); + + digest.DoFinal(dig, 0); + + int bytesToCopy = ((temp.Length - i * dig.Length) > dig.Length) + ? dig.Length + : (temp.Length - i * dig.Length); + Array.Copy(dig, 0, temp, i * dig.Length, bytesToCopy); + + counter++; + } + + // do a left shift to get rid of excess bits. + if (seedLength % 8 != 0) + { + int shift = 8 - (seedLength % 8); + uint carry = 0; + + for (int i = 0; i != temp.Length; i++) + { + uint b = temp[i]; + temp[i] = (byte)((b >> shift) | (carry << (8 - shift))); + carry = b; + } + } + + return temp; + } + + internal static bool IsTooLarge(byte[] bytes, int maxBytes) + { + return bytes != null && bytes.Length > maxBytes; + } + } +} diff --git a/crypto/src/crypto/prng/drbg/HMacSP800Drbg.cs b/crypto/src/crypto/prng/drbg/HMacSP800Drbg.cs new file mode 100644
index 000000000..78331705e --- /dev/null +++ b/crypto/src/crypto/prng/drbg/HMacSP800Drbg.cs
@@ -0,0 +1,186 @@ +using System; + +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Utilities; + +namespace Org.BouncyCastle.Crypto.Prng.Drbg +{ + /** + * A SP800-90A HMAC DRBG. + */ + public class HMacSP800Drbg + : ISP80090Drbg + { + private readonly static long RESEED_MAX = 1L << (48 - 1); + private readonly static int MAX_BITS_REQUEST = 1 << (19 - 1); + + private readonly byte[] mK; + private readonly byte[] mV; + private readonly IEntropySource mEntropySource; + private readonly IMac mHMac; + private readonly int mSecurityStrength; + + private long mReseedCounter; + + /** + * Construct a SP800-90A Hash DRBG. + * <p> + * Minimum entropy requirement is the security strength requested. + * </p> + * @param hMac Hash MAC to base the DRBG on. + * @param securityStrength security strength required (in bits) + * @param entropySource source of entropy to use for seeding/reseeding. + * @param personalizationString personalization string to distinguish this DRBG (may be null). + * @param nonce nonce to further distinguish this DRBG (may be null). + */ + public HMacSP800Drbg(IMac hMac, int securityStrength, IEntropySource entropySource, byte[] personalizationString, byte[] nonce) + { + if (securityStrength > DrbgUtilities.GetMaxSecurityStrength(hMac)) + throw new ArgumentException("Requested security strength is not supported by the derivation function"); + if (entropySource.EntropySize < securityStrength) + throw new ArgumentException("Not enough entropy for security strength required"); + + mHMac = hMac; + mSecurityStrength = securityStrength; + mEntropySource = entropySource; + + byte[] entropy = GetEntropy(); + byte[] seedMaterial = Arrays.ConcatenateAll(entropy, nonce, personalizationString); + + mK = new byte[hMac.GetMacSize()]; + mV = new byte[mK.Length]; + Arrays.Fill(mV, (byte)1); + + hmac_DRBG_Update(seedMaterial); + + mReseedCounter = 1; + } + + private void hmac_DRBG_Update(byte[] seedMaterial) + { + hmac_DRBG_Update_Func(seedMaterial, (byte)0x00); + if (seedMaterial != null) + { + hmac_DRBG_Update_Func(seedMaterial, (byte)0x01); + } + } + + private void hmac_DRBG_Update_Func(byte[] seedMaterial, byte vValue) + { + mHMac.Init(new KeyParameter(mK)); + + mHMac.BlockUpdate(mV, 0, mV.Length); + mHMac.Update(vValue); + + if (seedMaterial != null) + { + mHMac.BlockUpdate(seedMaterial, 0, seedMaterial.Length); + } + + mHMac.DoFinal(mK, 0); + + mHMac.Init(new KeyParameter(mK)); + mHMac.BlockUpdate(mV, 0, mV.Length); + + mHMac.DoFinal(mV, 0); + } + + /** + * Return the block size (in bits) of the DRBG. + * + * @return the number of bits produced on each round of the DRBG. + */ + public int BlockSize + { + get { return mV.Length * 8; } + } + + /** + * Populate a passed in array with random data. + * + * @param output output array for generated bits. + * @param additionalInput additional input to be added to the DRBG in this step. + * @param predictionResistant true if a reseed should be forced, false otherwise. + * + * @return number of bits generated, -1 if a reseed required. + */ + public int Generate(byte[] output, byte[] additionalInput, bool predictionResistant) + { + int numberOfBits = output.Length * 8; + + if (numberOfBits > MAX_BITS_REQUEST) + throw new ArgumentException("Number of bits per request limited to " + MAX_BITS_REQUEST, "output"); + + if (mReseedCounter > RESEED_MAX) + { + return -1; + } + + if (predictionResistant) + { + Reseed(additionalInput); + additionalInput = null; + } + + // 2. + if (additionalInput != null) + { + hmac_DRBG_Update(additionalInput); + } + + // 3. + byte[] rv = new byte[output.Length]; + + int m = output.Length / mV.Length; + + mHMac.Init(new KeyParameter(mK)); + + for (int i = 0; i < m; i++) + { + mHMac.BlockUpdate(mV, 0, mV.Length); + mHMac.DoFinal(mV, 0); + + Array.Copy(mV, 0, rv, i * mV.Length, mV.Length); + } + + if (m * mV.Length < rv.Length) + { + mHMac.BlockUpdate(mV, 0, mV.Length); + mHMac.DoFinal(mV, 0); + + Array.Copy(mV, 0, rv, m * mV.Length, rv.Length - (m * mV.Length)); + } + + hmac_DRBG_Update(additionalInput); + + mReseedCounter++; + + Array.Copy(rv, 0, output, 0, output.Length); + + return numberOfBits; + } + + /** + * Reseed the DRBG. + * + * @param additionalInput additional input to be added to the DRBG in this step. + */ + public void Reseed(byte[] additionalInput) + { + byte[] entropy = GetEntropy(); + byte[] seedMaterial = Arrays.Concatenate(entropy, additionalInput); + + hmac_DRBG_Update(seedMaterial); + + mReseedCounter = 1; + } + + private byte[] GetEntropy() + { + byte[] entropy = mEntropySource.GetEntropy(); + if (entropy.Length < (mSecurityStrength + 7) / 8) + throw new InvalidOperationException("Insufficient entropy provided by entropy source"); + return entropy; + } + } +} diff --git a/crypto/src/crypto/prng/drbg/HashSP800Drbg.cs b/crypto/src/crypto/prng/drbg/HashSP800Drbg.cs new file mode 100644
index 000000000..493da5a75 --- /dev/null +++ b/crypto/src/crypto/prng/drbg/HashSP800Drbg.cs
@@ -0,0 +1,287 @@ +using System; +using System.Collections; + +using Org.BouncyCastle.Utilities; + +namespace Org.BouncyCastle.Crypto.Prng.Drbg +{ + /** + * A SP800-90A Hash DRBG. + */ + public class HashSP800Drbg + : ISP80090Drbg + { + private readonly static byte[] ONE = { 0x01 }; + + private readonly static long RESEED_MAX = 1L << (48 - 1); + private readonly static int MAX_BITS_REQUEST = 1 << (19 - 1); + + private static readonly IDictionary seedlens = Platform.CreateHashtable(); + + static HashSP800Drbg() + { + seedlens.Add("SHA-1", 440); + seedlens.Add("SHA-224", 440); + seedlens.Add("SHA-256", 440); + seedlens.Add("SHA-512/256", 440); + seedlens.Add("SHA-512/224", 440); + seedlens.Add("SHA-384", 888); + seedlens.Add("SHA-512", 888); + } + + private readonly IDigest mDigest; + private readonly IEntropySource mEntropySource; + private readonly int mSecurityStrength; + private readonly int mSeedLength; + + private byte[] mV; + private byte[] mC; + private long mReseedCounter; + + /** + * Construct a SP800-90A Hash DRBG. + * <p> + * Minimum entropy requirement is the security strength requested. + * </p> + * @param digest source digest to use for DRB stream. + * @param securityStrength security strength required (in bits) + * @param entropySource source of entropy to use for seeding/reseeding. + * @param personalizationString personalization string to distinguish this DRBG (may be null). + * @param nonce nonce to further distinguish this DRBG (may be null). + */ + public HashSP800Drbg(IDigest digest, int securityStrength, IEntropySource entropySource, byte[] personalizationString, byte[] nonce) + { + if (securityStrength > DrbgUtilities.GetMaxSecurityStrength(digest)) + throw new ArgumentException("Requested security strength is not supported by the derivation function"); + if (entropySource.EntropySize < securityStrength) + throw new ArgumentException("Not enough entropy for security strength required"); + + mDigest = digest; + mEntropySource = entropySource; + mSecurityStrength = securityStrength; + mSeedLength = (int)seedlens[digest.AlgorithmName]; + + // 1. seed_material = entropy_input || nonce || personalization_string. + // 2. seed = Hash_df (seed_material, seedlen). + // 3. V = seed. + // 4. C = Hash_df ((0x00 || V), seedlen). Comment: Preceed V with a byte + // of zeros. + // 5. reseed_counter = 1. + // 6. Return V, C, and reseed_counter as the initial_working_state + + byte[] entropy = GetEntropy(); + byte[] seedMaterial = Arrays.ConcatenateAll(entropy, nonce, personalizationString); + byte[] seed = DrbgUtilities.HashDF(mDigest, seedMaterial, mSeedLength); + + mV = seed; + byte[] subV = new byte[mV.Length + 1]; + Array.Copy(mV, 0, subV, 1, mV.Length); + mC = DrbgUtilities.HashDF(mDigest, subV, mSeedLength); + + mReseedCounter = 1; + } + + /** + * Return the block size (in bits) of the DRBG. + * + * @return the number of bits produced on each internal round of the DRBG. + */ + public int BlockSize + { + get { return mDigest.GetDigestSize () * 8; } + } + + /** + * Populate a passed in array with random data. + * + * @param output output array for generated bits. + * @param additionalInput additional input to be added to the DRBG in this step. + * @param predictionResistant true if a reseed should be forced, false otherwise. + * + * @return number of bits generated, -1 if a reseed required. + */ + public int Generate(byte[] output, byte[] additionalInput, bool predictionResistant) + { + // 1. If reseed_counter > reseed_interval, then return an indication that a + // reseed is required. + // 2. If (additional_input != Null), then do + // 2.1 w = Hash (0x02 || V || additional_input). + // 2.2 V = (V + w) mod 2^seedlen + // . + // 3. (returned_bits) = Hashgen (requested_number_of_bits, V). + // 4. H = Hash (0x03 || V). + // 5. V = (V + H + C + reseed_counter) mod 2^seedlen + // . + // 6. reseed_counter = reseed_counter + 1. + // 7. Return SUCCESS, returned_bits, and the new values of V, C, and + // reseed_counter for the new_working_state. + int numberOfBits = output.Length * 8; + + if (numberOfBits > MAX_BITS_REQUEST) + throw new ArgumentException("Number of bits per request limited to " + MAX_BITS_REQUEST, "output"); + + if (mReseedCounter > RESEED_MAX) + return -1; + + if (predictionResistant) + { + Reseed(additionalInput); + additionalInput = null; + } + + // 2. + if (additionalInput != null) + { + byte[] newInput = new byte[1 + mV.Length + additionalInput.Length]; + newInput[0] = 0x02; + Array.Copy(mV, 0, newInput, 1, mV.Length); + // TODO: inOff / inLength + Array.Copy(additionalInput, 0, newInput, 1 + mV.Length, additionalInput.Length); + byte[] w = Hash(newInput); + + AddTo(mV, w); + } + + // 3. + byte[] rv = hashgen(mV, numberOfBits); + + // 4. + byte[] subH = new byte[mV.Length + 1]; + Array.Copy(mV, 0, subH, 1, mV.Length); + subH[0] = 0x03; + + byte[] H = Hash(subH); + + // 5. + AddTo(mV, H); + AddTo(mV, mC); + byte[] c = new byte[4]; + c[0] = (byte)(mReseedCounter >> 24); + c[1] = (byte)(mReseedCounter >> 16); + c[2] = (byte)(mReseedCounter >> 8); + c[3] = (byte)mReseedCounter; + + AddTo(mV, c); + + mReseedCounter++; + + Array.Copy(rv, 0, output, 0, output.Length); + + return numberOfBits; + } + + private byte[] GetEntropy() + { + byte[] entropy = mEntropySource.GetEntropy(); + if (entropy.Length < (mSecurityStrength + 7) / 8) + throw new InvalidOperationException("Insufficient entropy provided by entropy source"); + return entropy; + } + + // this will always add the shorter length byte array mathematically to the + // longer length byte array. + // be careful.... + private void AddTo(byte[] longer, byte[] shorter) + { + int off = longer.Length - shorter.Length; + + uint carry = 0; + int i = shorter.Length; + while (--i >= 0) + { + carry += (uint)longer[off + i] + (uint)shorter[i]; + longer[off + i] = (byte)carry; + carry >>= 8; + } + + i = off; + while (--i >= 0) + { + carry += longer[i]; + longer[i] = (byte)carry; + carry >>= 8; + } + } + + /** + * Reseed the DRBG. + * + * @param additionalInput additional input to be added to the DRBG in this step. + */ + public void Reseed(byte[] additionalInput) + { + // 1. seed_material = 0x01 || V || entropy_input || additional_input. + // + // 2. seed = Hash_df (seed_material, seedlen). + // + // 3. V = seed. + // + // 4. C = Hash_df ((0x00 || V), seedlen). + // + // 5. reseed_counter = 1. + // + // 6. Return V, C, and reseed_counter for the new_working_state. + // + // Comment: Precede with a byte of all zeros. + byte[] entropy = GetEntropy(); + byte[] seedMaterial = Arrays.ConcatenateAll(ONE, mV, entropy, additionalInput); + byte[] seed = DrbgUtilities.HashDF(mDigest, seedMaterial, mSeedLength); + + mV = seed; + byte[] subV = new byte[mV.Length + 1]; + subV[0] = 0x00; + Array.Copy(mV, 0, subV, 1, mV.Length); + mC = DrbgUtilities.HashDF(mDigest, subV, mSeedLength); + + mReseedCounter = 1; + } + + private byte[] Hash(byte[] input) + { + byte[] hash = new byte[mDigest.GetDigestSize()]; + DoHash(input, hash); + return hash; + } + + private void DoHash(byte[] input, byte[] output) + { + mDigest.BlockUpdate(input, 0, input.Length); + mDigest.DoFinal(output, 0); + } + + // 1. m = [requested_number_of_bits / outlen] + // 2. data = V. + // 3. W = the Null string. + // 4. For i = 1 to m + // 4.1 wi = Hash (data). + // 4.2 W = W || wi. + // 4.3 data = (data + 1) mod 2^seedlen + // . + // 5. returned_bits = Leftmost (requested_no_of_bits) bits of W. + private byte[] hashgen(byte[] input, int lengthInBits) + { + int digestSize = mDigest.GetDigestSize(); + int m = (lengthInBits / 8) / digestSize; + + byte[] data = new byte[input.Length]; + Array.Copy(input, 0, data, 0, input.Length); + + byte[] W = new byte[lengthInBits / 8]; + + byte[] dig = new byte[mDigest.GetDigestSize()]; + for (int i = 0; i <= m; i++) + { + DoHash(data, dig); + + int bytesToCopy = ((W.Length - i * dig.Length) > dig.Length) + ? dig.Length + : (W.Length - i * dig.Length); + Array.Copy(dig, 0, W, i * dig.Length, bytesToCopy); + + AddTo(data, ONE); + } + + return W; + } + } +} diff --git a/crypto/src/crypto/prng/drbg/ISP80090Drbg.cs b/crypto/src/crypto/prng/drbg/ISP80090Drbg.cs new file mode 100644
index 000000000..0e398209e --- /dev/null +++ b/crypto/src/crypto/prng/drbg/ISP80090Drbg.cs
@@ -0,0 +1,35 @@ +using System; + +namespace Org.BouncyCastle.Crypto.Prng.Drbg +{ + /** + * Interface to SP800-90A deterministic random bit generators. + */ + public interface ISP80090Drbg + { + /** + * Return the block size of the DRBG. + * + * @return the block size (in bits) produced by each round of the DRBG. + */ + int BlockSize { get; } + + /** + * Populate a passed in array with random data. + * + * @param output output array for generated bits. + * @param additionalInput additional input to be added to the DRBG in this step. + * @param predictionResistant true if a reseed should be forced, false otherwise. + * + * @return number of bits generated, -1 if a reseed required. + */ + int Generate(byte[] output, byte[] additionalInput, bool predictionResistant); + + /** + * Reseed the DRBG. + * + * @param additionalInput additional input to be added to the DRBG in this step. + */ + void Reseed(byte[] additionalInput); + } +} diff --git a/crypto/src/crypto/signers/ECDsaSigner.cs b/crypto/src/crypto/signers/ECDsaSigner.cs
index 9821732c2..520507b8c 100644 --- a/crypto/src/crypto/signers/ECDsaSigner.cs +++ b/crypto/src/crypto/signers/ECDsaSigner.cs
@@ -15,6 +15,8 @@ namespace Org.BouncyCastle.Crypto.Signers public class ECDsaSigner : IDsa { + private static readonly BigInteger Eight = BigInteger.ValueOf(8); + protected readonly IDsaKCalculator kCalculator; protected ECKeyParameters key = null; @@ -149,13 +151,49 @@ namespace Org.BouncyCastle.Crypto.Signers ECPoint G = key.Parameters.G; ECPoint Q = ((ECPublicKeyParameters) key).Q; - ECPoint point = ECAlgorithms.SumOfTwoMultiplies(G, u1, Q, u2).Normalize(); + ECPoint point = ECAlgorithms.SumOfTwoMultiplies(G, u1, Q, u2); if (point.IsInfinity) return false; - BigInteger v = point.AffineXCoord.ToBigInteger().Mod(n); + /* + * If possible, avoid normalizing the point (to save a modular inversion in the curve field). + * + * There are ~cofactor elements of the curve field that reduce (modulo the group order) to 'r'. + * If the cofactor is known and small, we generate those possible field values and project each + * of them to the same "denominator" (depending on the particular projective coordinates in use) + * as the calculated point.X. If any of the projected values matches point.X, then we have: + * (point.X / Denominator mod p) mod n == r + * as required, and verification succeeds. + * + * Based on an original idea by Gregory Maxwell (https://github.com/gmaxwell), as implemented in + * the libsecp256k1 project (https://github.com/bitcoin/secp256k1). + */ + ECCurve curve = point.Curve; + if (curve != null) + { + BigInteger cofactor = curve.Cofactor; + if (cofactor != null && cofactor.CompareTo(Eight) <= 0) + { + ECFieldElement D = GetDenominator(curve.CoordinateSystem, point); + if (D != null && !D.IsZero) + { + ECFieldElement X = point.XCoord; + while (curve.IsValidFieldElement(r)) + { + ECFieldElement R = curve.FromBigInteger(r).Multiply(D); + if (R.Equals(X)) + { + return true; + } + r = r.Add(n); + } + return false; + } + } + } + BigInteger v = point.Normalize().AffineXCoord.ToBigInteger().Mod(n); return v.Equals(r); } @@ -177,6 +215,23 @@ namespace Org.BouncyCastle.Crypto.Signers return new FixedPointCombMultiplier(); } + protected virtual ECFieldElement GetDenominator(int coordinateSystem, ECPoint p) + { + switch (coordinateSystem) + { + case ECCurve.COORD_HOMOGENEOUS: + case ECCurve.COORD_LAMBDA_PROJECTIVE: + case ECCurve.COORD_SKEWED: + return p.GetZCoord(0); + case ECCurve.COORD_JACOBIAN: + case ECCurve.COORD_JACOBIAN_CHUDNOVSKY: + case ECCurve.COORD_JACOBIAN_MODIFIED: + return p.GetZCoord(0).Square(); + default: + return null; + } + } + protected virtual SecureRandom InitSecureRandom(bool needed, SecureRandom provided) { return !needed ? null : (provided != null) ? provided : new SecureRandom(); diff --git a/crypto/src/crypto/tls/ByteQueueStream.cs b/crypto/src/crypto/tls/ByteQueueStream.cs
index bf603e006..249e6099b 100644 --- a/crypto/src/crypto/tls/ByteQueueStream.cs +++ b/crypto/src/crypto/tls/ByteQueueStream.cs
@@ -33,10 +33,6 @@ namespace Org.BouncyCastle.Crypto.Tls get { return true; } } - public override void Close() - { - } - public override void Flush() { } diff --git a/crypto/src/crypto/tls/CertificateUrl.cs b/crypto/src/crypto/tls/CertificateUrl.cs
index a951b8063..d285fa0f6 100644 --- a/crypto/src/crypto/tls/CertificateUrl.cs +++ b/crypto/src/crypto/tls/CertificateUrl.cs
@@ -117,7 +117,7 @@ namespace Org.BouncyCastle.Crypto.Tls this.Position = 0; TlsUtilities.WriteUint16((int)length, this); this.WriteTo(output); - this.Close(); + Platform.Dispose(this); } } } diff --git a/crypto/src/crypto/tls/DefaultTlsAgreementCredentials.cs b/crypto/src/crypto/tls/DefaultTlsAgreementCredentials.cs
index 5147a1990..fab978886 100644 --- a/crypto/src/crypto/tls/DefaultTlsAgreementCredentials.cs +++ b/crypto/src/crypto/tls/DefaultTlsAgreementCredentials.cs
@@ -40,7 +40,7 @@ namespace Org.BouncyCastle.Crypto.Tls } else { - throw new ArgumentException("type not supported: " + privateKey.GetType().FullName, "privateKey"); + throw new ArgumentException("type not supported: " + Platform.GetTypeName(privateKey), "privateKey"); } this.mCertificate = certificate; diff --git a/crypto/src/crypto/tls/DefaultTlsEncryptionCredentials.cs b/crypto/src/crypto/tls/DefaultTlsEncryptionCredentials.cs
index 34d15d146..5348ee88d 100644 --- a/crypto/src/crypto/tls/DefaultTlsEncryptionCredentials.cs +++ b/crypto/src/crypto/tls/DefaultTlsEncryptionCredentials.cs
@@ -2,6 +2,7 @@ using System.IO; using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Tls { @@ -29,7 +30,7 @@ namespace Org.BouncyCastle.Crypto.Tls } else { - throw new ArgumentException("type not supported: " + privateKey.GetType().FullName, "privateKey"); + throw new ArgumentException("type not supported: " + Platform.GetTypeName(privateKey), "privateKey"); } this.mContext = context; diff --git a/crypto/src/crypto/tls/DefaultTlsSignerCredentials.cs b/crypto/src/crypto/tls/DefaultTlsSignerCredentials.cs
index c7a136573..0ff732a97 100644 --- a/crypto/src/crypto/tls/DefaultTlsSignerCredentials.cs +++ b/crypto/src/crypto/tls/DefaultTlsSignerCredentials.cs
@@ -2,6 +2,7 @@ using System; using System.IO; using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Tls { @@ -48,7 +49,7 @@ namespace Org.BouncyCastle.Crypto.Tls } else { - throw new ArgumentException("type not supported: " + privateKey.GetType().FullName, "privateKey"); + throw new ArgumentException("type not supported: " + Platform.GetTypeName(privateKey), "privateKey"); } this.mSigner.Init(context); diff --git a/crypto/src/crypto/tls/DtlsReliableHandshake.cs b/crypto/src/crypto/tls/DtlsReliableHandshake.cs
index 8e4439e67..18a41769a 100644 --- a/crypto/src/crypto/tls/DtlsReliableHandshake.cs +++ b/crypto/src/crypto/tls/DtlsReliableHandshake.cs
@@ -419,8 +419,16 @@ namespace Org.BouncyCastle.Crypto.Tls internal void SendToRecordLayer(DtlsRecordLayer recordLayer) { - recordLayer.Send(GetBuffer(), 0, (int)Length); - this.Close(); +#if PORTABLE + byte[] buf = ToArray(); + int bufLen = buf.Length; +#else + byte[] buf = GetBuffer(); + int bufLen = (int)Length; +#endif + + recordLayer.Send(buf, 0, bufLen); + Platform.Dispose(this); } } diff --git a/crypto/src/crypto/tls/HeartbeatMessage.cs b/crypto/src/crypto/tls/HeartbeatMessage.cs
index f64a7baa4..3f22f7e1d 100644 --- a/crypto/src/crypto/tls/HeartbeatMessage.cs +++ b/crypto/src/crypto/tls/HeartbeatMessage.cs
@@ -95,7 +95,14 @@ namespace Org.BouncyCastle.Crypto.Tls int minimumCount = payloadLength + 16; if (Length < minimumCount) return null; - return Arrays.CopyOf(GetBuffer(), payloadLength); + +#if PORTABLE + byte[] buf = ToArray(); +#else + byte[] buf = GetBuffer(); +#endif + + return Arrays.CopyOf(buf, payloadLength); } } } diff --git a/crypto/src/crypto/tls/RecordStream.cs b/crypto/src/crypto/tls/RecordStream.cs
index 6f3fc41c6..d510ed94e 100644 --- a/crypto/src/crypto/tls/RecordStream.cs +++ b/crypto/src/crypto/tls/RecordStream.cs
@@ -1,6 +1,8 @@ using System; using System.IO; +using Org.BouncyCastle.Utilities; + namespace Org.BouncyCastle.Crypto.Tls { /// <summary>An implementation of the TLS 1.0/1.1/1.2 record layer, allowing downgrade to SSLv3.</summary> @@ -287,7 +289,7 @@ namespace Org.BouncyCastle.Crypto.Tls { try { - mInput.Close(); + Platform.Dispose(mInput); } catch (IOException) { @@ -295,7 +297,7 @@ namespace Org.BouncyCastle.Crypto.Tls try { - mOutput.Close(); + Platform.Dispose(mOutput); } catch (IOException) { diff --git a/crypto/src/crypto/tls/ServerName.cs b/crypto/src/crypto/tls/ServerName.cs
index 3d1e8f844..508c2ddbc 100644 --- a/crypto/src/crypto/tls/ServerName.cs +++ b/crypto/src/crypto/tls/ServerName.cs
@@ -51,10 +51,10 @@ namespace Org.BouncyCastle.Crypto.Tls switch (mNameType) { case Tls.NameType.host_name: - byte[] utf8Encoding = Strings.ToUtf8ByteArray((string)mName); - if (utf8Encoding.Length < 1) + byte[] asciiEncoding = Strings.ToAsciiByteArray((string)mName); + if (asciiEncoding.Length < 1) throw new TlsFatalAlert(AlertDescription.internal_error); - TlsUtilities.WriteOpaque16(utf8Encoding, output); + TlsUtilities.WriteOpaque16(asciiEncoding, output); break; default: throw new TlsFatalAlert(AlertDescription.internal_error); @@ -78,10 +78,10 @@ namespace Org.BouncyCastle.Crypto.Tls { case Tls.NameType.host_name: { - byte[] utf8Encoding = TlsUtilities.ReadOpaque16(input); - if (utf8Encoding.Length < 1) + byte[] asciiEncoding = TlsUtilities.ReadOpaque16(input); + if (asciiEncoding.Length < 1) throw new TlsFatalAlert(AlertDescription.decode_error); - name = Strings.FromUtf8ByteArray(utf8Encoding); + name = Strings.FromAsciiByteArray(asciiEncoding); break; } default: diff --git a/crypto/src/crypto/tls/TlsProtocol.cs b/crypto/src/crypto/tls/TlsProtocol.cs
index fffde0b2b..99168b883 100644 --- a/crypto/src/crypto/tls/TlsProtocol.cs +++ b/crypto/src/crypto/tls/TlsProtocol.cs
@@ -1310,8 +1310,17 @@ namespace Org.BouncyCastle.Crypto.Tls TlsUtilities.CheckUint24(length); this.Position = 1; TlsUtilities.WriteUint24((int)length, this); - protocol.WriteHandshakeMessage(GetBuffer(), 0, (int)Length); - this.Close(); + +#if PORTABLE + byte[] buf = ToArray(); + int bufLen = buf.Length; +#else + byte[] buf = GetBuffer(); + int bufLen = (int)Length; +#endif + + protocol.WriteHandshakeMessage(buf, 0, bufLen); + Platform.Dispose(this); } } } diff --git a/crypto/src/crypto/tls/TlsStream.cs b/crypto/src/crypto/tls/TlsStream.cs
index 7ff7184e3..bfd80edf2 100644 --- a/crypto/src/crypto/tls/TlsStream.cs +++ b/crypto/src/crypto/tls/TlsStream.cs
@@ -28,10 +28,22 @@ namespace Org.BouncyCastle.Crypto.Tls get { return !handler.IsClosed; } } +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + handler.Close(); + } + base.Dispose(disposing); + } +#else public override void Close() { handler.Close(); + base.Close(); } +#endif public override void Flush() { diff --git a/crypto/src/crypto/tls/TlsUtilities.cs b/crypto/src/crypto/tls/TlsUtilities.cs
index a8c8a2b28..26fb0d5e8 100644 --- a/crypto/src/crypto/tls/TlsUtilities.cs +++ b/crypto/src/crypto/tls/TlsUtilities.cs
@@ -529,11 +529,12 @@ namespace Org.BouncyCastle.Crypto.Tls public static Asn1Object ReadAsn1Object(byte[] encoding) { - Asn1InputStream asn1 = new Asn1InputStream(encoding); + MemoryStream input = new MemoryStream(encoding, false); + Asn1InputStream asn1 = new Asn1InputStream(input, encoding.Length); Asn1Object result = asn1.ReadObject(); if (null == result) throw new TlsFatalAlert(AlertDescription.decode_error); - if (null != asn1.ReadObject()) + if (input.Position != input.Length) throw new TlsFatalAlert(AlertDescription.decode_error); return result; } diff --git a/crypto/src/math/BigInteger.cs b/crypto/src/math/BigInteger.cs
index ebeb78788..b35701fb3 100644 --- a/crypto/src/math/BigInteger.cs +++ b/crypto/src/math/BigInteger.cs
@@ -681,6 +681,7 @@ namespace Org.BouncyCastle.Math int xBits = BitsPerByte * nBytes - bitLength; byte mask = (byte)(255U >> xBits); + byte lead = (byte)(1 << (7 - xBits)); for (;;) { @@ -690,7 +691,7 @@ namespace Org.BouncyCastle.Math b[0] &= mask; // ensure the leading bit is 1 (to meet the strength requirement) - b[0] |= (byte)(1 << (7 - xBits)); + b[0] |= lead; // ensure the trailing bit is 1 (i.e. must be odd) b[nBytes - 1] |= 1; @@ -702,21 +703,15 @@ namespace Org.BouncyCastle.Math if (certainty < 1) break; - if (CheckProbablePrime(certainty, random)) + if (CheckProbablePrime(certainty, random, true)) break; - if (bitLength > 32) + for (int j = 1; j < (magnitude.Length - 1); ++j) { - for (int rep = 0; rep < 10000; ++rep) - { - int n = 33 + random.Next(bitLength - 2); - this.magnitude[this.magnitude.Length - (n >> 5)] ^= (1 << (n & 31)); - this.magnitude[this.magnitude.Length - 1] ^= ((random.Next() + 1) << 1); - this.mQuote = 0; + this.magnitude[j] ^= random.Next(); - if (CheckProbablePrime(certainty, random)) - return; - } + if (CheckProbablePrime(certainty, random, true)) + return; } } } @@ -968,7 +963,7 @@ namespace Org.BouncyCastle.Math // // BitLen(value) is the number of bits in value. // - private static int BitLen(int w) + internal static int BitLen(int w) { uint v = (uint)w; uint t = v >> 24; @@ -1340,8 +1335,12 @@ namespace Org.BouncyCastle.Math * probability of 1 - (1/2)**certainty. * <p>From Knuth Vol 2, pg 395.</p> */ - public bool IsProbablePrime( - int certainty) + public bool IsProbablePrime(int certainty) + { + return IsProbablePrime(certainty, false); + } + + internal bool IsProbablePrime(int certainty, bool randomlySelected) { if (certainty <= 0) return true; @@ -1354,12 +1353,10 @@ namespace Org.BouncyCastle.Math if (n.Equals(One)) return false; - return n.CheckProbablePrime(certainty, RandomSource); + return n.CheckProbablePrime(certainty, RandomSource, randomlySelected); } - private bool CheckProbablePrime( - int certainty, - Random random) + private bool CheckProbablePrime(int certainty, Random random, bool randomlySelected) { Debug.Assert(certainty > 0); Debug.Assert(CompareTo(Two) > 0); @@ -1395,7 +1392,7 @@ namespace Org.BouncyCastle.Math // TODO Is it worth trying to create a hybrid of these two? - return RabinMillerTest(certainty, random); + return RabinMillerTest(certainty, random, randomlySelected); // return SolovayStrassenTest(certainty, random); // bool rbTest = RabinMillerTest(certainty, random); @@ -1408,10 +1405,36 @@ namespace Org.BouncyCastle.Math public bool RabinMillerTest(int certainty, Random random) { + return RabinMillerTest(certainty, random, false); + } + + internal bool RabinMillerTest(int certainty, Random random, bool randomlySelected) + { + int bits = BitLength; + Debug.Assert(certainty > 0); - Debug.Assert(BitLength > 2); + Debug.Assert(bits > 2); Debug.Assert(TestBit(0)); + int iterations = ((certainty - 1) / 2) + 1; + if (randomlySelected) + { + int itersFor100Cert = bits >= 1024 ? 4 + : bits >= 512 ? 8 + : bits >= 256 ? 16 + : 50; + + if (certainty < 100) + { + iterations = System.Math.Min(itersFor100Cert, iterations); + } + else + { + iterations -= 50; + iterations += itersFor100Cert; + } + } + // let n = 1 + d . 2^s BigInteger n = this; int s = n.GetLowestSetBitMaskFirst(-1 << 1); @@ -1449,10 +1472,8 @@ namespace Org.BouncyCastle.Math return false; } } - - certainty -= 2; // composites pass for only 1/4 possible 'a' } - while (certainty > 0); + while (--iterations > 0); return true; } @@ -2494,7 +2515,7 @@ namespace Org.BouncyCastle.Math BigInteger n = Inc().SetBit(0); - while (!n.CheckProbablePrime(100, RandomSource)) + while (!n.CheckProbablePrime(100, RandomSource, false)) { n = n.Add(Two); } diff --git a/crypto/src/math/Primes.cs b/crypto/src/math/Primes.cs
index 420c3cc5a..fb279f103 100644 --- a/crypto/src/math/Primes.cs +++ b/crypto/src/math/Primes.cs
@@ -11,6 +11,8 @@ namespace Org.BouncyCastle.Math */ public abstract class Primes { + public static readonly int SmallFactorLimit = 211; + private static readonly BigInteger One = BigInteger.One; private static readonly BigInteger Two = BigInteger.Two; private static readonly BigInteger Three = BigInteger.Three; @@ -326,37 +328,80 @@ namespace Org.BouncyCastle.Math */ int m = 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23; int r = x.Mod(BigInteger.ValueOf(m)).IntValue; - if ((r & 1) != 0 && (r % 3) != 0 && (r % 5) != 0 && (r % 7) != 0 && (r % 11) != 0 - && (r % 13) != 0 && (r % 17) != 0 && (r % 19) != 0 && (r % 23) != 0) + if ((r % 2) == 0 || (r % 3) == 0 || (r % 5) == 0 || (r % 7) == 0 || (r % 11) == 0 || (r % 13) == 0 + || (r % 17) == 0 || (r % 19) == 0 || (r % 23) == 0) { - m = 29 * 31 * 37 * 41 * 43; - r = x.Mod(BigInteger.ValueOf(m)).IntValue; - if ((r % 29) != 0 && (r % 31) != 0 && (r % 37) != 0 && (r % 41) != 0 && (r % 43) != 0) - { - m = 47 * 53 * 59 * 61 * 67; - r = x.Mod(BigInteger.ValueOf(m)).IntValue; - if ((r % 47) != 0 && (r % 53) != 0 && (r % 59) != 0 && (r % 61) != 0 && (r % 67) != 0) - { - m = 71 * 73 * 79 * 83; - r = x.Mod(BigInteger.ValueOf(m)).IntValue; - if ((r % 71) != 0 && (r % 73) != 0 && (r % 79) != 0 && (r % 83) != 0) - { - m = 89 * 97 * 101 * 103; - r = x.Mod(BigInteger.ValueOf(m)).IntValue; - if ((r % 89) != 0 && (r % 97) != 0 && (r % 101) != 0 && (r % 103) != 0) - { - m = 107 * 109 * 113 * 127; - r = x.Mod(BigInteger.ValueOf(m)).IntValue; - if ((r % 107) != 0 && (r % 109) != 0 && (r % 113) != 0 && (r % 127) != 0) - { - return false; - } - } - } - } - } + return true; } - return true; + + m = 29 * 31 * 37 * 41 * 43; + r = x.Mod(BigInteger.ValueOf(m)).IntValue; + if ((r % 29) == 0 || (r % 31) == 0 || (r % 37) == 0 || (r % 41) == 0 || (r % 43) == 0) + { + return true; + } + + m = 47 * 53 * 59 * 61 * 67; + r = x.Mod(BigInteger.ValueOf(m)).IntValue; + if ((r % 47) == 0 || (r % 53) == 0 || (r % 59) == 0 || (r % 61) == 0 || (r % 67) == 0) + { + return true; + } + + m = 71 * 73 * 79 * 83; + r = x.Mod(BigInteger.ValueOf(m)).IntValue; + if ((r % 71) == 0 || (r % 73) == 0 || (r % 79) == 0 || (r % 83) == 0) + { + return true; + } + + m = 89 * 97 * 101 * 103; + r = x.Mod(BigInteger.ValueOf(m)).IntValue; + if ((r % 89) == 0 || (r % 97) == 0 || (r % 101) == 0 || (r % 103) == 0) + { + return true; + } + + m = 107 * 109 * 113 * 127; + r = x.Mod(BigInteger.ValueOf(m)).IntValue; + if ((r % 107) == 0 || (r % 109) == 0 || (r % 113) == 0 || (r % 127) == 0) + { + return true; + } + + m = 131 * 137 * 139 * 149; + r = x.Mod(BigInteger.ValueOf(m)).IntValue; + if ((r % 131) == 0 || (r % 137) == 0 || (r % 139) == 0 || (r % 149) == 0) + { + return true; + } + + m = 151 * 157 * 163 * 167; + r = x.Mod(BigInteger.ValueOf(m)).IntValue; + if ((r % 151) == 0 || (r % 157) == 0 || (r % 163) == 0 || (r % 167) == 0) + { + return true; + } + + m = 173 * 179 * 181 * 191; + r = x.Mod(BigInteger.ValueOf(m)).IntValue; + if ((r % 173) == 0 || (r % 179) == 0 || (r % 181) == 0 || (r % 191) == 0) + { + return true; + } + + m = 193 * 197 * 199 * 211; + r = x.Mod(BigInteger.ValueOf(m)).IntValue; + if ((r % 193) == 0 || (r % 197) == 0 || (r % 199) == 0 || (r % 211) == 0) + { + return true; + } + + /* + * NOTE: Unit tests depend on SMALL_FACTOR_LIMIT matching the + * highest small factor tested here. + */ + return false; } private static bool ImplMRProbablePrimeToBase(BigInteger w, BigInteger wSubOne, BigInteger m, int a, BigInteger b) diff --git a/crypto/src/math/ec/ECCurve.cs b/crypto/src/math/ec/ECCurve.cs
index fa2c72570..6ccd97e7b 100644 --- a/crypto/src/math/ec/ECCurve.cs +++ b/crypto/src/math/ec/ECCurve.cs
@@ -96,6 +96,7 @@ namespace Org.BouncyCastle.Math.EC public abstract int FieldSize { get; } public abstract ECFieldElement FromBigInteger(BigInteger x); + public abstract bool IsValidFieldElement(BigInteger x); public virtual Config Configure() { @@ -477,6 +478,11 @@ namespace Org.BouncyCastle.Math.EC { } + public override bool IsValidFieldElement(BigInteger x) + { + return x != null && x.SignValue >= 0 && x.CompareTo(Field.Characteristic) < 0; + } + protected override ECPoint DecompressPoint(int yTilde, BigInteger X1) { ECFieldElement x = FromBigInteger(X1); @@ -670,6 +676,11 @@ namespace Org.BouncyCastle.Math.EC { } + public override bool IsValidFieldElement(BigInteger x) + { + return x != null && x.SignValue >= 0 && x.BitLength <= FieldSize; + } + [Obsolete("Per-point compression property will be removed")] public override ECPoint CreatePoint(BigInteger x, BigInteger y, bool withCompression) { diff --git a/crypto/src/ocsp/BasicOCSPResp.cs b/crypto/src/ocsp/BasicOCSPResp.cs
index 4253726bb..63ab8921e 100644 --- a/crypto/src/ocsp/BasicOCSPResp.cs +++ b/crypto/src/ocsp/BasicOCSPResp.cs
@@ -95,12 +95,12 @@ namespace Org.BouncyCastle.Ocsp public string SignatureAlgName { - get { return OcspUtilities.GetAlgorithmName(resp.SignatureAlgorithm.ObjectID); } + get { return OcspUtilities.GetAlgorithmName(resp.SignatureAlgorithm.Algorithm); } } public string SignatureAlgOid { - get { return resp.SignatureAlgorithm.ObjectID.Id; } + get { return resp.SignatureAlgorithm.Algorithm.Id; } } [Obsolete("RespData class is no longer required as all functionality is available on this class")] @@ -111,7 +111,7 @@ namespace Org.BouncyCastle.Ocsp public byte[] GetSignature() { - return resp.Signature.GetBytes(); + return resp.GetSignatureOctets(); } private IList GetCertList() diff --git a/crypto/src/ocsp/BasicOCSPRespGenerator.cs b/crypto/src/ocsp/BasicOCSPRespGenerator.cs
index 9735ba177..0dd4e0a09 100644 --- a/crypto/src/ocsp/BasicOCSPRespGenerator.cs +++ b/crypto/src/ocsp/BasicOCSPRespGenerator.cs
@@ -185,7 +185,7 @@ namespace Org.BouncyCastle.Ocsp } private BasicOcspResp GenerateResponse( - ISignatureCalculator signatureCalculator, + ISignatureFactory signatureCalculator, X509Certificate[] chain, DateTime producedAt) { @@ -217,7 +217,7 @@ namespace Org.BouncyCastle.Ocsp streamCalculator.Stream.Write(encoded, 0, encoded.Length); - streamCalculator.Stream.Close(); + Platform.Dispose(streamCalculator.Stream); bitSig = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect()); } @@ -277,27 +277,27 @@ namespace Org.BouncyCastle.Ocsp throw new ArgumentException("no signing algorithm specified"); } - return GenerateResponse(new Asn1SignatureCalculator(signingAlgorithm, privateKey, random), chain, producedAt); + return GenerateResponse(new Asn1SignatureFactory(signingAlgorithm, privateKey, random), chain, producedAt); } /// <summary> /// Generate the signed response using the passed in signature calculator. /// </summary> - /// <param name="signatureCalculator">Implementation of signing calculator.</param> + /// <param name="signatureCalculatorFactory">Implementation of signing calculator factory.</param> /// <param name="chain">The certificate chain associated with the response signer.</param> /// <param name="producedAt">"produced at" date.</param> /// <returns></returns> public BasicOcspResp Generate( - ISignatureCalculator signatureCalculator, + ISignatureFactory signatureCalculatorFactory, X509Certificate[] chain, DateTime producedAt) { - if (signatureCalculator == null) + if (signatureCalculatorFactory == null) { throw new ArgumentException("no signature calculator specified"); } - return GenerateResponse(signatureCalculator, chain, producedAt); + return GenerateResponse(signatureCalculatorFactory, chain, producedAt); } /** diff --git a/crypto/src/ocsp/CertificateID.cs b/crypto/src/ocsp/CertificateID.cs
index a8f035759..ec902d5c3 100644 --- a/crypto/src/ocsp/CertificateID.cs +++ b/crypto/src/ocsp/CertificateID.cs
@@ -43,7 +43,7 @@ namespace Org.BouncyCastle.Ocsp public string HashAlgOid { - get { return id.HashAlgorithm.ObjectID.Id; } + get { return id.HashAlgorithm.Algorithm.Id; } } public byte[] GetIssuerNameHash() @@ -118,7 +118,7 @@ namespace Org.BouncyCastle.Ocsp { try { - String hashAlgorithm = hashAlg.ObjectID.Id; + String hashAlgorithm = hashAlg.Algorithm.Id; X509Name issuerName = PrincipalUtilities.GetSubjectX509Principal(issuerCert); byte[] issuerNameHash = DigestUtilities.CalculateDigest( diff --git a/crypto/src/ocsp/OCSPReq.cs b/crypto/src/ocsp/OCSPReq.cs
index 84808e50a..0cd95c6d6 100644 --- a/crypto/src/ocsp/OCSPReq.cs +++ b/crypto/src/ocsp/OCSPReq.cs
@@ -144,7 +144,7 @@ namespace Org.BouncyCastle.Ocsp if (!this.IsSigned) return null; - return req.OptionalSignature.SignatureAlgorithm.ObjectID.Id; + return req.OptionalSignature.SignatureAlgorithm.Algorithm.Id; } } @@ -153,10 +153,10 @@ namespace Org.BouncyCastle.Ocsp if (!this.IsSigned) return null; - return req.OptionalSignature.SignatureValue.GetBytes(); + return req.OptionalSignature.GetSignatureOctets(); } - private IList GetCertList() + private IList GetCertList() { // load the certificates if we have any diff --git a/crypto/src/openpgp/PgpCompressedDataGenerator.cs b/crypto/src/openpgp/PgpCompressedDataGenerator.cs
index 7f4ec8e53..51b645279 100644 --- a/crypto/src/openpgp/PgpCompressedDataGenerator.cs +++ b/crypto/src/openpgp/PgpCompressedDataGenerator.cs
@@ -2,6 +2,7 @@ using System; using System.IO; using Org.BouncyCastle.Apache.Bzip2; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Zlib; namespace Org.BouncyCastle.Bcpg.OpenPgp @@ -155,10 +156,8 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp { if (dOut != pkOut) { - dOut.Close(); - dOut.Flush(); + Platform.Dispose(dOut); } - dOut = null; pkOut.Finish(); @@ -174,10 +173,22 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp { } - public override void Close() +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + Finish(); + return; + } + base.Dispose(disposing); + } +#else + public override void Close() { Finish(); } +#endif } private class SafeZOutputStream : ZOutputStream @@ -187,11 +198,24 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp { } - public override void Close() +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + Finish(); + End(); + return; + } + base.Dispose(disposing); + } +#else + public override void Close() { Finish(); End(); } +#endif } } } diff --git a/crypto/src/openpgp/PgpEncryptedData.cs b/crypto/src/openpgp/PgpEncryptedData.cs
index 0d237b56c..558e0b8a2 100644 --- a/crypto/src/openpgp/PgpEncryptedData.cs +++ b/crypto/src/openpgp/PgpEncryptedData.cs
@@ -81,7 +81,7 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp Array.Copy(lookAhead, bufStart, buf, pos, len); bufStart += len; - return pos + len - off;; + return pos + len - off; } internal byte[] GetLookAhead() diff --git a/crypto/src/openpgp/PgpLiteralDataGenerator.cs b/crypto/src/openpgp/PgpLiteralDataGenerator.cs
index 17a6eeef2..7672659ca 100644 --- a/crypto/src/openpgp/PgpLiteralDataGenerator.cs +++ b/crypto/src/openpgp/PgpLiteralDataGenerator.cs
@@ -141,8 +141,8 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp return new WrappedGeneratorStream(this, pkOut); } -#if !PORTABLE - /// <summary> +#if !PORTABLE || DOTNET + /// <summary> /// <p> /// Open a literal data packet for the passed in <c>FileInfo</c> object, returning /// an output stream for saving the file contents. diff --git a/crypto/src/openpgp/PgpPublicKeyRing.cs b/crypto/src/openpgp/PgpPublicKeyRing.cs
index 7b1ac93bf..92464d64f 100644 --- a/crypto/src/openpgp/PgpPublicKeyRing.cs +++ b/crypto/src/openpgp/PgpPublicKeyRing.cs
@@ -45,7 +45,7 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp + "tag 0x" + ((int)initialTag).ToString("X")); } - PublicKeyPacket pubPk = (PublicKeyPacket) bcpgInput.ReadPacket();; + PublicKeyPacket pubPk = (PublicKeyPacket) bcpgInput.ReadPacket(); TrustPacket trustPk = ReadOptionalTrustPacket(bcpgInput); // direct signatures and revocations diff --git a/crypto/src/openpgp/PgpPublicKeyRingBundle.cs b/crypto/src/openpgp/PgpPublicKeyRingBundle.cs
index 519a2f884..91113e904 100644 --- a/crypto/src/openpgp/PgpPublicKeyRingBundle.cs +++ b/crypto/src/openpgp/PgpPublicKeyRingBundle.cs
@@ -52,7 +52,7 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp if (pgpPub == null) { - throw new PgpException(obj.GetType().FullName + " found where PgpPublicKeyRing expected"); + throw new PgpException(Platform.GetTypeName(obj) + " found where PgpPublicKeyRing expected"); } long key = pgpPub.GetPublicKey().KeyId; @@ -113,7 +113,7 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp if (ignoreCase) { - userId = Platform.ToLowerInvariant(userId); + userId = Platform.ToUpperInvariant(userId); } foreach (PgpPublicKeyRing pubRing in GetKeyRings()) @@ -123,12 +123,12 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp string next = nextUserID; if (ignoreCase) { - next = Platform.ToLowerInvariant(next); + next = Platform.ToUpperInvariant(next); } if (matchPartial) { - if (next.IndexOf(userId) > -1) + if (Platform.IndexOf(next, userId) > -1) { rings.Add(pubRing); } diff --git a/crypto/src/openpgp/PgpSecretKey.cs b/crypto/src/openpgp/PgpSecretKey.cs
index d3811c44c..b3986073d 100644 --- a/crypto/src/openpgp/PgpSecretKey.cs +++ b/crypto/src/openpgp/PgpSecretKey.cs
@@ -1204,7 +1204,7 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp string curveID = SXprUtilities.ReadString(inputStream, inputStream.ReadByte()); curveName = SXprUtilities.ReadString(inputStream, inputStream.ReadByte()); - if (curveName.StartsWith("NIST ")) + if (Platform.StartsWith(curveName, "NIST ")) { curveName = curveName.Substring("NIST ".Length); } diff --git a/crypto/src/openpgp/PgpSecretKeyRingBundle.cs b/crypto/src/openpgp/PgpSecretKeyRingBundle.cs
index 12c7c098c..c9f4d3959 100644 --- a/crypto/src/openpgp/PgpSecretKeyRingBundle.cs +++ b/crypto/src/openpgp/PgpSecretKeyRingBundle.cs
@@ -1,6 +1,5 @@ using System; using System.Collections; -using System.Globalization; using System.IO; using Org.BouncyCastle.Utilities; @@ -53,7 +52,7 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp if (pgpSecret == null) { - throw new PgpException(obj.GetType().FullName + " found where PgpSecretKeyRing expected"); + throw new PgpException(Platform.GetTypeName(obj) + " found where PgpSecretKeyRing expected"); } long key = pgpSecret.GetPublicKey().KeyId; @@ -114,7 +113,7 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp if (ignoreCase) { - userId = Platform.ToLowerInvariant(userId); + userId = Platform.ToUpperInvariant(userId); } foreach (PgpSecretKeyRing secRing in GetKeyRings()) @@ -124,12 +123,12 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp string next = nextUserID; if (ignoreCase) { - next = Platform.ToLowerInvariant(next); + next = Platform.ToUpperInvariant(next); } if (matchPartial) { - if (next.IndexOf(userId) > -1) + if (Platform.IndexOf(next, userId) > -1) { rings.Add(secRing); } diff --git a/crypto/src/openpgp/PgpUtilities.cs b/crypto/src/openpgp/PgpUtilities.cs
index f982ae459..055f99636 100644 --- a/crypto/src/openpgp/PgpUtilities.cs +++ b/crypto/src/openpgp/PgpUtilities.cs
@@ -347,7 +347,7 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp return MakeKey(algorithm, keyBytes); } -#if !PORTABLE +#if !PORTABLE || DOTNET /// <summary>Write out the passed in file as a literal data packet.</summary> public static void WriteFileToLiteralData( Stream output, @@ -382,8 +382,8 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp pOut.Write(buf, 0, len); } - pOut.Close(); - inputStream.Close(); + Platform.Dispose(pOut); + Platform.Dispose(inputStream); } #endif diff --git a/crypto/src/openpgp/WrappedGeneratorStream.cs b/crypto/src/openpgp/WrappedGeneratorStream.cs
index cdc9befb3..5f4a4b045 100644 --- a/crypto/src/openpgp/WrappedGeneratorStream.cs +++ b/crypto/src/openpgp/WrappedGeneratorStream.cs
@@ -17,9 +17,21 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp this.gen = gen; } +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + gen.Close(); + return; + } + base.Dispose(disposing); + } +#else public override void Close() { gen.Close(); } +#endif } } diff --git a/crypto/src/openssl/MiscPemGenerator.cs b/crypto/src/openssl/MiscPemGenerator.cs
index 6b91e8b1c..22ae1eae1 100644 --- a/crypto/src/openssl/MiscPemGenerator.cs +++ b/crypto/src/openssl/MiscPemGenerator.cs
@@ -3,7 +3,6 @@ using System.Collections; using System.IO; using Org.BouncyCastle.Asn1; -using Org.BouncyCastle.Asn1.Cms; using Org.BouncyCastle.Asn1.CryptoPro; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Asn1.X509; @@ -127,7 +126,7 @@ namespace Org.BouncyCastle.OpenSsl } else { - throw new PemGenerationException("Object type not supported: " + obj.GetType().FullName); + throw new PemGenerationException("Object type not supported: " + Platform.GetTypeName(obj)); } return new PemObject(type, encoding); @@ -185,7 +184,7 @@ namespace Org.BouncyCastle.OpenSsl if (type == null || keyData == null) { // TODO Support other types? - throw new PemGenerationException("Object type not supported: " + obj.GetType().FullName); + throw new PemGenerationException("Object type not supported: " + Platform.GetTypeName(obj)); } @@ -197,7 +196,7 @@ namespace Org.BouncyCastle.OpenSsl dekAlgName = "DES-EDE3-CBC"; } - int ivLength = dekAlgName.StartsWith("AES-") ? 16 : 8; + int ivLength = Platform.StartsWith(dekAlgName, "AES-") ? 16 : 8; byte[] iv = new byte[ivLength]; random.NextBytes(iv); @@ -218,7 +217,7 @@ namespace Org.BouncyCastle.OpenSsl { PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(akp); AlgorithmIdentifier algID = info.PrivateKeyAlgorithm; - DerObjectIdentifier oid = algID.ObjectID; + DerObjectIdentifier oid = algID.Algorithm; if (oid.Equals(X9ObjectIdentifiers.IdDsa)) { @@ -250,7 +249,7 @@ namespace Org.BouncyCastle.OpenSsl } else { - throw new ArgumentException("Cannot handle private key of type: " + akp.GetType().FullName, "akp"); + throw new ArgumentException("Cannot handle private key of type: " + Platform.GetTypeName(akp), "akp"); } return info.ParsePrivateKey().GetEncoded(); diff --git a/crypto/src/openssl/PEMReader.cs b/crypto/src/openssl/PEMReader.cs
index ec5d1b414..9a5f99b1a 100644 --- a/crypto/src/openssl/PEMReader.cs +++ b/crypto/src/openssl/PEMReader.cs
@@ -93,7 +93,7 @@ namespace Org.BouncyCastle.OpenSsl // if (parsers.Contains(obj.Type)) // return ((PemObjectParser)parsers[obj.Type]).ParseObject(obj); - if (obj.Type.EndsWith("PRIVATE KEY")) + if (Platform.EndsWith(obj.Type, "PRIVATE KEY")) return ReadPrivateKey(obj); switch (obj.Type) @@ -233,7 +233,7 @@ namespace Org.BouncyCastle.OpenSsl // // extract the key // - Debug.Assert(pemObject.Type.EndsWith("PRIVATE KEY")); + Debug.Assert(Platform.EndsWith(pemObject.Type, "PRIVATE KEY")); string type = pemObject.Type.Substring(0, pemObject.Type.Length - "PRIVATE KEY".Length).Trim(); byte[] keyBytes = pemObject.Content; @@ -311,7 +311,7 @@ namespace Org.BouncyCastle.OpenSsl case "EC": { - ECPrivateKeyStructure pKey = new ECPrivateKeyStructure(seq); + ECPrivateKeyStructure pKey = ECPrivateKeyStructure.GetInstance(seq); AlgorithmIdentifier algId = new AlgorithmIdentifier( X9ObjectIdentifiers.IdECPublicKey, pKey.GetParameters()); diff --git a/crypto/src/pkcs/Pkcs10CertificationRequest.cs b/crypto/src/pkcs/Pkcs10CertificationRequest.cs
index 6c6b4c87d..c2504e6e5 100644 --- a/crypto/src/pkcs/Pkcs10CertificationRequest.cs +++ b/crypto/src/pkcs/Pkcs10CertificationRequest.cs
@@ -209,7 +209,7 @@ namespace Org.BouncyCastle.Pkcs /// <param name="publicKey">Public Key to be included in cert reqest.</param> /// <param name="attributes">ASN1Set of Attributes.</param> /// <param name="signingKey">Matching Private key for nominated (above) public key to be used to sign the request.</param> - [Obsolete("Use constructor with an ISignatureCalculator")] + [Obsolete("Use constructor with an ISignatureFactory")] public Pkcs10CertificationRequest( string signatureAlgorithm, X509Name subject, @@ -228,25 +228,25 @@ namespace Org.BouncyCastle.Pkcs if (!signingKey.IsPrivate) throw new ArgumentException("key for signing must be private", "signingKey"); - init(new Asn1SignatureCalculator(signatureAlgorithm, signingKey), subject, publicKey, attributes, signingKey); + init(new Asn1SignatureFactory(signatureAlgorithm, signingKey), subject, publicKey, attributes, signingKey); } /// <summary> /// Instantiate a Pkcs10CertificationRequest object with the necessary credentials. /// </summary> - ///<param name="signatureCalculator">The signature calculator to sign the PKCS#10 request with.</param> + ///<param name="signatureCalculatorFactory">The factory for signature calculators to sign the PKCS#10 request with.</param> /// <param name="subject">X509Name of subject eg OU="My unit." O="My Organisatioin" C="au" </param> /// <param name="publicKey">Public Key to be included in cert reqest.</param> /// <param name="attributes">ASN1Set of Attributes.</param> /// <param name="signingKey">Matching Private key for nominated (above) public key to be used to sign the request.</param> public Pkcs10CertificationRequest( - ISignatureCalculator signatureCalculator, + ISignatureFactory signatureCalculatorFactory, X509Name subject, AsymmetricKeyParameter publicKey, Asn1Set attributes, AsymmetricKeyParameter signingKey) { - if (signatureCalculator == null) + if (signatureCalculatorFactory == null) throw new ArgumentNullException("signatureCalculator"); if (subject == null) throw new ArgumentNullException("subject"); @@ -257,11 +257,11 @@ namespace Org.BouncyCastle.Pkcs if (!signingKey.IsPrivate) throw new ArgumentException("key for signing must be private", "signingKey"); - init(signatureCalculator, subject, publicKey, attributes, signingKey); + init(signatureCalculatorFactory, subject, publicKey, attributes, signingKey); } private void init( - ISignatureCalculator signatureCalculator, + ISignatureFactory signatureCalculator, X509Name subject, AsymmetricKeyParameter publicKey, Asn1Set attributes, @@ -279,7 +279,7 @@ namespace Org.BouncyCastle.Pkcs streamCalculator.Stream.Write(reqInfoData, 0, reqInfoData.Length); - streamCalculator.Stream.Close(); + Platform.Dispose(streamCalculator.Stream); // Generate Signature. sigBits = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect()); @@ -322,17 +322,17 @@ namespace Org.BouncyCastle.Pkcs public bool Verify( AsymmetricKeyParameter publicKey) { - return Verify(new Asn1SignatureVerifierProvider(publicKey)); + return Verify(new Asn1VerifierFactoryProvider(publicKey)); } public bool Verify( - ISignatureVerifierProvider verifierProvider) + IVerifierFactoryProvider verifierProvider) { - return Verify(verifierProvider.CreateSignatureVerifier(sigAlgId)); + return Verify(verifierProvider.CreateVerifierFactory(sigAlgId)); } public bool Verify( - ISignatureVerifier verifier) + IVerifierFactory verifier) { try { @@ -342,9 +342,9 @@ namespace Org.BouncyCastle.Pkcs streamCalculator.Stream.Write(b, 0, b.Length); - streamCalculator.Stream.Close(); + Platform.Dispose(streamCalculator.Stream); - return ((IVerifier)streamCalculator.GetResult()).IsVerified(sigBits.GetBytes()); + return ((IVerifier)streamCalculator.GetResult()).IsVerified(sigBits.GetOctets()); } catch (Exception e) { @@ -379,7 +379,7 @@ namespace Org.BouncyCastle.Pkcs // throw new SignatureException("IOException decoding parameters: " + e.Message); // } - if (signature.AlgorithmName.EndsWith("MGF1")) + if (Platform.EndsWith(signature.AlgorithmName, "MGF1")) { throw Platform.CreateNotImplementedException("signature algorithm with MGF1"); @@ -402,14 +402,14 @@ namespace Org.BouncyCastle.Pkcs if (asn1Params != null && !(asn1Params is Asn1Null)) { - if (sigAlgId.ObjectID.Equals(PkcsObjectIdentifiers.IdRsassaPss)) + if (sigAlgId.Algorithm.Equals(PkcsObjectIdentifiers.IdRsassaPss)) { RsassaPssParameters rsaParams = RsassaPssParameters.GetInstance(asn1Params); - return GetDigestAlgName(rsaParams.HashAlgorithm.ObjectID) + "withRSAandMGF1"; + return GetDigestAlgName(rsaParams.HashAlgorithm.Algorithm) + "withRSAandMGF1"; } } - return sigAlgId.ObjectID.Id; + return sigAlgId.Algorithm.Id; } private static string GetDigestAlgName( diff --git a/crypto/src/pkcs/Pkcs12Store.cs b/crypto/src/pkcs/Pkcs12Store.cs
index e4fe29401..e65788733 100644 --- a/crypto/src/pkcs/Pkcs12Store.cs +++ b/crypto/src/pkcs/Pkcs12Store.cs
@@ -213,7 +213,7 @@ namespace Org.BouncyCastle.Pkcs byte[] data = ((Asn1OctetString) info.Content).GetOctets(); - byte[] mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, false, data); + byte[] mac = CalculatePbeMac(algId.Algorithm, salt, itCount, password, false, data); byte[] dig = dInfo.GetDigest(); if (!Arrays.ConstantTimeAreEqual(mac, dig)) @@ -222,7 +222,7 @@ namespace Org.BouncyCastle.Pkcs throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); // Try with incorrect zero length password - mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, true, data); + mac = CalculatePbeMac(algId.Algorithm, salt, itCount, password, true, data); if (!Arrays.ConstantTimeAreEqual(mac, dig)) throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); @@ -1015,14 +1015,14 @@ namespace Org.BouncyCastle.Pkcs bool wrongPkcs12Zero, byte[] data) { - IBufferedCipher cipher = PbeUtilities.CreateEngine(algId.ObjectID) as IBufferedCipher; + IBufferedCipher cipher = PbeUtilities.CreateEngine(algId.Algorithm) as IBufferedCipher; if (cipher == null) - throw new Exception("Unknown encryption algorithm: " + algId.ObjectID); + throw new Exception("Unknown encryption algorithm: " + algId.Algorithm); Pkcs12PbeParams pbeParameters = Pkcs12PbeParams.GetInstance(algId.Parameters); ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters( - algId.ObjectID, password, wrongPkcs12Zero, pbeParameters); + algId.Algorithm, password, wrongPkcs12Zero, pbeParameters); cipher.Init(forEncryption, cipherParams); return cipher.DoFinal(data); } @@ -1052,13 +1052,13 @@ namespace Org.BouncyCastle.Pkcs public object Remove( string alias) { - string lower = Platform.ToLowerInvariant(alias); - string k = (string) keys[lower]; + string upper = Platform.ToUpperInvariant(alias); + string k = (string)keys[upper]; if (k == null) return null; - keys.Remove(lower); + keys.Remove(upper); object o = orig[k]; orig.Remove(k); @@ -1070,8 +1070,8 @@ namespace Org.BouncyCastle.Pkcs { get { - string lower = Platform.ToLowerInvariant(alias); - string k = (string)keys[lower]; + string upper = Platform.ToUpperInvariant(alias); + string k = (string)keys[upper]; if (k == null) return null; @@ -1080,13 +1080,13 @@ namespace Org.BouncyCastle.Pkcs } set { - string lower = Platform.ToLowerInvariant(alias); - string k = (string)keys[lower]; + string upper = Platform.ToUpperInvariant(alias); + string k = (string)keys[upper]; if (k != null) { orig.Remove(k); } - keys[lower] = alias; + keys[upper] = alias; orig[alias] = value; } } diff --git a/crypto/src/pkcs/Pkcs12Utilities.cs b/crypto/src/pkcs/Pkcs12Utilities.cs
index d35c8b6a2..923eca5a5 100644 --- a/crypto/src/pkcs/Pkcs12Utilities.cs +++ b/crypto/src/pkcs/Pkcs12Utilities.cs
@@ -56,10 +56,10 @@ namespace Org.BouncyCastle.Pkcs int itCount = mData.IterationCount.IntValue; byte[] data = Asn1OctetString.GetInstance(info.Content).GetOctets(); byte[] res = Pkcs12Store.CalculatePbeMac( - mData.Mac.AlgorithmID.ObjectID, mData.GetSalt(), itCount, passwd, false, data); + mData.Mac.AlgorithmID.Algorithm, mData.GetSalt(), itCount, passwd, false, data); AlgorithmIdentifier algId = new AlgorithmIdentifier( - mData.Mac.AlgorithmID.ObjectID, DerNull.Instance); + mData.Mac.AlgorithmID.Algorithm, DerNull.Instance); DigestInfo dInfo = new DigestInfo(algId, res); mData = new MacData(dInfo, mData.GetSalt(), itCount); diff --git a/crypto/src/pkcs/PrivateKeyInfoFactory.cs b/crypto/src/pkcs/PrivateKeyInfoFactory.cs
index 723d50f08..a349a11d2 100644 --- a/crypto/src/pkcs/PrivateKeyInfoFactory.cs +++ b/crypto/src/pkcs/PrivateKeyInfoFactory.cs
@@ -106,49 +106,46 @@ namespace Org.BouncyCastle.Pkcs if (key is ECPrivateKeyParameters) { - ECPrivateKeyParameters _key = (ECPrivateKeyParameters)key; + ECPrivateKeyParameters priv = (ECPrivateKeyParameters)key; + ECDomainParameters dp = priv.Parameters; + int orderBitLength = dp.N.BitLength; + AlgorithmIdentifier algID; ECPrivateKeyStructure ec; - if (_key.AlgorithmName == "ECGOST3410") + if (priv.AlgorithmName == "ECGOST3410") { - if (_key.PublicKeyParamSet == null) + if (priv.PublicKeyParamSet == null) throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( - _key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet); + priv.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet); - algID = new AlgorithmIdentifier( - CryptoProObjectIdentifiers.GostR3410x2001, - gostParams.ToAsn1Object()); + algID = new AlgorithmIdentifier(CryptoProObjectIdentifiers.GostR3410x2001, gostParams); // TODO Do we need to pass any parameters here? - ec = new ECPrivateKeyStructure(_key.D); + ec = new ECPrivateKeyStructure(orderBitLength, priv.D); } else { X962Parameters x962; - if (_key.PublicKeyParamSet == null) + if (priv.PublicKeyParamSet == null) { - ECDomainParameters kp = _key.Parameters; - X9ECParameters ecP = new X9ECParameters(kp.Curve, kp.G, kp.N, kp.H, kp.GetSeed()); - + X9ECParameters ecP = new X9ECParameters(dp.Curve, dp.G, dp.N, dp.H, dp.GetSeed()); x962 = new X962Parameters(ecP); } else { - x962 = new X962Parameters(_key.PublicKeyParamSet); + x962 = new X962Parameters(priv.PublicKeyParamSet); } - Asn1Object x962Object = x962.ToAsn1Object(); - // TODO Possible to pass the publicKey bitstring here? - ec = new ECPrivateKeyStructure(_key.D, x962Object); + ec = new ECPrivateKeyStructure(orderBitLength, priv.D, x962); - algID = new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, x962Object); + algID = new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, x962); } - return new PrivateKeyInfo(algID, ec.ToAsn1Object()); + return new PrivateKeyInfo(algID, ec); } if (key is Gost3410PrivateKeyParameters) @@ -176,7 +173,7 @@ namespace Org.BouncyCastle.Pkcs return new PrivateKeyInfo(algID, new DerOctetString(keyBytes)); } - throw new ArgumentException("Class provided is not convertible: " + key.GetType().FullName); + throw new ArgumentException("Class provided is not convertible: " + Platform.GetTypeName(key)); } public static PrivateKeyInfo CreatePrivateKeyInfo( @@ -195,7 +192,7 @@ namespace Org.BouncyCastle.Pkcs IBufferedCipher cipher = PbeUtilities.CreateEngine(algID) as IBufferedCipher; if (cipher == null) - throw new Exception("Unknown encryption algorithm: " + algID.ObjectID); + throw new Exception("Unknown encryption algorithm: " + algID.Algorithm); ICipherParameters cipherParameters = PbeUtilities.GenerateCipherParameters( algID, passPhrase, wrongPkcs12Zero); diff --git a/crypto/src/pkix/PkixCertPath.cs b/crypto/src/pkix/PkixCertPath.cs
index 23a53c396..3c428f6fb 100644 --- a/crypto/src/pkix/PkixCertPath.cs +++ b/crypto/src/pkix/PkixCertPath.cs
@@ -357,7 +357,7 @@ namespace Org.BouncyCastle.Pkix public virtual byte[] GetEncoded( string encoding) { - if (Platform.CompareIgnoreCase(encoding, "PkiPath") == 0) + if (Platform.EqualsIgnoreCase(encoding, "PkiPath")) { Asn1EncodableVector v = new Asn1EncodableVector(); @@ -368,7 +368,7 @@ namespace Org.BouncyCastle.Pkix return ToDerEncoded(new DerSequence(v)); } - else if (Platform.CompareIgnoreCase(encoding, "PKCS7") == 0) + else if (Platform.EqualsIgnoreCase(encoding, "PKCS7")) { Asn1.Pkcs.ContentInfo encInfo = new Asn1.Pkcs.ContentInfo( PkcsObjectIdentifiers.Data, null); @@ -389,7 +389,7 @@ namespace Org.BouncyCastle.Pkix return ToDerEncoded(new Asn1.Pkcs.ContentInfo(PkcsObjectIdentifiers.SignedData, sd)); } - else if (Platform.CompareIgnoreCase(encoding, "PEM") == 0) + else if (Platform.EqualsIgnoreCase(encoding, "PEM")) { MemoryStream bOut = new MemoryStream(); PemWriter pWrt = new PemWriter(new StreamWriter(bOut)); @@ -401,7 +401,7 @@ namespace Org.BouncyCastle.Pkix pWrt.WriteObject(certificates[i]); } - pWrt.Writer.Close(); + Platform.Dispose(pWrt.Writer); } catch (Exception) { diff --git a/crypto/src/pkix/PkixCertPathBuilder.cs b/crypto/src/pkix/PkixCertPathBuilder.cs
index 7082fe409..fa38a5ec0 100644 --- a/crypto/src/pkix/PkixCertPathBuilder.cs +++ b/crypto/src/pkix/PkixCertPathBuilder.cs
@@ -42,7 +42,7 @@ namespace Org.BouncyCastle.Pkix throw new PkixCertPathBuilderException( "TargetConstraints must be an instance of " + typeof(X509CertStoreSelector).FullName + " for " - + this.GetType() + " class."); + + Platform.GetTypeName(this) + " class."); } ISet targets = new HashSet(); diff --git a/crypto/src/pkix/PkixCertPathValidator.cs b/crypto/src/pkix/PkixCertPathValidator.cs
index 7eb838886..fcfa63837 100644 --- a/crypto/src/pkix/PkixCertPathValidator.cs +++ b/crypto/src/pkix/PkixCertPathValidator.cs
@@ -204,7 +204,7 @@ namespace Org.BouncyCastle.Pkix "Algorithm identifier of public key of trust anchor could not be read.", e, certPath, -1); } -// DerObjectIdentifier workingPublicKeyAlgorithm = workingAlgId.ObjectID; +// DerObjectIdentifier workingPublicKeyAlgorithm = workingAlgId.Algorithm; // Asn1Encodable workingPublicKeyParameters = workingAlgId.Parameters; // @@ -358,7 +358,7 @@ namespace Org.BouncyCastle.Pkix workingAlgId = PkixCertPathValidatorUtilities.GetAlgorithmIdentifier(workingPublicKey); // (f) -// workingPublicKeyAlgorithm = workingAlgId.ObjectID; +// workingPublicKeyAlgorithm = workingAlgId.Algorithm; // (e) // workingPublicKeyParameters = workingAlgId.Parameters; } diff --git a/crypto/src/pkix/PkixCertPathValidatorUtilities.cs b/crypto/src/pkix/PkixCertPathValidatorUtilities.cs
index acea77856..a2704a746 100644 --- a/crypto/src/pkix/PkixCertPathValidatorUtilities.cs +++ b/crypto/src/pkix/PkixCertPathValidatorUtilities.cs
@@ -230,7 +230,7 @@ namespace Org.BouncyCastle.Pkix { try { - if (location.StartsWith("ldap://")) + if (Platform.StartsWith(location, "ldap://")) { // ldap://directory.d-trust.net/CN=D-TRUST // Qualified CA 2003 1:PN,O=D-Trust GmbH,C=DE diff --git a/crypto/src/pkix/PkixNameConstraintValidator.cs b/crypto/src/pkix/PkixNameConstraintValidator.cs
index cf944beae..f4ae73925 100644 --- a/crypto/src/pkix/PkixNameConstraintValidator.cs +++ b/crypto/src/pkix/PkixNameConstraintValidator.cs
@@ -662,7 +662,7 @@ namespace Org.BouncyCastle.Pkix private bool WithinDomain(String testDomain, String domain) { String tempDomain = domain; - if (tempDomain.StartsWith(".")) + if (Platform.StartsWith(tempDomain, ".")) { tempDomain = tempDomain.Substring(1); } @@ -685,7 +685,7 @@ namespace Org.BouncyCastle.Pkix return false; } } - else if (!(Platform.CompareIgnoreCase(testDomainParts[i + d], domainParts[i]) == 0)) + else if (!Platform.EqualsIgnoreCase(testDomainParts[i + d], domainParts[i])) { return false; } @@ -737,7 +737,7 @@ namespace Org.BouncyCastle.Pkix String str = ((String)it.Current); // is sub domain or the same - if (WithinDomain(dns, str) || (Platform.CompareIgnoreCase(dns, str) == 0)) + if (WithinDomain(dns, str) || Platform.EqualsIgnoreCase(dns, str)) { throw new PkixNameConstraintValidatorException( "DNS is from an excluded subtree."); @@ -763,7 +763,7 @@ namespace Org.BouncyCastle.Pkix // both are a particular mailbox if (email2.IndexOf('@') != -1) { - if (Platform.CompareIgnoreCase(email1, email2) == 0) + if (Platform.EqualsIgnoreCase(email1, email2)) { union.Add(email1); } @@ -774,7 +774,7 @@ namespace Org.BouncyCastle.Pkix } } // email2 specifies a domain - else if (email2.StartsWith(".")) + else if (Platform.StartsWith(email2, ".")) { if (WithinDomain(_sub, email2)) { @@ -789,7 +789,7 @@ namespace Org.BouncyCastle.Pkix // email2 specifies a particular host else { - if (Platform.CompareIgnoreCase(_sub, email2) == 0) + if (Platform.EqualsIgnoreCase(_sub, email2)) { union.Add(email2); } @@ -801,7 +801,7 @@ namespace Org.BouncyCastle.Pkix } } // email1 specifies a domain - else if (email1.StartsWith(".")) + else if (Platform.StartsWith(email1, ".")) { if (email2.IndexOf('@') != -1) { @@ -817,9 +817,9 @@ namespace Org.BouncyCastle.Pkix } } // email2 specifies a domain - else if (email2.StartsWith(".")) + else if (Platform.StartsWith(email2, ".")) { - if (WithinDomain(email1, email2) || Platform.CompareIgnoreCase(email1, email2) == 0) + if (WithinDomain(email1, email2) || Platform.EqualsIgnoreCase(email1, email2)) { union.Add(email2); } @@ -852,7 +852,7 @@ namespace Org.BouncyCastle.Pkix if (email2.IndexOf('@') != -1) { String _sub = email2.Substring(email1.IndexOf('@') + 1); - if (Platform.CompareIgnoreCase(_sub, email1) == 0) + if (Platform.EqualsIgnoreCase(_sub, email1)) { union.Add(email1); } @@ -863,7 +863,7 @@ namespace Org.BouncyCastle.Pkix } } // email2 specifies a domain - else if (email2.StartsWith(".")) + else if (Platform.StartsWith(email2, ".")) { if (WithinDomain(email1, email2)) { @@ -878,7 +878,7 @@ namespace Org.BouncyCastle.Pkix // email2 specifies a particular host else { - if (Platform.CompareIgnoreCase(email1, email2) == 0) + if (Platform.EqualsIgnoreCase(email1, email2)) { union.Add(email1); } @@ -900,7 +900,7 @@ namespace Org.BouncyCastle.Pkix // both are a particular mailbox if (email2.IndexOf('@') != -1) { - if (Platform.CompareIgnoreCase(email1, email2) == 0) + if (Platform.EqualsIgnoreCase(email1, email2)) { union.Add(email1); } @@ -911,7 +911,7 @@ namespace Org.BouncyCastle.Pkix } } // email2 specifies a domain - else if (email2.StartsWith(".")) + else if (Platform.StartsWith(email2, ".")) { if (WithinDomain(_sub, email2)) { @@ -926,7 +926,7 @@ namespace Org.BouncyCastle.Pkix // email2 specifies a particular host else { - if (Platform.CompareIgnoreCase(_sub, email2) == 0) + if (Platform.EqualsIgnoreCase(_sub, email2)) { union.Add(email2); } @@ -939,7 +939,7 @@ namespace Org.BouncyCastle.Pkix } } // email1 specifies a domain - else if (email1.StartsWith(".")) + else if (Platform.StartsWith(email1, ".")) { if (email2.IndexOf('@') != -1) { @@ -955,9 +955,9 @@ namespace Org.BouncyCastle.Pkix } } // email2 specifies a domain - else if (email2.StartsWith(".")) + else if (Platform.StartsWith(email2, ".")) { - if (WithinDomain(email1, email2) || Platform.CompareIgnoreCase(email1, email2) == 0) + if (WithinDomain(email1, email2) || Platform.EqualsIgnoreCase(email1, email2)) { union.Add(email2); } @@ -990,7 +990,7 @@ namespace Org.BouncyCastle.Pkix if (email2.IndexOf('@') != -1) { String _sub = email2.Substring(email1.IndexOf('@') + 1); - if (Platform.CompareIgnoreCase(_sub, email1) == 0) + if (Platform.EqualsIgnoreCase(_sub, email1)) { union.Add(email1); } @@ -1001,7 +1001,7 @@ namespace Org.BouncyCastle.Pkix } } // email2 specifies a domain - else if (email2.StartsWith(".")) + else if (Platform.StartsWith(email2, ".")) { if (WithinDomain(email1, email2)) { @@ -1016,7 +1016,7 @@ namespace Org.BouncyCastle.Pkix // email2 specifies a particular host else { - if (Platform.CompareIgnoreCase(email1, email2) == 0) + if (Platform.EqualsIgnoreCase(email1, email2)) { union.Add(email1); } @@ -1122,13 +1122,13 @@ namespace Org.BouncyCastle.Pkix // both are a particular mailbox if (email2.IndexOf('@') != -1) { - if (Platform.CompareIgnoreCase(email1, email2) == 0) + if (Platform.EqualsIgnoreCase(email1, email2)) { intersect.Add(email1); } } // email2 specifies a domain - else if (email2.StartsWith(".")) + else if (Platform.StartsWith(email2, ".")) { if (WithinDomain(_sub, email2)) { @@ -1138,14 +1138,14 @@ namespace Org.BouncyCastle.Pkix // email2 specifies a particular host else { - if (Platform.CompareIgnoreCase(_sub, email2) == 0) + if (Platform.EqualsIgnoreCase(_sub, email2)) { intersect.Add(email1); } } } // email specifies a domain - else if (email1.StartsWith(".")) + else if (Platform.StartsWith(email1, ".")) { if (email2.IndexOf('@') != -1) { @@ -1156,9 +1156,9 @@ namespace Org.BouncyCastle.Pkix } } // email2 specifies a domain - else if (email2.StartsWith(".")) + else if (Platform.StartsWith(email2, ".")) { - if (WithinDomain(email1, email2) || (Platform.CompareIgnoreCase(email1, email2) == 0)) + if (WithinDomain(email1, email2) || Platform.EqualsIgnoreCase(email1, email2)) { intersect.Add(email1); } @@ -1181,13 +1181,13 @@ namespace Org.BouncyCastle.Pkix if (email2.IndexOf('@') != -1) { String _sub = email2.Substring(email2.IndexOf('@') + 1); - if (Platform.CompareIgnoreCase(_sub, email1) == 0) + if (Platform.EqualsIgnoreCase(_sub, email1)) { intersect.Add(email2); } } // email2 specifies a domain - else if (email2.StartsWith(".")) + else if (Platform.StartsWith(email2, ".")) { if (WithinDomain(email1, email2)) { @@ -1197,7 +1197,7 @@ namespace Org.BouncyCastle.Pkix // email2 specifies a particular host else { - if (Platform.CompareIgnoreCase(email1, email2) == 0) + if (Platform.EqualsIgnoreCase(email1, email2)) { intersect.Add(email1); } @@ -1291,13 +1291,13 @@ namespace Org.BouncyCastle.Pkix // both are a particular mailbox if (email2.IndexOf('@') != -1) { - if (Platform.CompareIgnoreCase(email1, email2) == 0) + if (Platform.EqualsIgnoreCase(email1, email2)) { intersect.Add(email1); } } // email2 specifies a domain - else if (email2.StartsWith(".")) + else if (Platform.StartsWith(email2, ".")) { if (WithinDomain(_sub, email2)) { @@ -1307,14 +1307,14 @@ namespace Org.BouncyCastle.Pkix // email2 specifies a particular host else { - if (Platform.CompareIgnoreCase(_sub, email2) == 0) + if (Platform.EqualsIgnoreCase(_sub, email2)) { intersect.Add(email1); } } } // email specifies a domain - else if (email1.StartsWith(".")) + else if (Platform.StartsWith(email1, ".")) { if (email2.IndexOf('@') != -1) { @@ -1325,9 +1325,9 @@ namespace Org.BouncyCastle.Pkix } } // email2 specifies a domain - else if (email2.StartsWith(".")) + else if (Platform.StartsWith(email2, ".")) { - if (WithinDomain(email1, email2) || (Platform.CompareIgnoreCase(email1, email2) == 0)) + if (WithinDomain(email1, email2) || Platform.EqualsIgnoreCase(email1, email2)) { intersect.Add(email1); } @@ -1350,13 +1350,13 @@ namespace Org.BouncyCastle.Pkix if (email2.IndexOf('@') != -1) { String _sub = email2.Substring(email2.IndexOf('@') + 1); - if (Platform.CompareIgnoreCase(_sub, email1) == 0) + if (Platform.EqualsIgnoreCase(_sub, email1)) { intersect.Add(email2); } } // email2 specifies a domain - else if (email2.StartsWith(".")) + else if (Platform.StartsWith(email2, ".")) { if (WithinDomain(email1, email2)) { @@ -1366,7 +1366,7 @@ namespace Org.BouncyCastle.Pkix // email2 specifies a particular host else { - if (Platform.CompareIgnoreCase(email1, email2) == 0) + if (Platform.EqualsIgnoreCase(email1, email2)) { intersect.Add(email1); } @@ -1405,9 +1405,9 @@ namespace Org.BouncyCastle.Pkix { String host = ExtractHostFromURL(uri); // a host - if (!constraint.StartsWith(".")) + if (!Platform.StartsWith(constraint, ".")) { - if (Platform.CompareIgnoreCase(host, constraint) == 0) + if (Platform.EqualsIgnoreCase(host, constraint)) { return true; } @@ -1428,9 +1428,10 @@ namespace Org.BouncyCastle.Pkix // remove ':' after protocol, e.g. http: String sub = url.Substring(url.IndexOf(':') + 1); // extract host from Common Internet Scheme Syntax, e.g. http:// - if (sub.IndexOf("//") != -1) + int idxOfSlashes = Platform.IndexOf(sub, "//"); + if (idxOfSlashes != -1) { - sub = sub.Substring(sub.IndexOf("//") + 2); + sub = sub.Substring(idxOfSlashes + 2); } // first remove port, e.g. http://test.com:21 if (sub.LastIndexOf(':') != -1) diff --git a/crypto/src/pkix/PkixParameters.cs b/crypto/src/pkix/PkixParameters.cs
index 47d3b5e37..01ed9d4fa 100644 --- a/crypto/src/pkix/PkixParameters.cs +++ b/crypto/src/pkix/PkixParameters.cs
@@ -737,7 +737,7 @@ namespace Org.BouncyCastle.Pkix if (!(obj is TrustAnchor)) { throw new InvalidCastException("All elements of set must be " - + "of type " + typeof(TrustAnchor).Name + "."); + + "of type " + typeof(TrustAnchor).FullName + "."); } } this.trustedACIssuers = new HashSet(trustedACIssuers); diff --git a/crypto/src/security/CipherUtilities.cs b/crypto/src/security/CipherUtilities.cs
index cdb711f69..3217f3183 100644 --- a/crypto/src/security/CipherUtilities.cs +++ b/crypto/src/security/CipherUtilities.cs
@@ -54,6 +54,10 @@ namespace Org.BouncyCastle.Security SERPENT, SKIPJACK, TEA, + THREEFISH_256, + THREEFISH_512, + THREEFISH_1024, + TNEPRES, TWOFISH, VMPC, VMPC_KSA3, @@ -278,9 +282,9 @@ namespace Org.BouncyCastle.Security - if (algorithm.StartsWith("PBE")) + if (Platform.StartsWith(algorithm, "PBE")) { - if (algorithm.EndsWith("-CBC")) + if (Platform.EndsWith(algorithm, "-CBC")) { if (algorithm == "PBEWITHSHA1ANDDES-CBC") { @@ -305,7 +309,7 @@ namespace Org.BouncyCastle.Security new CbcBlockCipher(new RC2Engine())); } } - else if (algorithm.EndsWith("-BC") || algorithm.EndsWith("-OPENSSL")) + else if (Platform.EndsWith(algorithm, "-BC") || Platform.EndsWith(algorithm, "-OPENSSL")) { if (Strings.IsOneOf(algorithm, "PBEWITHSHAAND128BITAES-CBC-BC", @@ -432,6 +436,18 @@ namespace Org.BouncyCastle.Security case CipherAlgorithm.TEA: blockCipher = new TeaEngine(); break; + case CipherAlgorithm.THREEFISH_256: + blockCipher = new ThreefishEngine(ThreefishEngine.BLOCKSIZE_256); + break; + case CipherAlgorithm.THREEFISH_512: + blockCipher = new ThreefishEngine(ThreefishEngine.BLOCKSIZE_512); + break; + case CipherAlgorithm.THREEFISH_1024: + blockCipher = new ThreefishEngine(ThreefishEngine.BLOCKSIZE_1024); + break; + case CipherAlgorithm.TNEPRES: + blockCipher = new TnepresEngine(); + break; case CipherAlgorithm.TWOFISH: blockCipher = new TwofishEngine(); break; @@ -725,6 +741,10 @@ namespace Org.BouncyCastle.Security case CipherAlgorithm.SERPENT: return new SerpentEngine(); case CipherAlgorithm.SKIPJACK: return new SkipjackEngine(); case CipherAlgorithm.TEA: return new TeaEngine(); + case CipherAlgorithm.THREEFISH_256: return new ThreefishEngine(ThreefishEngine.BLOCKSIZE_256); + case CipherAlgorithm.THREEFISH_512: return new ThreefishEngine(ThreefishEngine.BLOCKSIZE_512); + case CipherAlgorithm.THREEFISH_1024: return new ThreefishEngine(ThreefishEngine.BLOCKSIZE_1024); + case CipherAlgorithm.TNEPRES: return new TnepresEngine(); case CipherAlgorithm.TWOFISH: return new TwofishEngine(); case CipherAlgorithm.XTEA: return new XteaEngine(); default: diff --git a/crypto/src/security/GeneratorUtilities.cs b/crypto/src/security/GeneratorUtilities.cs
index 45fbc9425..3beebd05b 100644 --- a/crypto/src/security/GeneratorUtilities.cs +++ b/crypto/src/security/GeneratorUtilities.cs
@@ -109,6 +109,10 @@ namespace Org.BouncyCastle.Security AddKgAlgorithm("SERPENT"); AddKgAlgorithm("SKIPJACK"); AddKgAlgorithm("TEA"); + AddKgAlgorithm("THREEFISH-256"); + AddKgAlgorithm("THREEFISH-512"); + AddKgAlgorithm("THREEFISH-1024"); + AddKgAlgorithm("TNEPRES"); AddKgAlgorithm("TWOFISH"); AddKgAlgorithm("VMPC"); AddKgAlgorithm("VMPC-KSA3"); @@ -178,14 +182,13 @@ namespace Org.BouncyCastle.Security "RC2", "RC4", "RC5", "SALSA20", "SEED", "TEA", "XTEA", "VMPC", "VMPC-KSA3"); AddDefaultKeySizeEntries(160, "HMACRIPEMD160", "HMACSHA1"); AddDefaultKeySizeEntries(192, "AES", "AES192", "CAMELLIA192", "DESEDE3", "HMACTIGER", - "RIJNDAEL", "SERPENT"); - AddDefaultKeySizeEntries(224, "HMACSHA224"); + "RIJNDAEL", "SERPENT", "TNEPRES"); + AddDefaultKeySizeEntries(224, "HMACSHA224", "HMACSHA512/224"); AddDefaultKeySizeEntries(256, "AES256", "CAMELLIA", "CAMELLIA256", "CAST6", "GOST28147", - "HC256", "HMACSHA256", "RC5-64", "RC6", "TWOFISH"); + "HC256", "HMACSHA256", "HMACSHA512/256", "RC5-64", "RC6", "THREEFISH-256", "TWOFISH"); AddDefaultKeySizeEntries(384, "HMACSHA384"); - AddDefaultKeySizeEntries(512, "HMACSHA512"); - AddDefaultKeySizeEntries(224, "HMACSHA512/224"); - AddDefaultKeySizeEntries(256, "HMACSHA512/256"); + AddDefaultKeySizeEntries(512, "HMACSHA512", "THREEFISH-512"); + AddDefaultKeySizeEntries(1024, "THREEFISH-1024"); } private static void AddDefaultKeySizeEntries(int size, params string[] algorithms) @@ -299,7 +302,7 @@ namespace Org.BouncyCastle.Security return new DsaKeyPairGenerator(); // "EC", "ECDH", "ECDHC", "ECDSA", "ECGOST3410", "ECMQV" - if (canonicalName.StartsWith("EC")) + if (Platform.StartsWith(canonicalName, "EC")) return new ECKeyPairGenerator(canonicalName); if (canonicalName == "ELGAMAL") diff --git a/crypto/src/security/MacUtilities.cs b/crypto/src/security/MacUtilities.cs
index d7fe91142..fab9b1d41 100644 --- a/crypto/src/security/MacUtilities.cs +++ b/crypto/src/security/MacUtilities.cs
@@ -1,4 +1,6 @@ +using System; using System.Collections; +using System.Globalization; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Iana; @@ -112,15 +114,15 @@ namespace Org.BouncyCastle.Security mechanism = upper; } - if (mechanism.StartsWith("PBEWITH")) + if (Platform.StartsWith(mechanism, "PBEWITH")) { mechanism = mechanism.Substring("PBEWITH".Length); } - if (mechanism.StartsWith("HMAC")) + if (Platform.StartsWith(mechanism, "HMAC")) { string digestName; - if (mechanism.StartsWith("HMAC-") || mechanism.StartsWith("HMAC/")) + if (Platform.StartsWith(mechanism, "HMAC-") || Platform.StartsWith(mechanism, "HMAC/")) { digestName = mechanism.Substring(5); } diff --git a/crypto/src/security/ParameterUtilities.cs b/crypto/src/security/ParameterUtilities.cs
index b2d7c0dff..c12155878 100644 --- a/crypto/src/security/ParameterUtilities.cs +++ b/crypto/src/security/ParameterUtilities.cs
@@ -104,6 +104,10 @@ namespace Org.BouncyCastle.Security AddAlgorithm("SERPENT"); AddAlgorithm("SKIPJACK"); AddAlgorithm("TEA"); + AddAlgorithm("THREEFISH-256"); + AddAlgorithm("THREEFISH-512"); + AddAlgorithm("THREEFISH-1024"); + AddAlgorithm("TNEPRES"); AddAlgorithm("TWOFISH"); AddAlgorithm("VMPC"); AddAlgorithm("VMPC-KSA3"); diff --git a/crypto/src/security/PbeUtilities.cs b/crypto/src/security/PbeUtilities.cs
index 56d68ba0a..33f31e5b4 100644 --- a/crypto/src/security/PbeUtilities.cs +++ b/crypto/src/security/PbeUtilities.cs
@@ -345,7 +345,7 @@ namespace Org.BouncyCastle.Security AlgorithmIdentifier algID, char[] password) { - return GenerateCipherParameters(algID.ObjectID.Id, password, false, algID.Parameters); + return GenerateCipherParameters(algID.Algorithm.Id, password, false, algID.Parameters); } public static ICipherParameters GenerateCipherParameters( @@ -353,7 +353,7 @@ namespace Org.BouncyCastle.Security char[] password, bool wrongPkcs12Zero) { - return GenerateCipherParameters(algID.ObjectID.Id, password, wrongPkcs12Zero, algID.Parameters); + return GenerateCipherParameters(algID.Algorithm.Id, password, wrongPkcs12Zero, algID.Parameters); } public static ICipherParameters GenerateCipherParameters( @@ -401,10 +401,10 @@ namespace Org.BouncyCastle.Security { PbeS2Parameters s2p = PbeS2Parameters.GetInstance(pbeParameters.ToAsn1Object()); AlgorithmIdentifier encScheme = s2p.EncryptionScheme; - DerObjectIdentifier encOid = encScheme.ObjectID; + DerObjectIdentifier encOid = encScheme.Algorithm; Asn1Object encParams = encScheme.Parameters.ToAsn1Object(); - // TODO What about s2p.KeyDerivationFunc.ObjectID? + // TODO What about s2p.KeyDerivationFunc.Algorithm? Pbkdf2Params pbeParams = Pbkdf2Params.GetInstance(s2p.KeyDerivationFunc.Parameters.ToAsn1Object()); byte[] iv; @@ -444,7 +444,7 @@ namespace Org.BouncyCastle.Security } } } - else if (mechanism.StartsWith("PBEwithSHA-1")) + else if (Platform.StartsWith(mechanism, "PBEwithSHA-1")) { PbeParametersGenerator generator = MakePbeGenerator( (string) algorithmType[mechanism], new Sha1Digest(), keyBytes, salt, iterationCount); @@ -494,7 +494,7 @@ namespace Org.BouncyCastle.Security parameters = generator.GenerateDerivedParameters("RC2", 64, 64); } } - else if (mechanism.StartsWith("PBEwithSHA-256")) + else if (Platform.StartsWith(mechanism, "PBEwithSHA-256")) { PbeParametersGenerator generator = MakePbeGenerator( (string) algorithmType[mechanism], new Sha256Digest(), keyBytes, salt, iterationCount); @@ -512,7 +512,7 @@ namespace Org.BouncyCastle.Security parameters = generator.GenerateDerivedParameters("AES", 256, 128); } } - else if (mechanism.StartsWith("PBEwithMD5")) + else if (Platform.StartsWith(mechanism, "PBEwithMD5")) { PbeParametersGenerator generator = MakePbeGenerator( (string)algorithmType[mechanism], new MD5Digest(), keyBytes, salt, iterationCount); @@ -538,7 +538,7 @@ namespace Org.BouncyCastle.Security parameters = generator.GenerateDerivedParameters("AES", 256, 128); } } - else if (mechanism.StartsWith("PBEwithMD2")) + else if (Platform.StartsWith(mechanism, "PBEwithMD2")) { PbeParametersGenerator generator = MakePbeGenerator( (string)algorithmType[mechanism], new MD2Digest(), keyBytes, salt, iterationCount); @@ -551,7 +551,7 @@ namespace Org.BouncyCastle.Security parameters = generator.GenerateDerivedParameters("RC2", 64, 64); } } - else if (mechanism.StartsWith("PBEwithHmac")) + else if (Platform.StartsWith(mechanism, "PBEwithHmac")) { string digestName = mechanism.Substring("PBEwithHmac".Length); IDigest digest = DigestUtilities.GetDigest(digestName); @@ -577,13 +577,13 @@ namespace Org.BouncyCastle.Security public static object CreateEngine( AlgorithmIdentifier algID) { - string algorithm = algID.ObjectID.Id; + string algorithm = algID.Algorithm.Id; if (IsPkcs5Scheme2(algorithm)) { PbeS2Parameters s2p = PbeS2Parameters.GetInstance(algID.Parameters.ToAsn1Object()); AlgorithmIdentifier encScheme = s2p.EncryptionScheme; - return CipherUtilities.GetCipher(encScheme.ObjectID); + return CipherUtilities.GetCipher(encScheme.Algorithm); } return CreateEngine(algorithm); @@ -594,39 +594,39 @@ namespace Org.BouncyCastle.Security { string mechanism = (string)algorithms[Platform.ToUpperInvariant(algorithm)]; - if (mechanism.StartsWith("PBEwithHmac")) + if (Platform.StartsWith(mechanism, "PBEwithHmac")) { string digestName = mechanism.Substring("PBEwithHmac".Length); return MacUtilities.GetMac("HMAC/" + digestName); } - if (mechanism.StartsWith("PBEwithMD2") - || mechanism.StartsWith("PBEwithMD5") - || mechanism.StartsWith("PBEwithSHA-1") - || mechanism.StartsWith("PBEwithSHA-256")) + if (Platform.StartsWith(mechanism, "PBEwithMD2") + || Platform.StartsWith(mechanism, "PBEwithMD5") + || Platform.StartsWith(mechanism, "PBEwithSHA-1") + || Platform.StartsWith(mechanism, "PBEwithSHA-256")) { - if (mechanism.EndsWith("AES-CBC-BC") || mechanism.EndsWith("AES-CBC-OPENSSL")) + if (Platform.EndsWith(mechanism, "AES-CBC-BC") || Platform.EndsWith(mechanism, "AES-CBC-OPENSSL")) { return CipherUtilities.GetCipher("AES/CBC"); } - if (mechanism.EndsWith("DES-CBC")) + if (Platform.EndsWith(mechanism, "DES-CBC")) { return CipherUtilities.GetCipher("DES/CBC"); } - if (mechanism.EndsWith("DESEDE-CBC")) + if (Platform.EndsWith(mechanism, "DESEDE-CBC")) { return CipherUtilities.GetCipher("DESEDE/CBC"); } - if (mechanism.EndsWith("RC2-CBC")) + if (Platform.EndsWith(mechanism, "RC2-CBC")) { return CipherUtilities.GetCipher("RC2/CBC"); } - if (mechanism.EndsWith("RC4")) + if (Platform.EndsWith(mechanism, "RC4")) { return CipherUtilities.GetCipher("RC4"); } @@ -643,7 +643,7 @@ namespace Org.BouncyCastle.Security private static ICipherParameters FixDesParity(string mechanism, ICipherParameters parameters) { - if (!mechanism.EndsWith("DES-CBC") & !mechanism.EndsWith("DESEDE-CBC")) + if (!Platform.EndsWith(mechanism, "DES-CBC") && !Platform.EndsWith(mechanism, "DESEDE-CBC")) { return parameters; } diff --git a/crypto/src/security/PrivateKeyFactory.cs b/crypto/src/security/PrivateKeyFactory.cs
index edc5ef85a..8c2ecfdb0 100644 --- a/crypto/src/security/PrivateKeyFactory.cs +++ b/crypto/src/security/PrivateKeyFactory.cs
@@ -45,7 +45,7 @@ namespace Org.BouncyCastle.Security PrivateKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.PrivateKeyAlgorithm; - DerObjectIdentifier algOid = algID.ObjectID; + DerObjectIdentifier algOid = algID.Algorithm; // TODO See RSAUtil.isRsaOid in Java build if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) @@ -117,8 +117,7 @@ namespace Org.BouncyCastle.Security x9 = new X9ECParameters((Asn1Sequence)para.Parameters); } - ECPrivateKeyStructure ec = new ECPrivateKeyStructure( - Asn1Sequence.GetInstance(keyInfo.ParsePrivateKey())); + ECPrivateKeyStructure ec = ECPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey()); BigInteger d = ec.GetKey(); if (para.IsNamedCurve) @@ -134,24 +133,24 @@ namespace Org.BouncyCastle.Security Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); + ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet); + + if (ecP == null) + throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key"); + Asn1Object privKey = keyInfo.ParsePrivateKey(); ECPrivateKeyStructure ec; if (privKey is DerInteger) { // TODO Do we need to pass any parameters here? - ec = new ECPrivateKeyStructure(((DerInteger)privKey).Value); + ec = new ECPrivateKeyStructure(ecP.N.BitLength, ((DerInteger)privKey).Value); } else { ec = ECPrivateKeyStructure.GetInstance(privKey); } - ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet); - - if (ecP == null) - throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key"); - return new ECPrivateKeyParameters("ECGOST3410", ec.GetKey(), gostParams.PublicKeyParamSet); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94)) diff --git a/crypto/src/security/PublicKeyFactory.cs b/crypto/src/security/PublicKeyFactory.cs
index 8c0be4f70..f1b28b774 100644 --- a/crypto/src/security/PublicKeyFactory.cs +++ b/crypto/src/security/PublicKeyFactory.cs
@@ -44,7 +44,7 @@ namespace Org.BouncyCastle.Security SubjectPublicKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.AlgorithmID; - DerObjectIdentifier algOid = algID.ObjectID; + DerObjectIdentifier algOid = algID.Algorithm; // TODO See RSAUtil.isRsaOid in Java build if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) diff --git a/crypto/src/security/SecureRandom.cs b/crypto/src/security/SecureRandom.cs
index 5bad57a14..cb831acc2 100644 --- a/crypto/src/security/SecureRandom.cs +++ b/crypto/src/security/SecureRandom.cs
@@ -68,11 +68,18 @@ namespace Org.BouncyCastle.Security if (autoSeed) { prng.AddSeedMaterial(NextCounterValue()); - prng.AddSeedMaterial(GetSeed(digest.GetDigestSize())); + prng.AddSeedMaterial(GetNextBytes(Master, digest.GetDigestSize())); } return prng; } + public static byte[] GetNextBytes(SecureRandom secureRandom, int length) + { + byte[] result = new byte[length]; + secureRandom.NextBytes(result); + return result; + } + /// <summary> /// Create and auto-seed an instance based on the given algorithm. /// </summary> @@ -91,7 +98,7 @@ namespace Org.BouncyCastle.Security public static SecureRandom GetInstance(string algorithm, bool autoSeed) { string upper = Platform.ToUpperInvariant(algorithm); - if (upper.EndsWith("PRNG")) + if (Platform.EndsWith(upper, "PRNG")) { string digestName = upper.Substring(0, upper.Length - "PRNG".Length); DigestRandomGenerator prng = CreatePrng(digestName, autoSeed); @@ -104,12 +111,10 @@ namespace Org.BouncyCastle.Security throw new ArgumentException("Unrecognised PRNG algorithm: " + algorithm, "algorithm"); } + [Obsolete("Call GenerateSeed() on a SecureRandom instance instead")] public static byte[] GetSeed(int length) { -#if NETCF_1_0 - lock (master) -#endif - return Master.GenerateSeed(length); + return GetNextBytes(Master, length); } protected readonly IRandomGenerator generator; @@ -145,11 +150,7 @@ namespace Org.BouncyCastle.Security public virtual byte[] GenerateSeed(int length) { - SetSeed(DateTime.Now.Ticks); - - byte[] rv = new byte[length]; - NextBytes(rv); - return rv; + return GetNextBytes(Master, length); } public virtual void SetSeed(byte[] seed) @@ -164,13 +165,7 @@ namespace Org.BouncyCastle.Security public override int Next() { - for (;;) - { - int i = NextInt() & int.MaxValue; - - if (i != int.MaxValue) - return i; - } + return NextInt() & int.MaxValue; } public override int Next(int maxValue) @@ -184,11 +179,9 @@ namespace Org.BouncyCastle.Security } // Test whether maxValue is a power of 2 - if ((maxValue & -maxValue) == maxValue) + if ((maxValue & (maxValue - 1)) == 0) { - int val = NextInt() & int.MaxValue; - long lr = ((long) maxValue * (long) val) >> 31; - return (int) lr; + return NextInt() & (maxValue - 1); } int bits, result; @@ -244,16 +237,17 @@ namespace Org.BouncyCastle.Security public virtual int NextInt() { - byte[] intBytes = new byte[4]; - NextBytes(intBytes); - - int result = 0; - for (int i = 0; i < 4; i++) - { - result = (result << 8) + (intBytes[i] & 0xff); - } - - return result; + byte[] bytes = new byte[4]; + NextBytes(bytes); + + uint result = bytes[0]; + result <<= 8; + result |= bytes[1]; + result <<= 8; + result |= bytes[2]; + result <<= 8; + result |= bytes[3]; + return (int)result; } public virtual long NextLong() diff --git a/crypto/src/security/SignerUtilities.cs b/crypto/src/security/SignerUtilities.cs
index bd1515147..9a4915b46 100644 --- a/crypto/src/security/SignerUtilities.cs +++ b/crypto/src/security/SignerUtilities.cs
@@ -312,7 +312,7 @@ namespace Org.BouncyCastle.Security return GetPssX509Parameters("SHA-1"); } - if (mechanism.EndsWith("withRSAandMGF1")) + if (Platform.EndsWith(mechanism, "withRSAandMGF1")) { string digestName = mechanism.Substring(0, mechanism.Length - "withRSAandMGF1".Length); return GetPssX509Parameters(digestName); @@ -534,10 +534,10 @@ namespace Org.BouncyCastle.Security return new Iso9796d2Signer(new RsaBlindedEngine(), new RipeMD160Digest(), true); } - if (mechanism.EndsWith("/X9.31")) + if (Platform.EndsWith(mechanism, "/X9.31")) { string x931 = mechanism.Substring(0, mechanism.Length - "/X9.31".Length); - int withPos = x931.IndexOf("WITH"); + int withPos = Platform.IndexOf(x931, "WITH"); if (withPos > 0) { int endPos = withPos + "WITH".Length; diff --git a/crypto/src/tsp/TimeStampRequest.cs b/crypto/src/tsp/TimeStampRequest.cs
index 6b9699379..f54d33e04 100644 --- a/crypto/src/tsp/TimeStampRequest.cs +++ b/crypto/src/tsp/TimeStampRequest.cs
@@ -77,7 +77,7 @@ namespace Org.BouncyCastle.Tsp public string MessageImprintAlgOid { - get { return req.MessageImprint.HashAlgorithm.ObjectID.Id; } + get { return req.MessageImprint.HashAlgorithm.Algorithm.Id; } } public byte[] GetMessageImprintDigest() diff --git a/crypto/src/tsp/TimeStampResponseGenerator.cs b/crypto/src/tsp/TimeStampResponseGenerator.cs
index 8d798de67..b596f8d97 100644 --- a/crypto/src/tsp/TimeStampResponseGenerator.cs +++ b/crypto/src/tsp/TimeStampResponseGenerator.cs
@@ -166,9 +166,8 @@ namespace Org.BouncyCastle.Tsp class FailInfo : DerBitString { - internal FailInfo( - int failInfoValue) - : base(GetBytes(failInfoValue), GetPadBits(failInfoValue)) + internal FailInfo(int failInfoValue) + : base(failInfoValue) { } } diff --git a/crypto/src/tsp/TimeStampToken.cs b/crypto/src/tsp/TimeStampToken.cs
index 51a9592dc..105208a7d 100644 --- a/crypto/src/tsp/TimeStampToken.cs +++ b/crypto/src/tsp/TimeStampToken.cs
@@ -271,10 +271,10 @@ namespace Org.BouncyCastle.Tsp if (certID != null) return "SHA-1"; - if (NistObjectIdentifiers.IdSha256.Equals(certIDv2.HashAlgorithm.ObjectID)) + if (NistObjectIdentifiers.IdSha256.Equals(certIDv2.HashAlgorithm.Algorithm)) return "SHA-256"; - return certIDv2.HashAlgorithm.ObjectID.Id; + return certIDv2.HashAlgorithm.Algorithm.Id; } public AlgorithmIdentifier GetHashAlgorithm() diff --git a/crypto/src/tsp/TimeStampTokenInfo.cs b/crypto/src/tsp/TimeStampTokenInfo.cs
index 5027a87c4..cdef826bc 100644 --- a/crypto/src/tsp/TimeStampTokenInfo.cs +++ b/crypto/src/tsp/TimeStampTokenInfo.cs
@@ -86,7 +86,7 @@ namespace Org.BouncyCastle.Tsp public string MessageImprintAlgOid { - get { return tstInfo.MessageImprint.HashAlgorithm.ObjectID.Id; } + get { return tstInfo.MessageImprint.HashAlgorithm.Algorithm.Id; } } public byte[] GetMessageImprintDigest() diff --git a/crypto/src/util/Arrays.cs b/crypto/src/util/Arrays.cs
index 1f9711555..df9b4e7ee 100644 --- a/crypto/src/util/Arrays.cs +++ b/crypto/src/util/Arrays.cs
@@ -591,6 +591,35 @@ namespace Org.BouncyCastle.Utilities return rv; } + public static byte[] ConcatenateAll(params byte[][] vs) + { + byte[][] nonNull = new byte[vs.Length][]; + int count = 0; + int totalLength = 0; + + for (int i = 0; i < vs.Length; ++i) + { + byte[] v = vs[i]; + if (v != null) + { + nonNull[count++] = v; + totalLength += v.Length; + } + } + + byte[] result = new byte[totalLength]; + int pos = 0; + + for (int j = 0; j < count; ++j) + { + byte[] v = nonNull[j]; + Array.Copy(v, 0, result, pos, v.Length); + pos += v.Length; + } + + return result; + } + public static int[] Concatenate(int[] a, int[] b) { if (a == null) diff --git a/crypto/src/util/Enums.cs b/crypto/src/util/Enums.cs
index 25b218667..9e908c4c0 100644 --- a/crypto/src/util/Enums.cs +++ b/crypto/src/util/Enums.cs
@@ -14,7 +14,7 @@ namespace Org.BouncyCastle.Utilities { internal static Enum GetEnumValue(System.Type enumType, string s) { - if (!enumType.IsEnum) + if (!IsEnumType(enumType)) throw new ArgumentException("Not an enumeration type", "enumType"); // We only want to parse single named constants @@ -39,10 +39,10 @@ namespace Org.BouncyCastle.Utilities internal static Array GetEnumValues(System.Type enumType) { - if (!enumType.IsEnum) + if (!IsEnumType(enumType)) throw new ArgumentException("Not an enumeration type", "enumType"); -#if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE +#if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT IList result = Platform.CreateArrayList(); FieldInfo[] fields = enumType.GetFields(BindingFlags.Static | BindingFlags.Public); foreach (FieldInfo field in fields) @@ -65,5 +65,14 @@ namespace Org.BouncyCastle.Utilities int pos = (int)(DateTimeUtilities.CurrentUnixMs() & int.MaxValue) % values.Length; return (Enum)values.GetValue(pos); } + + internal static bool IsEnumType(System.Type t) + { +#if NEW_REFLECTION + return t.GetTypeInfo().IsEnum; +#else + return t.IsEnum; +#endif + } } } diff --git a/crypto/src/util/Platform.cs b/crypto/src/util/Platform.cs
index bfed0950a..86484854d 100644 --- a/crypto/src/util/Platform.cs +++ b/crypto/src/util/Platform.cs
@@ -13,13 +13,15 @@ namespace Org.BouncyCastle.Utilities { internal abstract class Platform { + private static readonly CompareInfo InvariantCompareInfo = CultureInfo.InvariantCulture.CompareInfo; + #if NETCF_1_0 || NETCF_2_0 private static string GetNewLine() { MemoryStream buf = new MemoryStream(); StreamWriter w = new StreamWriter(buf, Encoding.UTF8); w.WriteLine(); - w.Close(); + Dispose(w); byte[] bs = buf.ToArray(); return Encoding.UTF8.GetString(bs, 0, bs.Length); } @@ -30,14 +32,12 @@ namespace Org.BouncyCastle.Utilities } #endif - internal static int CompareIgnoreCase(string a, string b) + internal static bool EqualsIgnoreCase(string a, string b) { -#if SILVERLIGHT - return String.Compare(a, b, StringComparison.InvariantCultureIgnoreCase); -#elif PORTABLE - return String.Compare(a, b, CultureInfo.InvariantCulture, CompareOptions.IgnoreCase); +#if PORTABLE + return String.Equals(a, b, StringComparison.OrdinalIgnoreCase); #else - return String.Compare(a, b, true); + return ToUpperInvariant(a) == ToUpperInvariant(b); #endif } @@ -184,5 +184,46 @@ namespace Org.BouncyCastle.Utilities } internal static readonly string NewLine = GetNewLine(); + +#if PORTABLE + internal static void Dispose(IDisposable d) + { + d.Dispose(); + } +#else + internal static void Dispose(Stream s) + { + s.Close(); + } + internal static void Dispose(TextWriter t) + { + t.Close(); + } +#endif + + internal static int IndexOf(string source, string value) + { + return InvariantCompareInfo.IndexOf(source, value, CompareOptions.Ordinal); + } + + internal static int LastIndexOf(string source, string value) + { + return InvariantCompareInfo.LastIndexOf(source, value, CompareOptions.Ordinal); + } + + internal static bool StartsWith(string source, string prefix) + { + return InvariantCompareInfo.IsPrefix(source, prefix, CompareOptions.Ordinal); + } + + internal static bool EndsWith(string source, string suffix) + { + return InvariantCompareInfo.IsSuffix(source, suffix, CompareOptions.Ordinal); + } + + internal static string GetTypeName(object obj) + { + return obj.GetType().FullName; + } } } diff --git a/crypto/src/util/TypeExtensions.cs b/crypto/src/util/TypeExtensions.cs new file mode 100644
index 000000000..e2aeae4dc --- /dev/null +++ b/crypto/src/util/TypeExtensions.cs
@@ -0,0 +1,17 @@ +#if NEW_REFLECTION + +using System; +using System.Reflection; + +namespace Org.BouncyCastle +{ + internal static class TypeExtensions + { + public static bool IsInstanceOfType(this Type type, object instance) + { + return instance != null && type.GetTypeInfo().IsAssignableFrom(instance.GetType().GetTypeInfo()); + } + } +} + +#endif diff --git a/crypto/src/util/io/BaseInputStream.cs b/crypto/src/util/io/BaseInputStream.cs
index 3ff4a1957..a5613d801 100644 --- a/crypto/src/util/io/BaseInputStream.cs +++ b/crypto/src/util/io/BaseInputStream.cs
@@ -11,8 +11,25 @@ namespace Org.BouncyCastle.Utilities.IO public sealed override bool CanRead { get { return !closed; } } public sealed override bool CanSeek { get { return false; } } public sealed override bool CanWrite { get { return false; } } - public override void Close() { closed = true; } - public sealed override void Flush() {} + +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + closed = true; + } + base.Dispose(disposing); + } +#else + public override void Close() + { + closed = true; + base.Close(); + } +#endif + + public sealed override void Flush() {} public sealed override long Length { get { throw new NotSupportedException(); } } public sealed override long Position { diff --git a/crypto/src/util/io/BaseOutputStream.cs b/crypto/src/util/io/BaseOutputStream.cs
index 6e6c6d346..a0608d111 100644 --- a/crypto/src/util/io/BaseOutputStream.cs +++ b/crypto/src/util/io/BaseOutputStream.cs
@@ -11,8 +11,25 @@ namespace Org.BouncyCastle.Utilities.IO public sealed override bool CanRead { get { return false; } } public sealed override bool CanSeek { get { return false; } } public sealed override bool CanWrite { get { return !closed; } } - public override void Close() { closed = true; } - public override void Flush() {} + +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + closed = true; + } + base.Dispose(disposing); + } +#else + public override void Close() + { + closed = true; + base.Close(); + } +#endif + + public override void Flush() { } public sealed override long Length { get { throw new NotSupportedException(); } } public sealed override long Position { diff --git a/crypto/src/util/io/FilterStream.cs b/crypto/src/util/io/FilterStream.cs
index 260ce1789..a92dee3e5 100644 --- a/crypto/src/util/io/FilterStream.cs +++ b/crypto/src/util/io/FilterStream.cs
@@ -29,10 +29,22 @@ namespace Org.BouncyCastle.Utilities.IO get { return s.Position; } set { s.Position = value; } } +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + Platform.Dispose(s); + } + base.Dispose(disposing); + } +#else public override void Close() { - s.Close(); + Platform.Dispose(s); + base.Close(); } +#endif public override void Flush() { s.Flush(); diff --git a/crypto/src/util/io/TeeInputStream.cs b/crypto/src/util/io/TeeInputStream.cs
index 373df4502..6996f3fbb 100644 --- a/crypto/src/util/io/TeeInputStream.cs +++ b/crypto/src/util/io/TeeInputStream.cs
@@ -18,13 +18,26 @@ namespace Org.BouncyCastle.Utilities.IO this.tee = tee; } - public override void Close() +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + Platform.Dispose(input); + Platform.Dispose(tee); + } + base.Dispose(disposing); + } +#else + public override void Close() { - input.Close(); - tee.Close(); + Platform.Dispose(input); + Platform.Dispose(tee); + base.Close(); } +#endif - public override int Read(byte[] buf, int off, int len) + public override int Read(byte[] buf, int off, int len) { int i = input.Read(buf, off, len); diff --git a/crypto/src/util/io/TeeOutputStream.cs b/crypto/src/util/io/TeeOutputStream.cs
index fe3a7586a..a6c7fd5b5 100644 --- a/crypto/src/util/io/TeeOutputStream.cs +++ b/crypto/src/util/io/TeeOutputStream.cs
@@ -18,13 +18,26 @@ namespace Org.BouncyCastle.Utilities.IO this.tee = tee; } - public override void Close() +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + Platform.Dispose(output); + Platform.Dispose(tee); + } + base.Dispose(disposing); + } +#else + public override void Close() { - output.Close(); - tee.Close(); + Platform.Dispose(output); + Platform.Dispose(tee); + base.Close(); } +#endif - public override void Write(byte[] buffer, int offset, int count) + public override void Write(byte[] buffer, int offset, int count) { output.Write(buffer, offset, count); tee.Write(buffer, offset, count); diff --git a/crypto/src/util/io/pem/PemReader.cs b/crypto/src/util/io/pem/PemReader.cs
index b3284705d..bf712b6de 100644 --- a/crypto/src/util/io/pem/PemReader.cs +++ b/crypto/src/util/io/pem/PemReader.cs
@@ -35,7 +35,7 @@ namespace Org.BouncyCastle.Utilities.IO.Pem { string line = reader.ReadLine(); - if (line != null && line.StartsWith(BeginString)) + if (line != null && Platform.StartsWith(line, BeginString)) { line = line.Substring(BeginString.Length); int index = line.IndexOf('-'); @@ -56,7 +56,7 @@ namespace Org.BouncyCastle.Utilities.IO.Pem string line; while ((line = reader.ReadLine()) != null - && line.IndexOf(endMarker) == -1) + && Platform.IndexOf(line, endMarker) == -1) { int colonPos = line.IndexOf(':'); @@ -69,8 +69,10 @@ namespace Org.BouncyCastle.Utilities.IO.Pem // Process field string fieldName = line.Substring(0, colonPos).Trim(); - if (fieldName.StartsWith("X-")) - fieldName = fieldName.Substring(2); + if (Platform.StartsWith(fieldName, "X-")) + { + fieldName = fieldName.Substring(2); + } string fieldValue = line.Substring(colonPos + 1).Trim(); diff --git a/crypto/src/util/net/IPAddress.cs b/crypto/src/util/net/IPAddress.cs
index 2a30a15f0..38c124590 100644 --- a/crypto/src/util/net/IPAddress.cs +++ b/crypto/src/util/net/IPAddress.cs
@@ -85,7 +85,7 @@ namespace Org.BouncyCastle.Utilities.Net public static bool IsValidIPv4WithNetmask( string address) { - int index = address.IndexOf("/"); + int index = address.IndexOf('/'); string mask = address.Substring(index + 1); return (index > 0) && IsValidIPv4(address.Substring(0, index)) @@ -95,7 +95,7 @@ namespace Org.BouncyCastle.Utilities.Net public static bool IsValidIPv6WithNetmask( string address) { - int index = address.IndexOf("/"); + int index = address.IndexOf('/'); string mask = address.Substring(index + 1); return (index > 0) && (IsValidIPv6(address.Substring(0, index)) diff --git a/crypto/src/util/zlib/ZDeflaterOutputStream.cs b/crypto/src/util/zlib/ZDeflaterOutputStream.cs
index 1d88847bd..d0f0bcb8d 100644 --- a/crypto/src/util/zlib/ZDeflaterOutputStream.cs +++ b/crypto/src/util/zlib/ZDeflaterOutputStream.cs
@@ -136,6 +136,24 @@ namespace Org.BouncyCastle.Utilities.Zlib { z=null; } +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + try{ + try{Finish();} + catch (IOException) {} + } + finally{ + End(); + Platform.Dispose(outp); + outp=null; + } + } + base.Dispose(disposing); + } +#else public override void Close() { try{ try{Finish();} @@ -143,9 +161,11 @@ namespace Org.BouncyCastle.Utilities.Zlib { } finally{ End(); - outp.Close(); + Platform.Dispose(outp); outp=null; } + base.Close(); } +#endif } } diff --git a/crypto/src/util/zlib/ZInflaterInputStream.cs b/crypto/src/util/zlib/ZInflaterInputStream.cs
index 5a3ff5aa6..ef742bb00 100644 --- a/crypto/src/util/zlib/ZInflaterInputStream.cs +++ b/crypto/src/util/zlib/ZInflaterInputStream.cs
@@ -114,10 +114,23 @@ namespace Org.BouncyCastle.Utilities.Zlib { public override void WriteByte(byte b) { } - public override void Close() { - inp.Close(); +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + Platform.Dispose(inp); + } + base.Dispose(disposing); } - +#else + public override void Close() + { + Platform.Dispose(inp); + base.Close(); + } +#endif + public override int ReadByte() { if(Read(buf1, 0, 1)<=0) return -1; diff --git a/crypto/src/util/zlib/ZInputStream.cs b/crypto/src/util/zlib/ZInputStream.cs
index d1e1ba160..4b7351555 100644 --- a/crypto/src/util/zlib/ZInputStream.cs +++ b/crypto/src/util/zlib/ZInputStream.cs
@@ -93,14 +93,30 @@ namespace Org.BouncyCastle.Utilities.Zlib public sealed override bool CanSeek { get { return false; } } public sealed override bool CanWrite { get { return false; } } - public override void Close() +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (closed) + return; + + closed = true; + Platform.Dispose(input); + } + base.Dispose(disposing); + } +#else + public override void Close() { - if (!closed) - { - closed = true; - input.Close(); - } + if (closed) + return; + + closed = true; + Platform.Dispose(input); + base.Close(); } +#endif public sealed override void Flush() {} diff --git a/crypto/src/util/zlib/ZOutputStream.cs b/crypto/src/util/zlib/ZOutputStream.cs
index 1d2ead7b3..d9f005f69 100644 --- a/crypto/src/util/zlib/ZOutputStream.cs +++ b/crypto/src/util/zlib/ZOutputStream.cs
@@ -95,32 +95,52 @@ namespace Org.BouncyCastle.Utilities.Zlib public sealed override bool CanSeek { get { return false; } } public sealed override bool CanWrite { get { return !closed; } } +#if PORTABLE + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (closed) + return; + + DoClose(); + } + base.Dispose(disposing); + } +#else public override void Close() { - if (this.closed) + if (closed) return; - try - { - try - { - Finish(); - } - catch (IOException) - { - // Ignore - } - } - finally - { - this.closed = true; - End(); - output.Close(); - output = null; - } + DoClose(); + base.Close(); } +#endif + + private void DoClose() + { + try + { + try + { + Finish(); + } + catch (IOException) + { + // Ignore + } + } + finally + { + this.closed = true; + End(); + Platform.Dispose(output); + output = null; + } + } - public virtual void End() + public virtual void End() { if (z == null) return; diff --git a/crypto/src/x509/AttributeCertificateHolder.cs b/crypto/src/x509/AttributeCertificateHolder.cs
index 3a6af4c20..04460cd59 100644 --- a/crypto/src/x509/AttributeCertificateHolder.cs +++ b/crypto/src/x509/AttributeCertificateHolder.cs
@@ -103,7 +103,7 @@ namespace Org.BouncyCastle.X509 // TODO Allow 'objectDigest' to be null? holder = new Holder(new ObjectDigestInfo(digestedObjectType, otherObjectTypeID, - new AlgorithmIdentifier(digestAlgorithm), Arrays.Clone(objectDigest))); + new AlgorithmIdentifier(new DerObjectIdentifier(digestAlgorithm)), Arrays.Clone(objectDigest))); } /** @@ -147,7 +147,7 @@ namespace Org.BouncyCastle.X509 return odi == null ? null - : odi.DigestAlgorithm.ObjectID.Id; + : odi.DigestAlgorithm.Algorithm.Id; } } diff --git a/crypto/src/x509/PEMParser.cs b/crypto/src/x509/PEMParser.cs
index 8c117f323..28f28ee0a 100644 --- a/crypto/src/x509/PEMParser.cs +++ b/crypto/src/x509/PEMParser.cs
@@ -3,6 +3,7 @@ using System.IO; using System.Text; using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Encoders; namespace Org.BouncyCastle.X509 @@ -59,7 +60,7 @@ namespace Org.BouncyCastle.X509 while ((line = ReadLine(inStream)) != null) { - if (line.StartsWith(_header1) || line.StartsWith(_header2)) + if (Platform.StartsWith(line, _header1) || Platform.StartsWith(line, _header2)) { break; } @@ -67,7 +68,7 @@ namespace Org.BouncyCastle.X509 while ((line = ReadLine(inStream)) != null) { - if (line.StartsWith(_footer1) || line.StartsWith(_footer2)) + if (Platform.StartsWith(line, _footer1) || Platform.StartsWith(line, _footer2)) { break; } diff --git a/crypto/src/x509/SubjectPublicKeyInfoFactory.cs b/crypto/src/x509/SubjectPublicKeyInfoFactory.cs
index bb6f37831..7614321d4 100644 --- a/crypto/src/x509/SubjectPublicKeyInfoFactory.cs +++ b/crypto/src/x509/SubjectPublicKeyInfoFactory.cs
@@ -1,7 +1,4 @@ using System; -using System.IO; -using System.Collections; -using System.Text; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Asn1; @@ -167,7 +164,7 @@ namespace Org.BouncyCastle.X509 return new SubjectPublicKeyInfo(algID, new DerOctetString(keyBytes)); } - throw new ArgumentException("Class provided no convertible: " + key.GetType().FullName); + throw new ArgumentException("Class provided no convertible: " + Platform.GetTypeName(key)); } private static void ExtractBytes( diff --git a/crypto/src/x509/X509Certificate.cs b/crypto/src/x509/X509Certificate.cs
index c323fc8f1..6d7bd7a61 100644 --- a/crypto/src/x509/X509Certificate.cs +++ b/crypto/src/x509/X509Certificate.cs
@@ -237,16 +237,16 @@ namespace Org.BouncyCastle.X509 /// <returns>A byte array containg the signature of the certificate.</returns> public virtual byte[] GetSignature() { - return c.Signature.GetBytes(); + return c.GetSignatureOctets(); } - /// <summary> + /// <summary> /// A meaningful version of the Signature Algorithm. (EG SHA1WITHRSA) /// </summary> /// <returns>A sting representing the signature algorithm.</returns> public virtual string SigAlgName { - get { return SignerUtilities.GetEncodingName(c.SignatureAlgorithm.ObjectID); } + get { return SignerUtilities.GetEncodingName(c.SignatureAlgorithm.Algorithm); } } /// <summary> @@ -255,7 +255,7 @@ namespace Org.BouncyCastle.X509 /// <returns>A string containg a '.' separated object id.</returns> public virtual string SigAlgOid { - get { return c.SignatureAlgorithm.ObjectID.Id; } + get { return c.SignatureAlgorithm.Algorithm.Id; } } /// <summary> @@ -547,7 +547,7 @@ namespace Org.BouncyCastle.X509 public virtual void Verify( AsymmetricKeyParameter key) { - CheckSignature(new Asn1SignatureVerifier(c.SignatureAlgorithm, key)); + CheckSignature(new Asn1VerifierFactory(c.SignatureAlgorithm, key)); } /// <summary> @@ -557,13 +557,13 @@ namespace Org.BouncyCastle.X509 /// <returns>True if the signature is valid.</returns> /// <exception cref="Exception">If verifier provider is not appropriate or the certificate algorithm is invalid.</exception> public virtual void Verify( - ISignatureVerifierProvider verifierProvider) + IVerifierFactoryProvider verifierProvider) { - CheckSignature(verifierProvider.CreateSignatureVerifier (c.SignatureAlgorithm)); + CheckSignature(verifierProvider.CreateVerifierFactory (c.SignatureAlgorithm)); } protected virtual void CheckSignature( - ISignatureVerifier verifier) + IVerifierFactory verifier) { if (!IsAlgIDEqual(c.SignatureAlgorithm, c.TbsCertificate.Signature)) throw new CertificateException("signature algorithm in TBS cert not same as outer cert"); @@ -576,7 +576,7 @@ namespace Org.BouncyCastle.X509 streamCalculator.Stream.Write(b, 0, b.Length); - streamCalculator.Stream.Close(); + Platform.Dispose(streamCalculator.Stream); if (!((IVerifier)streamCalculator.GetResult()).IsVerified(this.GetSignature())) { @@ -586,7 +586,7 @@ namespace Org.BouncyCastle.X509 private static bool IsAlgIDEqual(AlgorithmIdentifier id1, AlgorithmIdentifier id2) { - if (!id1.ObjectID.Equals(id2.ObjectID)) + if (!id1.Algorithm.Equals(id2.Algorithm)) return false; Asn1Encodable p1 = id1.Parameters; diff --git a/crypto/src/x509/X509Crl.cs b/crypto/src/x509/X509Crl.cs
index 0679cb240..ecfb14132 100644 --- a/crypto/src/x509/X509Crl.cs +++ b/crypto/src/x509/X509Crl.cs
@@ -84,7 +84,7 @@ namespace Org.BouncyCastle.X509 public virtual void Verify( AsymmetricKeyParameter publicKey) { - Verify(new Asn1SignatureVerifierProvider(publicKey)); + Verify(new Asn1VerifierFactoryProvider(publicKey)); } /// <summary> @@ -94,13 +94,13 @@ namespace Org.BouncyCastle.X509 /// <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( - ISignatureVerifierProvider verifierProvider) + IVerifierFactoryProvider verifierProvider) { - CheckSignature(verifierProvider.CreateSignatureVerifier(c.SignatureAlgorithm)); + CheckSignature(verifierProvider.CreateVerifierFactory(c.SignatureAlgorithm)); } protected virtual void CheckSignature( - ISignatureVerifier verifier) + IVerifierFactory verifier) { if (!c.SignatureAlgorithm.Equals(c.TbsCertList.Signature)) { @@ -115,7 +115,7 @@ namespace Org.BouncyCastle.X509 streamCalculator.Stream.Write(b, 0, b.Length); - streamCalculator.Stream.Close(); + Platform.Dispose(streamCalculator.Stream); if (!((IVerifier)streamCalculator.GetResult()).IsVerified(this.GetSignature())) { @@ -211,7 +211,7 @@ namespace Org.BouncyCastle.X509 public virtual byte[] GetSignature() { - return c.Signature.GetBytes(); + return c.GetSignatureOctets(); } public virtual string SigAlgName @@ -221,7 +221,7 @@ namespace Org.BouncyCastle.X509 public virtual string SigAlgOid { - get { return c.SignatureAlgorithm.ObjectID.Id; } + get { return c.SignatureAlgorithm.Algorithm.Id; } } public virtual byte[] GetSigAlgParams() diff --git a/crypto/src/x509/X509SignatureUtil.cs b/crypto/src/x509/X509SignatureUtil.cs
index 7a4ab1448..83863aee1 100644 --- a/crypto/src/x509/X509SignatureUtil.cs +++ b/crypto/src/x509/X509SignatureUtil.cs
@@ -34,7 +34,7 @@ namespace Org.BouncyCastle.X509 // throw new SignatureException("IOException decoding parameters: " + e.Message); // } // -// if (signature.getAlgorithm().EndsWith("MGF1")) +// if (Platform.EndsWith(signature.getAlgorithm(), "MGF1")) // { // try // { @@ -55,13 +55,13 @@ namespace Org.BouncyCastle.X509 if (parameters != null && !derNull.Equals(parameters)) { - if (sigAlgId.ObjectID.Equals(PkcsObjectIdentifiers.IdRsassaPss)) + if (sigAlgId.Algorithm.Equals(PkcsObjectIdentifiers.IdRsassaPss)) { RsassaPssParameters rsaParams = RsassaPssParameters.GetInstance(parameters); - return GetDigestAlgName(rsaParams.HashAlgorithm.ObjectID) + "withRSAandMGF1"; + return GetDigestAlgName(rsaParams.HashAlgorithm.Algorithm) + "withRSAandMGF1"; } - if (sigAlgId.ObjectID.Equals(X9ObjectIdentifiers.ECDsaWithSha2)) + if (sigAlgId.Algorithm.Equals(X9ObjectIdentifiers.ECDsaWithSha2)) { Asn1Sequence ecDsaParams = Asn1Sequence.GetInstance(parameters); @@ -69,7 +69,7 @@ namespace Org.BouncyCastle.X509 } } - return sigAlgId.ObjectID.Id; + return sigAlgId.Algorithm.Id; } /** diff --git a/crypto/src/x509/X509V1CertificateGenerator.cs b/crypto/src/x509/X509V1CertificateGenerator.cs
index 2279767e3..9adebcb16 100644 --- a/crypto/src/x509/X509V1CertificateGenerator.cs +++ b/crypto/src/x509/X509V1CertificateGenerator.cs
@@ -10,6 +10,7 @@ using Org.BouncyCastle.Crypto.Operators; using Org.BouncyCastle.Math; using Org.BouncyCastle.Security; using Org.BouncyCastle.Security.Certificates; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.X509 { @@ -121,7 +122,7 @@ namespace Org.BouncyCastle.X509 /// This can be either a name or an OID, names are treated as case insensitive. /// </summary> /// <param name="signatureAlgorithm">string representation of the algorithm name</param> - [Obsolete("Not needed if Generate used with an ISignatureCalculator")] + [Obsolete("Not needed if Generate used with an ISignatureFactory")] public void SetSignatureAlgorithm( string signatureAlgorithm) { @@ -146,7 +147,7 @@ namespace Org.BouncyCastle.X509 /// </summary> /// <param name="privateKey">The private key of the issuer used to sign this certificate.</param> /// <returns>An X509Certificate.</returns> - [Obsolete("Use Generate with an ISignatureCalculator")] + [Obsolete("Use Generate with an ISignatureFactory")] public X509Certificate Generate( AsymmetricKeyParameter privateKey) { @@ -159,34 +160,34 @@ namespace Org.BouncyCastle.X509 /// <param name="privateKey">The private key of the issuer used to sign this certificate.</param> /// <param name="random">The Secure Random you want to use.</param> /// <returns>An X509Certificate.</returns> - [Obsolete("Use Generate with an ISignatureCalculator")] + [Obsolete("Use Generate with an ISignatureFactory")] public X509Certificate Generate( AsymmetricKeyParameter privateKey, SecureRandom random) { - return Generate(new Asn1SignatureCalculator(signatureAlgorithm, privateKey, random)); + return Generate(new Asn1SignatureFactory(signatureAlgorithm, privateKey, random)); } /// <summary> /// Generate a new X509Certificate using the passed in SignatureCalculator. /// </summary> - /// <param name="signatureCalculator">A signature calculator with the necessary algorithm details.</param> + /// <param name="signatureCalculatorFactory">A signature calculator factory with the necessary algorithm details.</param> /// <returns>An X509Certificate.</returns> - public X509Certificate Generate(ISignatureCalculator signatureCalculator) + public X509Certificate Generate(ISignatureFactory signatureCalculatorFactory) { - tbsGen.SetSignature ((AlgorithmIdentifier)signatureCalculator.AlgorithmDetails); + tbsGen.SetSignature ((AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails); TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate(); - IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator(); + IStreamCalculator streamCalculator = signatureCalculatorFactory.CreateCalculator(); byte[] encoded = tbsCert.GetDerEncoded(); streamCalculator.Stream.Write(encoded, 0, encoded.Length); - streamCalculator.Stream.Close(); + Platform.Dispose(streamCalculator.Stream); - return GenerateJcaObject(tbsCert, (AlgorithmIdentifier)signatureCalculator.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect()); + return GenerateJcaObject(tbsCert, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect()); } private X509Certificate GenerateJcaObject( diff --git a/crypto/src/x509/X509V2AttributeCertificate.cs b/crypto/src/x509/X509V2AttributeCertificate.cs
index cc72c23bb..c41b31239 100644 --- a/crypto/src/x509/X509V2AttributeCertificate.cs +++ b/crypto/src/x509/X509V2AttributeCertificate.cs
@@ -5,11 +5,11 @@ using System.IO; using Org.BouncyCastle.Asn1; 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.Crypto.Operators; namespace Org.BouncyCastle.X509 { @@ -147,15 +147,20 @@ namespace Org.BouncyCastle.X509 throw new CertificateNotYetValidException("certificate not valid until " + NotBefore); } + public virtual AlgorithmIdentifier SignatureAlgorithm + { + get { return cert.SignatureAlgorithm; } + } + public virtual byte[] GetSignature() { - return cert.SignatureValue.GetBytes(); + return cert.GetSignatureOctets(); } public virtual void Verify( AsymmetricKeyParameter key) { - CheckSignature(new Asn1SignatureVerifier(cert.SignatureAlgorithm, key)); + CheckSignature(new Asn1VerifierFactory(cert.SignatureAlgorithm, key)); } /// <summary> @@ -165,13 +170,13 @@ namespace Org.BouncyCastle.X509 /// <returns>True if the signature is valid.</returns> /// <exception cref="Exception">If verifier provider is not appropriate or the certificate algorithm is invalid.</exception> public virtual void Verify( - ISignatureVerifierProvider verifierProvider) + IVerifierFactoryProvider verifierProvider) { - CheckSignature(verifierProvider.CreateSignatureVerifier(cert.SignatureAlgorithm)); + CheckSignature(verifierProvider.CreateVerifierFactory(cert.SignatureAlgorithm)); } protected virtual void CheckSignature( - ISignatureVerifier verifier) + IVerifierFactory verifier) { if (!cert.SignatureAlgorithm.Equals(cert.ACInfo.Signature)) { @@ -186,7 +191,7 @@ namespace Org.BouncyCastle.X509 streamCalculator.Stream.Write(b, 0, b.Length); - streamCalculator.Stream.Close(); + Platform.Dispose(streamCalculator.Stream); } catch (IOException e) { diff --git a/crypto/src/x509/X509V2AttributeCertificateGenerator.cs b/crypto/src/x509/X509V2AttributeCertificateGenerator.cs
index b6ab45c64..bf046cd1e 100644 --- a/crypto/src/x509/X509V2AttributeCertificateGenerator.cs +++ b/crypto/src/x509/X509V2AttributeCertificateGenerator.cs
@@ -1,15 +1,15 @@ using System; using System.Collections; +using System.IO; using Org.BouncyCastle.Asn1; 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.Crypto.Operators; -using System.IO; namespace Org.BouncyCastle.X509 { @@ -73,7 +73,7 @@ namespace Org.BouncyCastle.X509 /// are treated as case insensitive. /// </summary> /// <param name="signatureAlgorithm">The algorithm name.</param> - [Obsolete("Not needed if Generate used with an ISignatureCalculator")] + [Obsolete("Not needed if Generate used with an ISignatureFactory")] public void SetSignatureAlgorithm( string signatureAlgorithm) { @@ -133,7 +133,7 @@ namespace Org.BouncyCastle.X509 /// <summary> /// Generate an X509 certificate, based on the current issuer and subject. /// </summary> - [Obsolete("Use Generate with an ISignatureCalculator")] + [Obsolete("Use Generate with an ISignatureFactory")] public IX509AttributeCertificate Generate( AsymmetricKeyParameter privateKey) { @@ -144,20 +144,20 @@ namespace Org.BouncyCastle.X509 /// Generate an X509 certificate, based on the current issuer and subject, /// using the supplied source of randomness, if required. /// </summary> - [Obsolete("Use Generate with an ISignatureCalculator")] + [Obsolete("Use Generate with an ISignatureFactory")] public IX509AttributeCertificate Generate( AsymmetricKeyParameter privateKey, SecureRandom random) { - return Generate(new Asn1SignatureCalculator(signatureAlgorithm, privateKey, random)); + return Generate(new Asn1SignatureFactory(signatureAlgorithm, privateKey, random)); } /// <summary> /// Generate a new X.509 Attribute Certificate using the passed in SignatureCalculator. /// </summary> - /// <param name="signatureCalculator">A signature calculator with the necessary algorithm details.</param> + /// <param name="signatureCalculatorFactory">A signature calculator factory with the necessary algorithm details.</param> /// <returns>An IX509AttributeCertificate.</returns> - public IX509AttributeCertificate Generate(ISignatureCalculator signatureCalculator) + public IX509AttributeCertificate Generate(ISignatureFactory signatureCalculatorFactory) { if (!extGenerator.IsEmpty) { @@ -168,15 +168,15 @@ namespace Org.BouncyCastle.X509 byte[] encoded = acInfo.GetDerEncoded(); - IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator(); + IStreamCalculator streamCalculator = signatureCalculatorFactory.CreateCalculator(); streamCalculator.Stream.Write(encoded, 0, encoded.Length); - streamCalculator.Stream.Close(); + Platform.Dispose(streamCalculator.Stream); Asn1EncodableVector v = new Asn1EncodableVector(); - v.Add(acInfo, (AlgorithmIdentifier)signatureCalculator.AlgorithmDetails); + v.Add(acInfo, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails); try { diff --git a/crypto/src/x509/X509V2CRLGenerator.cs b/crypto/src/x509/X509V2CRLGenerator.cs
index 869722219..566d50234 100644 --- a/crypto/src/x509/X509V2CRLGenerator.cs +++ b/crypto/src/x509/X509V2CRLGenerator.cs
@@ -5,12 +5,13 @@ using System.IO; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto; +using Org.BouncyCastle.Crypto.Operators; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Security; using Org.BouncyCastle.Security.Certificates; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; -using Org.BouncyCastle.Crypto.Operators; namespace Org.BouncyCastle.X509 { @@ -134,7 +135,7 @@ namespace Org.BouncyCastle.X509 /// Set the signature algorithm that will be used to sign this CRL. /// </summary> /// <param name="signatureAlgorithm"/> - [Obsolete("Not needed if Generate used with an ISignatureCalculator")] + [Obsolete("Not needed if Generate used with an ISignatureFactory")] public void SetSignatureAlgorithm( string signatureAlgorithm) { @@ -203,7 +204,7 @@ namespace Org.BouncyCastle.X509 /// </summary> /// <param name="privateKey">The private key of the issuer that is signing this certificate.</param> /// <returns>An X509Crl.</returns> - [Obsolete("Use Generate with an ISignatureCalculator")] + [Obsolete("Use Generate with an ISignatureFactory")] public X509Crl Generate( AsymmetricKeyParameter privateKey) { @@ -216,34 +217,34 @@ namespace Org.BouncyCastle.X509 /// <param name="privateKey">The private key of the issuer that is signing this certificate.</param> /// <param name="random">Your Secure Random instance.</param> /// <returns>An X509Crl.</returns> - [Obsolete("Use Generate with an ISignatureCalculator")] + [Obsolete("Use Generate with an ISignatureFactory")] public X509Crl Generate( AsymmetricKeyParameter privateKey, SecureRandom random) { - return Generate(new Asn1SignatureCalculator(signatureAlgorithm, privateKey, random)); + return Generate(new Asn1SignatureFactory(signatureAlgorithm, privateKey, random)); } /// <summary> /// Generate a new X509Crl using the passed in SignatureCalculator. /// </summary> - /// <param name="signatureCalculator">A signature calculator with the necessary algorithm details.</param> + /// <param name="signatureCalculatorFactory">A signature calculator factory with the necessary algorithm details.</param> /// <returns>An X509Crl.</returns> - public X509Crl Generate(ISignatureCalculator signatureCalculator) + public X509Crl Generate(ISignatureFactory signatureCalculatorFactory) { - tbsGen.SetSignature((AlgorithmIdentifier)signatureCalculator.AlgorithmDetails); + tbsGen.SetSignature((AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails); TbsCertificateList tbsCertList = GenerateCertList(); - IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator(); + IStreamCalculator streamCalculator = signatureCalculatorFactory.CreateCalculator(); byte[] encoded = tbsCertList.GetDerEncoded(); streamCalculator.Stream.Write(encoded, 0, encoded.Length); - streamCalculator.Stream.Close(); + Platform.Dispose(streamCalculator.Stream); - return GenerateJcaObject(tbsCertList, (AlgorithmIdentifier)signatureCalculator.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect()); + return GenerateJcaObject(tbsCertList, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect()); } private TbsCertificateList GenerateCertList() diff --git a/crypto/src/x509/X509V3CertificateGenerator.cs b/crypto/src/x509/X509V3CertificateGenerator.cs
index d8cdc7521..bc619c37b 100644 --- a/crypto/src/x509/X509V3CertificateGenerator.cs +++ b/crypto/src/x509/X509V3CertificateGenerator.cs
@@ -1,15 +1,14 @@ using System; using System.Collections; -using System.IO; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Operators; -using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Security; using Org.BouncyCastle.Security.Certificates; +using Org.BouncyCastle.Utilities; using Org.BouncyCastle.X509.Extension; namespace Org.BouncyCastle.X509 @@ -112,7 +111,7 @@ namespace Org.BouncyCastle.X509 /// Set the signature algorithm that will be used to sign this certificate. /// </summary> /// <param name="signatureAlgorithm"/> - [Obsolete("Not needed if Generate used with an ISignatureCalculator")] + [Obsolete("Not needed if Generate used with an ISignatureFactory")] public void SetSignatureAlgorithm( string signatureAlgorithm) { @@ -277,7 +276,7 @@ namespace Org.BouncyCastle.X509 /// </summary> /// <param name="privateKey">The private key of the issuer that is signing this certificate.</param> /// <returns>An X509Certificate.</returns> - [Obsolete("Use Generate with an ISignatureCalculator")] + [Obsolete("Use Generate with an ISignatureFactory")] public X509Certificate Generate( AsymmetricKeyParameter privateKey) { @@ -290,22 +289,22 @@ namespace Org.BouncyCastle.X509 /// <param name="privateKey">The private key of the issuer that is signing this certificate.</param> /// <param name="random">You Secure Random instance.</param> /// <returns>An X509Certificate.</returns> - [Obsolete("Use Generate with an ISignatureCalculator")] + [Obsolete("Use Generate with an ISignatureFactory")] public X509Certificate Generate( AsymmetricKeyParameter privateKey, SecureRandom random) { - return Generate(new Asn1SignatureCalculator(signatureAlgorithm, privateKey, random)); + return Generate(new Asn1SignatureFactory(signatureAlgorithm, privateKey, random)); } /// <summary> /// Generate a new X509Certificate using the passed in SignatureCalculator. /// </summary> - /// <param name="signatureCalculator">A signature calculator with the necessary algorithm details.</param> + /// <param name="signatureCalculatorFactory">A signature calculator factory with the necessary algorithm details.</param> /// <returns>An X509Certificate.</returns> - public X509Certificate Generate(ISignatureCalculator signatureCalculator) + public X509Certificate Generate(ISignatureFactory signatureCalculatorFactory) { - tbsGen.SetSignature ((AlgorithmIdentifier)signatureCalculator.AlgorithmDetails); + tbsGen.SetSignature ((AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails); if (!extGenerator.IsEmpty) { @@ -314,15 +313,15 @@ namespace Org.BouncyCastle.X509 TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate(); - IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator(); + IStreamCalculator streamCalculator = signatureCalculatorFactory.CreateCalculator(); byte[] encoded = tbsCert.GetDerEncoded(); - streamCalculator.Stream.Write (encoded, 0, encoded.Length); + streamCalculator.Stream.Write(encoded, 0, encoded.Length); - streamCalculator.Stream.Close (); + Platform.Dispose(streamCalculator.Stream); - return GenerateJcaObject(tbsCert, (AlgorithmIdentifier)signatureCalculator.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect()); + return GenerateJcaObject(tbsCert, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect()); } private X509Certificate GenerateJcaObject(